In your xampppath\apache\conf\extra open file httpd-xampp.conf and find the below tag:
# Close XAMPP sites here
<LocationMatch "^/(?i:(?:xampp|licenses|phpmyadmin|webalizer|server-status|server-info))">
Order deny,allow
Deny from all
Allow from ::1 127.0.0.0/8
ErrorDocument 403 /error/HTTP_XAMPP_FORBIDDEN.html.var
</LocationMatch>
and add
"Allow from all"
after Allow from ::1 127.0.0.0/8 {line}
Restart xampp, and you are done.
In later versions of Xampp
...you can simply remove this part
#
# New XAMPP security concept
#
<LocationMatch "^/(?i:(?:xampp|security|licenses|phpmyadmin|webalizer|server-status|server-info))">
Require local
ErrorDocument 403 /error/XAMPP_FORBIDDEN.html.var
</LocationMatch>
from the same file and it should work over the local network.
Probably the quickest way to retrieve only the key name:
mydic = {}
mydic['key_name'] = 'value_name'
print mydic.items()[0][0]
Result:
key_name
Converts the dictionary
into a list
then it lists the first element which is the whole dict
then it lists the first value of that element which is: key_name
Without knowing what the actual error you are getting is I would guess it is missing quotes. try the following:
mysql_query("UPDATE blogEntry SET content = '$udcontent', title = '$udtitle' WHERE id = '$id'")
The problem you'll face is that there's two types of PEM formatted keys: PKCS8 and SSLeay. It doesn't help that OpenSSL seems to use both depending on the command:
The usual openssl genrsa
command will generate a SSLeay format PEM. An export from an PKCS12 file with openssl pkcs12 -in file.p12
will create a PKCS8 file.
The latter PKCS8 format can be opened natively in Java using PKCS8EncodedKeySpec
. SSLeay formatted keys, on the other hand, can not be opened natively.
To open SSLeay private keys, you can either use BouncyCastle provider as many have done before or Not-Yet-Commons-SSL have borrowed a minimal amount of necessary code from BouncyCastle to support parsing PKCS8 and SSLeay keys in PEM and DER format: http://juliusdavies.ca/commons-ssl/pkcs8.html. (I'm not sure if Not-Yet-Commons-SSL will be FIPS compliant)
By inference from the OpenSSL man pages, key headers for two formats are as follows:
PKCS8 Format
Non-encrypted: -----BEGIN PRIVATE KEY-----
Encrypted: -----BEGIN ENCRYPTED PRIVATE KEY-----
SSLeay Format
-----BEGIN RSA PRIVATE KEY-----
(These seem to be in contradiction to other answers but I've tested OpenSSL's output using PKCS8EncodedKeySpec
. Only PKCS8 keys, showing ----BEGIN PRIVATE KEY-----
work natively)
I don't know that regex would handle something like that very well. Try something like this
line = line.Trim();
if(line.StartsWith("for") && line.EndsWith(";")){
//your code here
}
I had this error in code that looked like this:
int A = 1;
int B = A;
The fix is to change it to this
int A = 1;
#define B A
The compiler assigns a location in memory to a variable. The second is trying a assign a second variable to the same location as the first - which makes no sense. Using the macro preprocessor solves the problem.
The results from json.Unmarshal
(into var data interface{}
) do not directly match your Go type and variable declarations. For example,
package main
import (
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
"os"
)
type Tracks struct {
Toptracks []Toptracks_info
}
type Toptracks_info struct {
Track []Track_info
Attr []Attr_info
}
type Track_info struct {
Name string
Duration string
Listeners string
Mbid string
Url string
Streamable []Streamable_info
Artist []Artist_info
Attr []Track_attr_info
}
type Attr_info struct {
Country string
Page string
PerPage string
TotalPages string
Total string
}
type Streamable_info struct {
Text string
Fulltrack string
}
type Artist_info struct {
Name string
Mbid string
Url string
}
type Track_attr_info struct {
Rank string
}
func get_content() {
// json data
url := "http://ws.audioscrobbler.com/2.0/?method=geo.gettoptracks&api_key=c1572082105bd40d247836b5c1819623&format=json&country=Netherlands"
url += "&limit=1" // limit data for testing
res, err := http.Get(url)
if err != nil {
panic(err.Error())
}
body, err := ioutil.ReadAll(res.Body)
if err != nil {
panic(err.Error())
}
var data interface{} // TopTracks
err = json.Unmarshal(body, &data)
if err != nil {
panic(err.Error())
}
fmt.Printf("Results: %v\n", data)
os.Exit(0)
}
func main() {
get_content()
}
Output:
Results: map[toptracks:map[track:map[name:Get Lucky (feat. Pharrell Williams) listeners:1863 url:http://www.last.fm/music/Daft+Punk/_/Get+Lucky+(feat.+Pharrell+Williams) artist:map[name:Daft Punk mbid:056e4f3e-d505-4dad-8ec1-d04f521cbb56 url:http://www.last.fm/music/Daft+Punk] image:[map[#text:http://userserve-ak.last.fm/serve/34s/88137413.png size:small] map[#text:http://userserve-ak.last.fm/serve/64s/88137413.png size:medium] map[#text:http://userserve-ak.last.fm/serve/126/88137413.png size:large] map[#text:http://userserve-ak.last.fm/serve/300x300/88137413.png size:extralarge]] @attr:map[rank:1] duration:369 mbid: streamable:map[#text:1 fulltrack:0]] @attr:map[country:Netherlands page:1 perPage:1 totalPages:500 total:500]]]
It's an old question but I think it is still valid.
Since there is no CONTAINS function, why not declare it in VBA? The code below uses the VBA Instr function, which looks for a substring in a string. It returns 0 when the string is not found.
Public Function CONTAINS(TextString As String, SubString As String) As Integer
CONTAINS = InStr(1, TextString, SubString)
End Function
This is another related post Lombok not working with IntelliJ 2020.3 Community Edition which may resolve the question when user use lombook
and IntelliJ 2020.3 CommunityEdition
.
Here is a working example:
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.text.DateFormat;
import java.util.Date;
public class j4496359 {
public static void main(String[] args) {
try {
String target = "Thu Sep 28 20:29:30 JST 2000";
DateFormat df = new SimpleDateFormat("EEE MMM dd kk:mm:ss zzz yyyy");
Date result = df.parse(target);
System.out.println(result);
} catch (ParseException pe) {
pe.printStackTrace();
}
}
}
Will print:
Thu Sep 28 13:29:30 CEST 2000
The VPATH option might come in handy, which tells make what directories to look in for source code. You'd still need a -I option for each include path, though. An example:
CXXFLAGS=-Ipart1/inc -Ipart2/inc -Ipart3/inc
VPATH=part1/src:part2/src:part3/src
OutputExecutable: part1api.o part2api.o part3api.o
This will automatically find the matching partXapi.cpp files in any of the VPATH specified directories and compile them. However, this is more useful when your src directory is broken into subdirectories. For what you describe, as others have said, you are probably better off with a makefile for each part, especially if each part can stand alone.
I think in terms of keeping people happy during/ post switch over, one of things to get across early is just how private a local branch can be in Git, and how much freedom that gives them to make mistakes. Get them all to clone themselves a few private branches from the current code and then go wild in there, experimenting. Rename some files, check stuff in, merge things from another branch, rewind history, rebase one set of changes on top of another, and so on. Show how even their worst accidents locally have no consequences for their colleagues. What you want is a situation where developers feel safe, so they can learn faster (since Git has a steep learning curve that's important) and then eventually so that they're more effective as developers.
When you're trying to learn a centralised tool, obviously you will be worried about making some goof that causes problems for other users of the repository. The fear of embarrassment alone is enough to discourage people from experimenting. Even having a special "training" repository doesn't help, because inevitably developers will encounter a situation in the production system that they never saw during training, and so they're back to worrying.
But Git's distributed nature does away with this. You can try any experiment in a local branch, and if it goes horribly wrong, just throw the branch away and nobody needs to know. Since you can create a local branch of anything, you can replicate a problem you're seeing with the real live repository, yet have no danger of "breaking the build" or otherwise making a fool of yourself. You can check absolutely everything in, as soon as you've done it, no trying to batch work up into neat little packages. So not just the two major code changes you spent four hours on today, but also that build fix that you remembered half way through, and the spelling mistake in the documentation you spotted while explaining something to a colleague, and so on. And if the major changes are abandoned because the project is changing direction, you can cherry pick the build fix and the spelling mistake out of your branch and keep those with no hassle.
try to add this section in your web.config file on web server, sometimes it happens with php pages:
<httpProtocol>
<customHeaders>
<clear />
<add name="X-UA-Compatible" value="IE=edge" />
</customHeaders>
</httpProtocol>
If you want to extract a raw-ish value from a HSSF cell, you can use something like this code fragment:
CellBase base = (CellBase) cell;
CellType cellType = cell.getCellType();
base.setCellType(CellType.STRING);
String result = cell.getStringCellValue();
base.setCellType(cellType);
At least for strings that are completely composed of digits (and automatically converted to numbers by Excel), this returns the original string (e.g. "12345"
) instead of a fractional value (e.g. "12345.0"
). Note that setCellType
is available in interface Cell
(as of v. 4.1) but deprecated and announced to be eliminated in v 5.x, whereas this method is still available in class CellBase
. Obviously, it would be nicer either to have getRawValue
in the Cell
interface or at least to be able use getStringCellValue
on non STRING cell types. Unfortunately, all replacements of setCellType
mentioned in the description won't cover this use case (maybe a member of the POI dev team reads this answer).
You can simply request https://graph.facebook.com/me?access_token=xxxxxxxxxxxxxxxxx if you get an error, the token is invalid. If you get a JSON object with an id property then it is valid.
Unfortunately this will only tell you if your token is valid, not if it came from your app.
You need the ?Rscript
command to run an R script from the terminal.
Check out http://stat.ethz.ch/R-manual/R-devel/library/utils/html/Rscript.html
Example
## example #! script for a Unix-alike
#! /path/to/Rscript --vanilla --default-packages=utils
args <- commandArgs(TRUE)
res <- try(install.packages(args))
if(inherits(res, "try-error")) q(status=1) else q()
Depending on the situation and or your style, you might also wanna use print inside your <%
%>
tags, as it allows for direct output. Like:
<% if (typeof(id) != "undefined") {
print(id);
}
else {
print('new Model');
} %>
And for the original snippet with some concatenation:
<% if (typeof(date) != "undefined") {
print('<span class="date">' + date + '</span>');
} %>
import scala.io.Source
object Demo {
def main(args: Array[String]): Unit = {
val ipfileStream = getClass.getResourceAsStream("/folder/a-words.txt")
val readlines = Source.fromInputStream(ipfileStream).getLines
readlines.foreach(readlines => println(readlines))
}
}
Like others have mentioned, a functor is an object that acts like a function, i.e. it overloads the function call operator.
Functors are commonly used in STL algorithms. They are useful because they can hold state before and between function calls, like a closure in functional languages. For example, you could define a MultiplyBy
functor that multiplies its argument by a specified amount:
class MultiplyBy {
private:
int factor;
public:
MultiplyBy(int x) : factor(x) {
}
int operator () (int other) const {
return factor * other;
}
};
Then you could pass a MultiplyBy
object to an algorithm like std::transform:
int array[5] = {1, 2, 3, 4, 5};
std::transform(array, array + 5, array, MultiplyBy(3));
// Now, array is {3, 6, 9, 12, 15}
Another advantage of a functor over a pointer to a function is that the call can be inlined in more cases. If you passed a function pointer to transform
, unless that call got inlined and the compiler knows that you always pass the same function to it, it can't inline the call through the pointer.
Use CopyOnWriteArrayList
and if you want to remove it, do the following:
for (Iterator<String> it = userList.iterator(); it.hasNext() ;)
{
if (wordsToRemove.contains(word))
{
it.remove();
}
}
You can accomplish this as long emptyStrings = s.filter(s->!s.isEmpty()).count();
handle = open(path.rstrip("/") + "/" + filename.lstrip("/"), 'wb')
ftp.retrbinary('RETR %s' % filename, handle.write)
You could also use =COUNTA(A1:A200)
which requires no conditions.
From Google Support:
COUNTA counts all values in a dataset, including those which appear more than once and text values (including zero-length strings and whitespace). To count unique values, use COUNTUNIQUE.
You can get the values for the width and height of the browser using the following:
$(window).height();
$(window).width();
To get notified when the browser is resized, use this bind callback:
$(window).resize(function() {
// Do something
});
SQLite is database engine, .sqlite
or .db
should be a database. If you don't need to program anything, you can use a GUI like sqlitebrowser or anything like that to view the database contents.
There is also spatialite, https://www.gaia-gis.it/fossil/spatialite_gui/index
This is working func for an objects comparison. In some cases you might have lot of fields to compare. Simply loop the array and call this function with a existing items and new item.
var objectsEqual = function (object1, object2) {
if(!object1 || !object2)
return false;
var result = true;
var arrayObj1 = _.keys(object1);
var currentKey = "";
for (var i = 0; i < arrayObj1.length; i++) {
currentKey = arrayObj1[i];
if (object1[currentKey] !== null && object2[currentKey] !== null)
if (!_.has(object2, currentKey) ||
!_.isEqual(object1[currentKey].toUpperCase(), object2[currentKey].toUpperCase()))
return false;
}
return result;
};
I had this error while writing a Windows Service. I was running Visual Studio as Administrator so that my post build commands would automatically install my service. I noticed that when I closed everything and ran VS normally (Not as Administrator) it let me add the references just fine with no error.
Hope this solution works for you.
Why not just create a 1dp high view with a background color? Then it can be easily placed where you want.
Simply: DO NOT DO IT. Http Content within a HTTPS page is inherently insecure. Point. This is why IE shows a warning. Getting rid of the warning is a stupid hogwash approach.
Instead, a HTTPS page should only have HTTPS content. Make sure the content can be loaded via HTTPS, too, and reference it via https if the page is loaded via https. For external content this will mean loading and caching the elements locally so that they are available via https - sure. No way around that, sadly.
The warning is there for a good reason. Seriously. Spend 5 minutes thinking how you could take over a https shown page with custom content - you will be surprised.
lookup only works on localhost. If you want to retrieve variables from a variables file you made remotely use include_vars: {{ varfile }}
. Contents of {{ varfile }}
should be a dictionary of the form {"key":"value"}
, you will find ansible gives you trouble if you include a space after the colon.
assuming you want to find a value in a numpy array, I guess something like this might work:
Numpy.where(arr=="value")[0]
Here's my attempt at a comprehensive answer from the dplyr perspective, following the broad outline of Arun's answer (but somewhat rearranged based on differing priorities).
There is some subjectivity to syntax, but I stand by my statement that the concision of data.table makes it harder to learn and harder to read. This is partly because dplyr is solving a much easier problem!
One really important thing that dplyr does for you is that it constrains your options. I claim that most single table problems can be solved with just five key verbs filter, select, mutate, arrange and summarise, along with a "by group" adverb. That constraint is a big help when you're learning data manipulation, because it helps order your thinking about the problem. In dplyr, each of these verbs is mapped to a single function. Each function does one job, and is easy to understand in isolation.
You create complexity by piping these simple operations together with
%>%
. Here's an example from one of the posts Arun linked
to:
diamonds %>%
filter(cut != "Fair") %>%
group_by(cut) %>%
summarize(
AvgPrice = mean(price),
MedianPrice = as.numeric(median(price)),
Count = n()
) %>%
arrange(desc(Count))
Even if you've never seen dplyr before (or even R!), you can still get
the gist of what's happening because the functions are all English
verbs. The disadvantage of English verbs is that they require more typing than
[
, but I think that can be largely mitigated by better autocomplete.
Here's the equivalent data.table code:
diamondsDT <- data.table(diamonds)
diamondsDT[
cut != "Fair",
.(AvgPrice = mean(price),
MedianPrice = as.numeric(median(price)),
Count = .N
),
by = cut
][
order(-Count)
]
It's harder to follow this code unless you're already familiar with
data.table. (I also couldn't figure out how to indent the repeated [
in a way that looks good to my eye). Personally, when I look at code I
wrote 6 months ago, it's like looking at a code written by a stranger,
so I've come to prefer straightforward, if verbose, code.
Two other minor factors that I think slightly decrease readability:
Since almost every data table operation uses [
you need additional
context to figure out what's happening. For example, is x[y]
joining two data tables or extracting columns from a data frame?
This is only a small issue, because in well-written code the
variable names should suggest what's happening.
I like that group_by()
is a separate operation in dplyr. It
fundamentally changes the computation so I think should be obvious
when skimming the code, and it's easier to spot group_by()
than
the by
argument to [.data.table
.
I also like that the the pipe
isn't just limited to just one package. You can start by tidying your
data with
tidyr, and
finish up with a plot in ggvis. And you're
not limited to the packages that I write - anyone can write a function
that forms a seamless part of a data manipulation pipe. In fact, I
rather prefer the previous data.table code rewritten with %>%
:
diamonds %>%
data.table() %>%
.[cut != "Fair",
.(AvgPrice = mean(price),
MedianPrice = as.numeric(median(price)),
Count = .N
),
by = cut
] %>%
.[order(-Count)]
And the idea of piping with %>%
is not limited to just data frames and
is easily generalised to other contexts: interactive web
graphics, web
scraping,
gists, run-time
contracts, ...)
I've lumped these together, because, to me, they're not that important. Most R users work with well under 1 million rows of data, and dplyr is sufficiently fast enough for that size of data that you're not aware of processing time. We optimise dplyr for expressiveness on medium data; feel free to use data.table for raw speed on bigger data.
The flexibility of dplyr also means that you can easily tweak performance characteristics using the same syntax. If the performance of dplyr with the data frame backend is not good enough for you, you can use the data.table backend (albeit with a somewhat restricted set of functionality). If the data you're working with doesn't fit in memory, then you can use a database backend.
All that said, dplyr performance will get better in the long-term. We'll definitely implement some of the great ideas of data.table like radix ordering and using the same index for joins & filters. We're also working on parallelisation so we can take advantage of multiple cores.
A few things that we're planning to work on in 2015:
the readr
package, to make it easy to get files off disk and in
to memory, analogous to fread()
.
More flexible joins, including support for non-equi-joins.
More flexible grouping like bootstrap samples, rollups and more
I'm also investing time into improving R's database connectors, the ability to talk to web apis, and making it easier to scrape html pages.
Slight change to the FastArray from above:
'pushtest.vbs
imax = 10000000
value = "Testvalue"
s = imax & " of """ & value & """"
t0 = timer 'Fast array
a = array()
ub = UBound(a)
For i = 0 To imax
If i>ub Then
ReDim Preserve a(Int((ub+10)*1.1))
ub = UBound(a)
End If
a(i) = value
Next
ReDim Preserve a(i-1)
s = s & "[FastArr " & FormatNumber(timer - t0, 3, -1) & "]"
MsgBox s
There is no point in checking UBound(a)
in every cycle of the for if we know exactly when it changes.
I've changed it so that it checks does UBound(a)
just before the for starts and then only every time the ReDim
is called
On my computer the old method took 7.52 seconds for an imax of 10 millions.
The new method took 5.29 seconds for an imax of also 10 millions, which signifies a performance increase of over 20% (for 10 millions tries, obviously this percentage has a direct relationship to the number of tries)
Since pip
is an executable and which
returns path of executables or filenames in environment. It is correct. Pip module is installed in site-packages but the executable is installed in bin.
You must be providing the wrong path to the debug.keystore
file.
Follow these steps to get the correct path and complete your command:
And finally, use the path you just copied from Step 3 to construct your command:
For example, in my case, it would be:
C:\Program Files\Java\jre7\bin>keytool -list -v -keystore "C:\Users\Siddharth Lele.android\debug.keystore" -alias androiddebugkey -storepass android -keypass android
UPDATED:
If you had already followed the steps mentioned above, the only other solution is to delete the debug.keystore
and let Eclipse recreate it for you.
Step 1: Go to the path where your keystore is stored. In your case, C:\Users\Suresh\.android\debug.keystore
Step 2: Close and restart Eclipse.
Step 3 (Optional): You may need to clean your project before the debug.keystore
is created again.
Source: http://www.coderanch.com/t/440920/Security/KeyTool-genkeypair-exception-Keystore-file
You can refer to this for the part about deleting your debug.keystore
file: "Debug certificate expired" error in Eclipse Android plugins
?legend
will tell you:
Arguments
x
, y
the x
and y
co-ordinates to be used to position the legend. They can be specified by keyword or in any way which is accepted by xy.coords
: See ‘Details’.
Details:
Arguments x
, y
, legend are interpreted in a non-standard way to allow the coordinates to be specified via one or two arguments. If legend is missing and y
is not numeric, it is assumed that the second argument is intended to be legend and that the first argument specifies the coordinates.
The coordinates can be specified in any way which is accepted by xy.coords
. If this gives the coordinates of one point, it is used as the top-left coordinate of the rectangle containing the legend. If it gives the coordinates of two points, these specify opposite corners of the rectangle (either pair of corners, in any order).
The location may also be specified by setting x
to a single keyword from the list bottomright
, bottom
, bottomleft
, left
, topleft
, top
, topright
, right
and center
. This places the legend on the inside of the plot frame at the given location. Partial argument matching is used. The optional inset argument specifies how far the legend is inset from the plot margins. If a single value is given, it is used for both margins; if two values are given, the first is used for x- distance, the second for y-distance.
Does your fix not work? I'm not sure if I understand the question correctly - do you have a demo page? You could try:
if (location.hash) {
setTimeout(function() {
window.scrollTo(0, 0);
}, 1);
}
Edit: tested and works in Firefox, IE & Chrome on Windows.
Edit 2: move setTimeout()
inside if
block, props @vsync.
if
is not a loop structure, so you cannot "break out of it".
You can, however, break out of the foreach
by simply calling break
. In your example it has the desired effect:
$device = "wanted";
foreach($equipxml as $equip) {
$current_device = $equip->xpath("name");
if ( $current_device[0] == $device ) {
// found a match in the file
$nodeid = $equip->id;
// will leave the foreach loop and also the if statement
break;
some_function(); // never reached!
}
another_function(); // not executed after match/break
}
Just for completeness for others that stumble upon this question looking for an answer..
break
takes an optional argument, which defines how many loop structures it should break. Example:
foreach (array('1','2','3') as $a) {
echo "$a ";
foreach (array('3','2','1') as $b) {
echo "$b ";
if ($a == $b) {
break 2; // this will break both foreach loops
}
}
echo ". "; // never reached!
}
echo "!";
Resulting output:
1 3 2 1 !
Couldn't you just call the following replaceing the {zipcode} with the zip code or city and state http://maps.googleapis.com/maps/api/geocode/json?address={zipcode}
Here is a link with a How To Geocode using JavaScript: Geocode walk-thru. If you need the specific lat/lng numbers call geometry.location.lat() or geometry.location.lng() (API for google.maps.LatLng class)
EXAMPLE to get lat/lng:
var lat = '';
var lng = '';
var address = {zipcode} or {city and state};
geocoder.geocode( { 'address': address}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
lat = results[0].geometry.location.lat();
lng = results[0].geometry.location.lng();
});
} else {
alert("Geocode was not successful for the following reason: " + status);
}
});
alert('Latitude: ' + lat + ' Logitude: ' + lng);
One answer is to hackishly add some get query parameter like has been suggested.
A better answer is to emit a couple of extra options in your HTTP header.
Pragma: no-cache
Expires: Fri, 30 Oct 1998 14:19:41 GMT
Cache-Control: no-cache, must-revalidate
By providing a date in the past, it won't be cached by the browser. Cache-Control
was added in HTTP/1.1 and the must-revalidate tag indicates that proxies should never serve up an old image even under extenuating circumstances, and the Pragma: no-cache
isn't really necessary for current modern browsers/caches but may help with some crufty broken old implementations.
Eclipse's JPA 2.0 support through Dali (which is included in "Eclipse IDE for JEE Developers") has its own metamodel generator integrated with Eclipse.
This should work on any JPA provider as the generated classes are standard.
Also see here.
The SyntaxError: unexpected EOF while parsing
means that the end of your source code was reached before all code blocks were completed. A code block starts with a statement like for i in range(100):
and requires at least one line afterwards that contains code that should be in it.
It seems like you were executing your program line by line in the ipython console. This works for single statements like a = 3
but not for code blocks like for loops. See the following example:
In [1]: for i in range(100):
File "<ipython-input-1-ece1e5c2587f>", line 1
for i in range(100):
^
SyntaxError: unexpected EOF while parsing
To avoid this error, you have to enter the whole code block as a single input:
In [2]: for i in range(5):
...: print(i, end=', ')
0, 1, 2, 3, 4,
I'm answering on specific to this error code(08s01).
usually, MySql close socket connections are some interval of time that is wait_timeout defined on MySQL server-side which by default is 8hours. so if a connection will timeout after this time and the socket will throw an exception which SQLState is "08s01".
1.use connection pool to execute Query, make sure the pool class has a function to make an inspection of the connection members before it goes time_out.
2.give a value of <wait_timeout> greater than the default, but the largest value is 24 days
3.use another parameter in your connection URL, but this method is not recommended, and maybe deprecated.
Thanks @Enrico for the answer.
Note if you're using virtualenv you will have several more .pyc
files within the directory you're currently in, which will be captured by his find command.
For example:
./app.pyc
./lib/python2.7/_weakrefset.pyc
./lib/python2.7/abc.pyc
./lib/python2.7/codecs.pyc
./lib/python2.7/copy_reg.pyc
./lib/python2.7/site-packages/alembic/__init__.pyc
./lib/python2.7/site-packages/alembic/autogenerate/__init__.pyc
./lib/python2.7/site-packages/alembic/autogenerate/api.pyc
I suppose it's harmless to remove all the files, but if you only want to remove the .pyc
files in your main directory, then just do
find "*.pyc" -exec git rm -f "{}" \;
This will remove just the app.pyc
file from the git repository.
To make an Ajax request using jQuery you can do this by the following code.
HTML:
<form id="foo">
<label for="bar">A bar</label>
<input id="bar" name="bar" type="text" value="" />
<input type="submit" value="Send" />
</form>
<!-- The result of the search will be rendered inside this div -->
<div id="result"></div>
JavaScript:
Method 1
/* Get from elements values */
var values = $(this).serialize();
$.ajax({
url: "test.php",
type: "post",
data: values ,
success: function (response) {
// You will get response from your PHP page (what you echo or print)
},
error: function(jqXHR, textStatus, errorThrown) {
console.log(textStatus, errorThrown);
}
});
Method 2
/* Attach a submit handler to the form */
$("#foo").submit(function(event) {
var ajaxRequest;
/* Stop form from submitting normally */
event.preventDefault();
/* Clear result div*/
$("#result").html('');
/* Get from elements values */
var values = $(this).serialize();
/* Send the data using post and put the results in a div. */
/* I am not aborting the previous request, because it's an
asynchronous request, meaning once it's sent it's out
there. But in case you want to abort it you can do it
by abort(). jQuery Ajax methods return an XMLHttpRequest
object, so you can just use abort(). */
ajaxRequest= $.ajax({
url: "test.php",
type: "post",
data: values
});
/* Request can be aborted by ajaxRequest.abort() */
ajaxRequest.done(function (response, textStatus, jqXHR){
// Show successfully for submit message
$("#result").html('Submitted successfully');
});
/* On failure of request this function will be called */
ajaxRequest.fail(function (){
// Show error
$("#result").html('There is error while submit');
});
The .success()
, .error()
, and .complete()
callbacks are deprecated as of jQuery 1.8. To prepare your code for their eventual removal, use .done()
, .fail()
, and .always()
instead.
MDN: abort()
. If the request has been sent already, this method will abort the request.
So we have successfully send an Ajax request, and now it's time to grab data to server.
PHP
As we make a POST request in an Ajax call (type: "post"
), we can now grab data using either $_REQUEST
or $_POST
:
$bar = $_POST['bar']
You can also see what you get in the POST request by simply either. BTW, make sure that $_POST
is set. Otherwise you will get an error.
var_dump($_POST);
// Or
print_r($_POST);
And you are inserting a value into the database. Make sure you are sensitizing or escaping All requests (whether you made a GET or POST) properly before making the query. The best would be using prepared statements.
And if you want to return any data back to the page, you can do it by just echoing that data like below.
// 1. Without JSON
echo "Hello, this is one"
// 2. By JSON. Then here is where I want to send a value back to the success of the Ajax below
echo json_encode(array('returned_val' => 'yoho'));
And then you can get it like:
ajaxRequest.done(function (response){
alert(response);
});
There are a couple of shorthand methods. You can use the below code. It does the same work.
var ajaxRequest= $.post("test.php", values, function(data) {
alert(data);
})
.fail(function() {
alert("error");
})
.always(function() {
alert("finished");
});
Error:(30, 13) Failed to resolve: com.google.firebase:firebase-auth:9.6.1
If you ever get this error and you are using Android studio 2.2 that comes with firebase component integrated in it which has libraries version 9.6.0 by default and you are adding the latest dependencies like 9.6.1 . You might need to downgrade com.google.firebase:firebase-auth:9.6.1
to com.google.firebase:firebase-auth:9.6.0
Or check the library version of your pre-installed firebase and make sure it is of the same version with the new library you are trying to add or added to your project.
Solution:
function getSortedObject(object) {
var sortedObject = {};
var keys = Object.keys(object);
keys.sort();
for (var i = 0, size = keys.length; i < size; i++) {
key = keys[i];
value = object[key];
sortedObject[key] = value;
}
return sortedObject;
}
// Test run
getSortedObject({d: 4, a: 1, b: 2, c: 3});
Explanation:
Many JavaScript runtimes store values inside an object in the order in which they are added.
To sort the properties of an object by their keys you can make use of the Object.keys function which will return an array of keys. The array of keys can then be sorted by the Array.prototype.sort() method which sorts the elements of an array in place (no need to assign them to a new variable).
Once the keys are sorted you can start using them one-by-one to access the contents of the old object to fill a new object (which is now sorted).
Below is an example of the procedure (you can test it in your targeted browsers):
/**_x000D_
* Returns a copy of an object, which is ordered by the keys of the original object._x000D_
*_x000D_
* @param {Object} object - The original object._x000D_
* @returns {Object} Copy of the original object sorted by keys._x000D_
*/_x000D_
function getSortedObject(object) {_x000D_
// New object which will be returned with sorted keys_x000D_
var sortedObject = {};_x000D_
_x000D_
// Get array of keys from the old/current object_x000D_
var keys = Object.keys(object);_x000D_
// Sort keys (in place)_x000D_
keys.sort();_x000D_
_x000D_
// Use sorted keys to copy values from old object to the new one_x000D_
for (var i = 0, size = keys.length; i < size; i++) {_x000D_
key = keys[i];_x000D_
value = object[key];_x000D_
sortedObject[key] = value;_x000D_
}_x000D_
_x000D_
// Return the new object_x000D_
return sortedObject;_x000D_
}_x000D_
_x000D_
/**_x000D_
* Test run_x000D_
*/_x000D_
var unsortedObject = {_x000D_
d: 4,_x000D_
a: 1,_x000D_
b: 2,_x000D_
c: 3_x000D_
};_x000D_
_x000D_
var sortedObject = getSortedObject(unsortedObject);_x000D_
_x000D_
for (var key in sortedObject) {_x000D_
var text = "Key: " + key + ", Value: " + sortedObject[key];_x000D_
var paragraph = document.createElement('p');_x000D_
paragraph.textContent = text;_x000D_
document.body.appendChild(paragraph);_x000D_
}
_x000D_
Note: Object.keys is an ECMAScript 5.1 method but here is a polyfill for older browsers:
if (!Object.keys) {
Object.keys = function (object) {
var key = [];
var property = undefined;
for (property in object) {
if (Object.prototype.hasOwnProperty.call(object, property)) {
key.push(property);
}
}
return key;
};
}
Jquery code which contains simple ajax :
$("#product").on("input", function(event) {
var data=$("#nameform").serialize();
$.post("./__partails/search-productbyCat.php",data,function(e){
$(".result").empty().append(e);
});
});
Html elements you can use any element:
<form id="nameform">
<input type="text" name="product" id="product">
</form>
php Code:
$pdo=new PDO("mysql:host=localhost;dbname=onlineshooping","root","");
$Catagoryf=$_POST['product'];
$pricef=$_POST['price'];
$colorf=$_POST['color'];
$stmtcat=$pdo->prepare('SELECT * from products where Catagory =?');
$stmtcat->execute(array($Catagoryf));
while($result=$stmtcat->fetch(PDO::FETCH_ASSOC)){
$iddb=$result['ID'];
$namedb=$result['Name'];
$pricedb=$result['Price'];
$colordb=$result['Color'];
echo "<tr>";
echo "<td><a href=./pages/productsinfo.php?id=".$iddb."> $namedb</a> </td>".'<br>';
echo "<td><pre>$pricedb</pre></td>";
echo "<td><pre> $colordb</pre>";
echo "</tr>";
The easy way
I solved this issue by accessing my fragments directly through the FragmentManager instead of via the FragmentPagerAdapter like so. First I need to figure out the tag of the fragment auto generated by the FragmentPagerAdapter...
private String getFragmentTag(int pos){
return "android:switcher:"+R.id.viewpager+":"+pos;
}
Then I simply get a reference to that fragment and do what I need like so...
Fragment f = this.getSupportFragmentManager().findFragmentByTag(getFragmentTag(1));
((MyFragmentInterface) f).update(id, name);
viewPager.setCurrentItem(1, true);
Inside my fragments I set the setRetainInstance(false);
so that I can manually add values to the savedInstanceState bundle.
@Override
public void onSaveInstanceState(Bundle outState) {
if(this.my !=null)
outState.putInt("myId", this.my.getId());
super.onSaveInstanceState(outState);
}
and then in the OnCreate i grab that key and restore the state of the fragment as necessary. An easy solution which was hard (for me at least) to figure out.
There's not a good way to convert it to foreach, because mysql_fetch_array()
just fetches the next result from $result_select
. If you really wanted to foreach, you could do pull all the results into an array first, doing something like the following:
$result_list = array();
while($row = mysql_fetch_array($result_select)) {
result_list[] = $row;
}
foreach($result_list as $row) {
...
}
But there's no good reason I can see to do that - and you still have to use the while loop, which is unavoidable due to how mysql_fetch_array()
works. Why is it so important to use a foreach()?
EDIT: If this is just for learning purposes: you can't convert this to a foreach
. You have to have a pre-existing array to use a foreach()
instead of a while()
, and mysql_fetch_array()
fetches one result per call - there's no pre-existing array for foreach()
to iterate through.
Eclipse and Java JDK (or JRE) must match regarding the BIT Version
For example:
32 Bit Eclipse won't work with 64 Bit Java!
32 Bit Eclipse needs 32 Bit Java!
char* strtrim(char* const str)
{
if (str != nullptr)
{
char const* begin{ str };
while (std::isspace(*begin))
{
++begin;
}
auto end{ begin };
auto scout{ begin };
while (*scout != '\0')
{
if (!std::isspace(*scout++))
{
end = scout;
}
}
auto /* std::ptrdiff_t */ const length{ end - begin };
if (begin != str)
{
std::memmove(str, begin, length);
}
str[length] = '\0';
}
return str;
}
No, but that is a good thing since you should always handle your errors.
There are techniques that you can employ to defer error handling, see Errors are values by Rob Pike.
ew := &errWriter{w: fd} ew.write(p0[a:b]) ew.write(p1[c:d]) ew.write(p2[e:f]) // and so on if ew.err != nil { return ew.err }
In this example from the blog post he illustrates how you could create an errWriter
type that defers error handling till you are done calling write
.
Use this command to find your active zone(s):
firewall-cmd --get-active-zones
It will say either public, dmz, or something else. You should only apply to the zones required.
In the case of public try:
firewall-cmd --zone=public --add-port=2888/tcp --permanent
Then remember to reload the firewall for changes to take effect.
firewall-cmd --reload
Otherwise, substitute public for your zone, for example, if your zone is dmz:
firewall-cmd --zone=dmz --add-port=2888/tcp --permanent
You should install IIS sub components from
Control Panel
-> Programs and Features
-> Turn Windows features on or off
Internet Information Services
has subsection World Wide Web Services
/ Application Development Features
There you must check ASP.NET
(.NET Extensibility
, ISAPI Extensions
, ISAPI Filters
will be selected automatically). Double check that specific versions are checked. Under Windows Server 2012 R2, these options are split into 4 & 4.5.
Run from cmd
:
%windir%\Microsoft.NET\Framework64\v4.0.30319\aspnet_regiis.exe -ir
Finally check in IIS manager, that your application uses application pool with .NET framework version v4.0.
Also, look at this answer.
Here, Erik explains every way pass an array by reference: https://stackoverflow.com/a/5724184/5090928.
Similarly, you can create an array reference variable like so:
int arr1[] = {1, 2, 3, 4, 5};
int(&arr2)[5] = arr1;
There is one slight difference: return code.
The thing is that unless shopt -o pipefail
is set the return code of the piped command will be return code of the last one. And uniq
always returns zero (success). Try examining exit code, and you'll see something like this (pipefail
is not set here):
pavel@lonely ~ $ sort -u file_that_doesnt_exist ; echo $?
sort: open failed: file_that_doesnt_exist: No such file or directory
2
pavel@lonely ~ $ sort file_that_doesnt_exist | uniq ; echo $?
sort: open failed: file_that_doesnt_exist: No such file or directory
0
Other than this, the commands are equivalent.
You probably have a list containing one unicode string. The repr
of this is [u'String']
.
You can convert this to a list of byte strings using any variation of the following:
# Functional style.
print map(lambda x: x.encode('ascii'), my_list)
# List comprehension.
print [x.encode('ascii') for x in my_list]
# Interesting if my_list may be a tuple or a string.
print type(my_list)(x.encode('ascii') for x in my_list)
# What do I care about the brackets anyway?
print ', '.join(repr(x.encode('ascii')) for x in my_list)
# That's actually not a good way of doing it.
print ' '.join(repr(x).lstrip('u')[1:-1] for x in my_list)
Before I answer your question, I'd like to mention that you should probably look into using some sort of ORM solution (e.g., Hibernate), wrapped behind a data access tier. What you are doing appear to be very anti-OO. I admittedly do not know what the rest of your code looks like, but generally, if you start seeing yourself using a lot of Utility classes, you're probably taking too structural of an approach.
To answer your question, as others have mentioned, look into java.sql.PreparedStatement
, and use java.sql.Date
or java.sql.Timestamp
. Something like (to use your original code as much as possible, you probably want to change it even more):
java.util.Date myDate = new java.util.Date("10/10/2009");
java.sql.Date sqlDate = new java.sql.Date(myDate.getTime());
sb.append("INSERT INTO USERS");
sb.append("(USER_ID, FIRST_NAME, LAST_NAME, SEX, DATE) ");
sb.append("VALUES ( ");
sb.append("?, ?, ?, ?, ?");
sb.append(")");
Connection conn = ...;// you'll have to get this connection somehow
PreparedStatement stmt = conn.prepareStatement(sb.toString());
stmt.setString(1, userId);
stmt.setString(2, myUser.GetFirstName());
stmt.setString(3, myUser.GetLastName());
stmt.setString(4, myUser.GetSex());
stmt.setDate(5, sqlDate);
stmt.executeUpdate(); // optionally check the return value of this call
One additional benefit of this approach is that it automatically escapes your strings for you (e.g., if were to insert someone with the last name "O'Brien", you'd have problems with your original implementation).
Use window.intro
inside of $(document).ready()
.
So here's my solution.
A simple example for a 3x3 Array. You can keep chaining this to go deeper
Array(3).fill().map(a => Array(3))
Or the following function will generate any level deep you like
f = arr => {
let str = 'return ', l = arr.length;
arr.forEach((v, i) => {
str += i < l-1 ? `Array(${v}).fill().map(a => ` : `Array(${v}` + ')'.repeat(l);
});
return Function(str)();
}
f([4,5,6]) // Generates a 4x5x6 Array
http://www.binaryoverdose.com/2017/02/07/Generating-Multidimensional-Arrays-in-JavaScript/
Check whether you have declared the method where this code is executing as static
. If it is static
there may be some other thread resetting the ResultSet
.
Declare destructors virtual in polymorphic base classes. This is Item 7 in Scott Meyers' Effective C++. Meyers goes on to summarize that if a class has any virtual function, it should have a virtual destructor, and that classes not designed to be base classes or not designed to be used polymorphically should not declare virtual destructors.
find [SOURCEPATH] -type f -name '[PATTERN]' |
while read P; do cp --parents "$P" [DEST]; done
you may remove the --parents but there is a risk of collision if multiple files bear the same name.
Returning the whole object on an update would not seem very relevant, but I can hardly see why returning the whole object when it is created would be a bad practice in a normal use case. This would be useful at least to get the ID easily and to get the timestamps when relevant. This is actually the default behavior got when scaffolding with Rails.
I really do not see any advantage to returning only the ID and doing a GET request after, to get the data you could have got with your initial POST.
Anyway as long as your API is consistent I think that you should choose the pattern that fits your needs the best. There is not any correct way of how to build a REST API, imo.
You can reload using /etc/init.d/nginx reload
and sudo service nginx reload
If nginx -t
throws some error then it won't reload
so use && to run both at a same time
like
nginx -t && /etc/init.d/nginx reload
you should remove the vars from the function:
x = x * cs - y * sn; // now x is something different than original vector x
y = x * sn + y * cs;
create new coordinates becomes, to avoid calculation of x before it reaches the second line:
px = x * cs - y * sn;
py = x * sn + y * cs;
getDimensions(id) {
var obj = questions.filter(function(node) {
return node.id==id;
});
return obj;
}
Using merge
is different from lookup in Excel as it has potential to duplicate (multiply) your data if primary key constraint is not enforced in lookup table or reduce the number of records if you are not using all.x = T
.
To make sure you don't get into trouble with that and lookup safely, I suggest two strategies.
First one is to make a check on a number of duplicated rows in lookup key:
safeLookup <- function(data, lookup, by, select = setdiff(colnames(lookup), by)) {
# Merges data to lookup making sure that the number of rows does not change.
stopifnot(sum(duplicated(lookup[, by])) == 0)
res <- merge(data, lookup[, c(by, select)], by = by, all.x = T)
return (res)
}
This will force you to de-dupe lookup dataset before using it:
baseSafe <- safeLookup(largetable, house.ids, by = "HouseType")
# Error: sum(duplicated(lookup[, by])) == 0 is not TRUE
baseSafe<- safeLookup(largetable, unique(house.ids), by = "HouseType")
head(baseSafe)
# HouseType HouseTypeNo
# 1 Apartment 4
# 2 Apartment 4
# ...
Second option is to reproduce Excel behaviour by taking the first matching value from the lookup dataset:
firstLookup <- function(data, lookup, by, select = setdiff(colnames(lookup), by)) {
# Merges data to lookup using first row per unique combination in by.
unique.lookup <- lookup[!duplicated(lookup[, by]), ]
res <- merge(data, unique.lookup[, c(by, select)], by = by, all.x = T)
return (res)
}
baseFirst <- firstLookup(largetable, house.ids, by = "HouseType")
These functions are slightly different from lookup
as they add multiple columns.
Maybe it will be to complex for this question but it surely do the job for you. I have created two classes to handle not only array insertion but also querying the database, updating and deleting files. "MySqliConnection" class is used to create only one instance of db connection (to prevent duplication of new objects).
<?php
/**
*
* MySQLi database connection: only one connection is allowed
*/
class MySqliConnection{
public static $_instance;
public $_connection;
public function __construct($host, $user, $password, $database){
$this->_connection = new MySQLi($host, $user, $password, $database);
if (isset($mysqli->connect_error)) {
echo "Failed to connect to MySQL: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error;
echo $mysqli->host_info . "\n";
}
}
/*
* Gets instance of connection to database
* @return (MySqliConnection) Object
*/
public static function getInstance($host, $user, $password, $database){
if(!self::$_instance){
self::$_instance = new self($host, $user, $password, $database); //if no instance were created - new one will be initialize
}
return self::$_instance; //return already exsiting instance of the database connection
}
/*
* Prevent database connection from bing copied while assignig the object to new wariable
* @return (MySqliConnection) Object
*/
public function getConnection(){
return $this->_connection;
}
/*
* Prevent database connection from bing copied/duplicated while assignig the object to new wariable
* @return nothing
*/
function __clone(){
}
}
/*// CLASS USE EXAMPLE
$db = MySqliConnection::getInstance('localhost', 'root', '', 'sandbox');
$mysqli = $db->getConnection();
$sql_query = 'SELECT * FROM users;
$this->lastQuery = $sql_query;
$result = $mysqli->query($sql_query);
while($row = $result->fetch_array(MYSQLI_ASSOC)){
echo $row['ID'];
}
*/
The second "TableManager" class is little bit more complex. It also make use of the MySqliConnection class which I posted above. So you would have to include both of them in your project. TableManager will allow you to easy make insertion updates and deletions. Class have separate placeholder for read and write.
<?php
/*
* DEPENDENCIES:
* include 'class.MySqliConnection.inc'; //custom class
*
*/
class TableManager{
private $lastQuery;
private $lastInsertId;
private $tableName;
private $tableIdName;
private $columnNames = array();
private $lastResult = array();
private $curentRow = array();
private $newPost = array();
/*
* Class constructor
* [1] (string) $tableName // name of the table which you want to work with
* [2] (string) $tableIdName // name of the ID field which will be used to delete and update records
* @return void
*/
function __construct($tableName, $tableIdName){
$this->tableIdName = $tableIdName;
$this->tableName = $tableName;
$this->getColumnNames();
$this->curentRow = $this->columnNames;
}
public function getColumnNames(){
$sql_query = 'SELECT COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS WHERE table_name = "'.$this->tableName.'"';
$mysqli = $this->connection();
$this->lastQuery = $sql_query;
$result = $mysqli->query($sql_query);
if (!$result) {
throw new Exception("Database Error [{$this->database->errno}] {$this->database->error}");
}
while($row = $result->fetch_array(MYSQLI_ASSOC)){
$this->columnNames[$row['COLUMN_NAME']] = null;
}
}
/*
* Used by a Constructor to set native parameters or virtual array curentRow of the class
* [1] (array) $v
* @return void
*/
function setRowValues($v){
if(!is_array($v)){
$this->curentRow = $v;
return true;
}
foreach ($v as $a => $b) {
$method = 'set'.ucfirst($a);
if(is_callable(array($this, $method))){
//if method is callable use setSomeFunction($k, $v) to filter the value
$this->$method($b);
}else{
$this->curentRow[$a] = $b;
}
}
}
/*
* Used by a constructor to set native parameters or virtual array curentRow of the class
* [0]
* @return void
*/
function __toString(){
var_dump($this);
}
/*
* Query Database for information - Select column in table where column = somevalue
* [1] (string) $column_name // name od a column
* [2] (string) $quote_pos // searched value in a specified column
* @return void
*/
public function getRow($column_name = false, $quote_post = false){
$mysqli = $this->connection();
$quote_post = $mysqli->real_escape_string($quote_post);
$this->tableName = $mysqli->real_escape_string($this->tableName);
$column_name = $mysqli->real_escape_string($column_name);
if($this->tableName && $column_name && $quote_post){
$sql_query = 'SELECT * FROM '.$this->tableName.' WHERE '.$column_name.' = "'.$quote_post.'"';
$this->lastQuery = $sql_query;
$result = $mysqli->query($sql_query);
if (!$result) {
throw new Exception("Database Error [{$this->database->errno}] {$this->database->error}");
}
while($row = $result->fetch_array(MYSQLI_ASSOC)){
$this->lastResult[$row['ID']] = $row;
$this->setRowValues($row);
}
}
if($this->tableName && $column_name && !$quote_post){
$sql_query = 'SELECT '.$column_name.' FROM '.$this->tableName.'';
$this->lastQuery = $sql_query;
$result = $mysqli->query($sql_query);
if (!$result) {
throw new Exception("Database Error [{$this->database->errno}] {$this->database->error}");
}
while($row = $result->fetch_array(MYSQLI_ASSOC)){
$this->lastResult[] = $row;
$this->setRowValues($row);
}
}
if($this->tableName && !$column_name && !$quote_post){
$sql_query = 'SELECT * FROM '.$this->tableName.'';
$this->lastQuery = $sql_query;
$result = $mysqli->query($sql_query);
if (!$result) {
throw new Exception("Database Error [{$this->database->errno}] {$this->database->error}");
}
while($row = $result->fetch_array(MYSQLI_ASSOC)){
$this->lastResult[$row['ID']] = $row;
$this->setRowValues($row);
}
}
}
/*
* Connection class gets instance of db connection or if not exsist creats one
* [0]
* @return $mysqli
*/
private function connection(){
$this->lastResult = "";
$db = MySqliConnection::getInstance('localhost', 'root', '', 'sandbox');
$mysqli = $db->getConnection();
return $mysqli;
}
/*
* ...
* [1] (string) $getMe
* @return void
*/
function __get($getMe){
if(isset($this->curentRow[$getMe])){
return $this->curentRow[$getMe];
}else{
throw new Exception("Error Processing Request - No such a property in (array) $this->curentRow", 1);
}
}
/*
* ...
* [2] (string) $setMe, (string) $value
* @return void
*/
function __set($setMe, $value){
$temp = array($setMe=>$value);
$this->setRowValues($temp);
}
/*
* Dumps the object
* [0]
* @return void
*/
function dump(){
echo "<hr>";
var_dump($this);
echo "<hr>";
}
/*
* Sets Values for $this->newPost array which will be than inserted by insertNewPost() function
* [1] (array) $newPost //array of avlue that will be inserted to $this->newPost
* @return bolean
*/
public function setNewRow($arr){
if(!is_array($arr)){
$this->newPost = $arr;
return false;
}
foreach ($arr as $k => $v) {
if(array_key_exists($k, $this->columnNames)){
$method = 'set'.ucfirst($k);
if(is_callable(array($this, $method))){
if($this->$method($v) == false){ //if something go wrong
$this->newPost = array(); //empty the newPost array and return flase
throw new Exception("There was a problem in setting up New Post parameters. [Cleaning array]", 1);
}
}else{
$this->newPost[$k] = $v;
}
}else{
$this->newPost = array(); //empty the newPost array and return flase
throw new Exception("The column does not exsist in this table. [Cleaning array]", 1);
}
}
}
/*
* Inserts new post held in $this->newPost
* [0]
* @return bolean
*/
public function insertNewRow(){
// check if is set, is array and is not null
if(isset($this->newPost) && !is_null($this->newPost) && is_array($this->newPost)){
$mysqli = $this->connection();
$count_lenght_of_array = count($this->newPost);
// preper insert query
$sql_query = 'INSERT INTO '.$this->tableName.' (';
$i = 1;
foreach ($this->newPost as $key => $value) {
$sql_query .=$key;
if ($i < $count_lenght_of_array) {
$sql_query .=', ';
}
$i++;
}
$i = 1;
$sql_query .=') VALUES (';
foreach ($this->newPost as $key => $value) {
$sql_query .='"'.$value.'"';
if ($i < $count_lenght_of_array) {
$sql_query .=', ';
}
$i++;
}
$sql_query .=')';
var_dump($sql_query);
if($mysqli->query($sql_query)){
$this->lastInsertId = $mysqli->insert_id;
$this->lastQuery = $sql_query;
}
$this->getInsertedPost($this->lastInsertId);
}
}
/*
* getInsertedPost function query the last inserted id and assigned it to the object.
* [1] (integer) $id // last inserted id from insertNewRow fucntion
* @return void
*/
private function getInsertedPost($id){
$mysqli = $this->connection();
$sql_query = 'SELECT * FROM '.$this->tableName.' WHERE '.$this->tableIdName.' = "'.$id.'"';
$result = $mysqli->query($sql_query);
while($row = $result->fetch_array(MYSQLI_ASSOC)){
$this->lastResult[$row['ID']] = $row;
$this->setRowValues($row);
}
}
/*
* getInsertedPost function query the last inserted id and assigned it to the object.
* [0]
* @return bolean // if deletion was successful return true
*/
public function deleteLastInsertedPost(){
$mysqli = $this->connection();
$sql_query = 'DELETE FROM '.$this->tableName.' WHERE '.$this->tableIdName.' = '.$this->lastInsertId.'';
$result = $mysqli->query($sql_query);
if($result){
$this->lastResult[$this->lastInsertId] = "deleted";
return true;
}else{
throw new Exception("We could not delete last inserted row by ID [{$mysqli->errno}] {$mysqli->error}");
}
var_dump($sql_query);
}
/*
* deleteRow function delete the row with from a table based on a passed id
* [1] (integer) $id // id of the table row to be delated
* @return bolean // if deletion was successful return true
*/
public function deleteRow($id){
$mysqli = $this->connection();
$sql_query = 'DELETE FROM '.$this->tableName.' WHERE '.$this->tableIdName.' = '.$id.'';
$result = $mysqli->query($sql_query);
if($result){
$this->lastResult[$this->lastInsertId] = "deleted";
return true;
}else{
return false;
}
var_dump($sql_query);
}
/*
* deleteAllRows function deletes all rows from a table
* [0]
* @return bolean // if deletion was successful return true
*/
public function deleteAllRows(){
$mysqli = $this->connection();
$sql_query = 'DELETE FROM '.$this->tableName.'';
$result = $mysqli->query($sql_query);
if($result){
return true;
}else{
return false;
}
}
/*
* updateRow function updates all values to object values in a row with id
* [1] (integer) $id
* @return bolean // if deletion was successful return true
*/
public function updateRow($update_where = false){
$id = $this->curentRow[$this->tableIdName];
$mysqli = $this->connection();
$updateMe = $this->curentRow;
unset($updateMe[$this->tableIdName]);
$count_lenght_of_array = count($updateMe);
// preper insert query
$sql_query = 'UPDATE '.$this->tableName.' SET ';
$i = 1;
foreach ($updateMe as $k => $v) {
$sql_query .= $k.' = "'.$v.'"';
if ($i < $count_lenght_of_array) {
$sql_query .=', ';
}
$i++;
}
if($update_where == false){
//update row only for this object id
$sql_query .=' WHERE '.$this->tableIdName.' = '.$this->curentRow[$this->tableIdName].'';
}else{
//add your custom update where query
$sql_query .=' WHERE '.$update_where.'';
}
var_dump($sql_query);
if($mysqli->query($sql_query)){
$this->lastQuery = $sql_query;
}
$result = $mysqli->query($sql_query);
if($result){
return true;
}else{
return false;
}
}
}
/*TO DO
1 insertPost(X, X) write function to isert data and in to database;
2 get better query system and display data from database;
3 write function that displays data of a object not databsae;
object should be precise and alocate only one instance of the post at a time.
// Updating the Posts to curent object $this->curentRow values
->updatePost();
// Deleting the curent post by ID
// Add new row to database
*/
/*
USE EXAMPLE
$Post = new TableManager("post_table", "ID"); // New Object
// Getting posts from the database based on pased in paramerters
$Post->getRow('post_name', 'SOME POST TITLE WHICH IS IN DATABASE' );
$Post->getRow('post_name');
$Post->getRow();
MAGIC GET will read current object $this->curentRow parameter values by refering to its key as in a varible name
echo $Post->ID.
echo $Post->post_name;
echo $Post->post_description;
echo $Post->post_author;
$Task = new TableManager("table_name", "table_ID_name"); // creating new TableManager object
$addTask = array( //just an array [colum_name] => [values]
'task_name' => 'New Post',
'description' => 'New Description Post',
'person' => 'New Author',
);
$Task->setNewRow($addTask); //preper new values for insertion to table
$Task->getRow('ID', '12'); //load value from table to object
$Task->insertNewRow(); //inserts new row
$Task->dump(); //diplays object properities
$Task->person = "John"; //magic __set() method will look for setPerson(x,y) method firs if non found will assign value as it is.
$Task->description = "John Doe is a funny guy"; //magic __set() again
$Task->task_name = "John chellange"; //magic __set() again
$test = ($Task->updateRow("ID = 5")) ? "WORKS FINE" : "ERROR"; //update cutom row with object values
echo $test;
$test = ($Task->updateRow()) ? "WORKS FINE" : "ERROR"; //update curent data loaded in object
echo $test;
*/
I was running in to a problem with the standard way to do this:
$string = "one";
$float = (float)$string;
echo $float; : ( Prints 0 )
If there isn't a valid number, the parser shouldn't return a number, it should throw an error. (This is a condition I'm trying to catch in my code, YMMV)
To fix this I have done the following:
$string = "one";
$float = is_numeric($string) ? (float)$string : null;
echo $float; : ( Prints nothing )
Then before further processing the conversion, I can check and return an error if there wasn't a valid parse of the string.
for a in range(1):
for b in range(3):
a = b*2
print(a)
As per your question, you want to iterate the outer loop with help of the inner loop.
In the inner loop, we are iterating the 3 digits which are in the multiple of 2, starting from 0.
Output:
0
2
4
This is actually a documented feature, and can be found here
// This event listener calls addMarker() when the map is clicked.
google.maps.event.addListener(map, 'click', function(e) {
placeMarker(e.latLng, map);
});
function placeMarker(position, map) {
var marker = new google.maps.Marker({
position: position,
map: map
});
map.panTo(position);
}
Pageable has an option to specify sort as well. From the java doc
PageRequest(int page, int size, Sort.Direction direction, String... properties)
Creates a new PageRequest with sort parameters applied.
Worked liked a charm for me:
matplotlib.rcParams['figure.figsize'] = (20, 10)
I had the same problem.I solved with following command maven:
mvn eclipse:eclipse -Dwtpversion=2.0
PS: My project is WTP plugin
For someone new to all this and if accidentally landed here
As of now all AMI's in quickstart section are EBS backed
Also there's a good explanation at official doc for difference between EBS and Instance store
the problem is in flow annotation in handleClick, i removed this and works fine thanks @alik
in below code midpointsList is an ArrayList of waypoints
private String getMapsApiDirectionsUrl(GoogleMap googleMap, LatLng startLatLng, LatLng endLatLng, ArrayList<LatLng> midpointsList) {
String origin = "origin=" + startLatLng.latitude + "," + startLatLng.longitude;
String midpoints = "";
for (int mid = 0; mid < midpointsList.size(); mid++) {
midpoints += "|" + midpointsList.get(mid).latitude + "," + midpointsList.get(mid).longitude;
}
String waypoints = "waypoints=optimize:true" + midpoints + "|";
String destination = "destination=" + endLatLng.latitude + "," + endLatLng.longitude;
String key = "key=AIzaSyCV1sOa_7vASRBs6S3S6t1KofFvDhjohvI";
String sensor = "sensor=false";
String params = origin + "&" + waypoints + "&" + destination + "&" + sensor + "&" + key;
String output = "json";
String url = "https://maps.googleapis.com/maps/api/directions/" + output + "?" + params;
Log.e("url", url);
parseDirectionApidata(url, googleMap);
return url;
}
Then copy and paste this url in your browser to check And the below code is to parse the url
private void parseDirectionApidata(String url, final GoogleMap googleMap) {
final JSONObject jsonObject = new JSONObject();
try {
AppUtill.getJsonWithHTTPPost(ViewMapActivity.this, 1, new ServiceCallBack() {
@Override
public void serviceCallBack(int id, JSONObject jsonResult) throws JSONException {
if (jsonResult != null) {
Log.e("jsonRes", jsonResult.toString());
String status = jsonResult.optString("status");
if (status.equalsIgnoreCase("ok")) {
drawPath(jsonResult, googleMap);
}
} else {
Toast.makeText(ViewMapActivity.this, "Unable to parse Directions Data", Toast.LENGTH_LONG).show();
}
}
}, url, jsonObject);
} catch (Exception e) {
e.printStackTrace();
}
}
And then pass the result to the drawPath method
public void drawPath(JSONObject jObject, GoogleMap googleMap) {
List<List<HashMap<String, String>>> routes = new ArrayList<List<HashMap<String, String>>>();
JSONArray jRoutes = null;
JSONArray jLegs = null;
JSONArray jSteps = null;
List<LatLng> list = null;
try {
Toast.makeText(ViewMapActivity.this, "Drawing Path...", Toast.LENGTH_SHORT).show();
jRoutes = jObject.getJSONArray("routes");
/** Traversing all routes */
for (int i = 0; i < jRoutes.length(); i++) {
jLegs = ((JSONObject) jRoutes.get(i)).getJSONArray("legs");
List path = new ArrayList<HashMap<String, String>>();
/** Traversing all legs */
for (int j = 0; j < jLegs.length(); j++) {
jSteps = ((JSONObject) jLegs.get(j)).getJSONArray("steps");
/** Traversing all steps */
for (int k = 0; k < jSteps.length(); k++) {
String polyline = "";
polyline = (String) ((JSONObject) ((JSONObject) jSteps.get(k)).get("polyline")).get("points");
list = decodePoly(polyline);
}
Log.e("list", list.toString());
routes.add(path);
Log.e("routes", routes.toString());
if (list != null) {
Polyline line = googleMap.addPolyline(new PolylineOptions()
.addAll(list)
.width(12)
.color(Color.parseColor("#FF0000"))//Google maps blue color #05b1fb
.geodesic(true)
);
}
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}
private List<LatLng> decodePoly(String encoded) {
List<LatLng> poly = new ArrayList<LatLng>();
int index = 0, len = encoded.length();
int lat = 0, lng = 0;
while (index < len) {
int b, shift = 0, result = 0;
do {
b = encoded.charAt(index++) - 63;
result |= (b & 0x1f) << shift;
shift += 5;
} while (b >= 0x20);
int dlat = ((result & 1) != 0 ? ~(result >> 1) : (result >> 1));
lat += dlat;
shift = 0;
result = 0;
do {
b = encoded.charAt(index++) - 63;
result |= (b & 0x1f) << shift;
shift += 5;
} while (b >= 0x20);
int dlng = ((result & 1) != 0 ? ~(result >> 1) : (result >> 1));
lng += dlng;
LatLng p = new LatLng((((double) lat / 1E5)),
(((double) lng / 1E5)));
poly.add(p);
}
return poly;
}
decode poly function is to decode the points(lat and long) provided by Directions API in encoded form
I send you an example with swiftmailer:
recipients: [email1, email2, email3]
your_service_name:
class: your_namespace
arguments: ["%recipients%"]
protected $recipients;
public function __construct($recipients)
{
$this->recipients = $recipients;
}
For the mouse cursor (with jQuery UI) :
$('#my-modal').draggable({
handle: ".modal-header"
});
For the touch cursor (with jQuery):
var box = null;
var touchobj = null;
var position = {'x':0, 'y':0};
var positionbox = {'x':0, 'y':0};
// init touch
$('.modal-header').on('touchstart', function(e){
box = $(this).closest('.modal-dialog');
touchobj = e.changedTouches[0];
// take position touch cursor
position['x'] = touchobj.pageX;
position['y'] = touchobj.pageY;
//take original position box to move with touch
positionbox['x'] = parseInt(box.css('left'));
positionbox['y'] = parseInt(box.css('top'));
e.preventDefault();
});
// on move touch
$('.modal-header').on('touchmove', function(e){
var dist = {'x':0, 'y':0};
touchobj = e.changedTouches[0];
// we calculate the distance of move
dist['x'] = parseInt(touchobj.clientX) - position['x'];
dist['y'] = parseInt(touchobj.clientY) - position['y'];
// we apply the movement distance on the box
box.css('left', positionbox['x']+dist['x'] +"px");
box.css('top', positionbox['y']+dist['y'] +"px");
e.preventDefault();
});
The addition of the 2 solutions is compatible
Andrey Tarasevich provides the following explanation:
[Minor changes to formatting made. Parenthetical annotations added in square brackets []
].
The whole idea of using 'do/while' version is to make a macro which will expand into a regular statement, not into a compound statement. This is done in order to make the use of function-style macros uniform with the use of ordinary functions in all contexts.
Consider the following code sketch:
if (<condition>) foo(a); else bar(a);
where
foo
andbar
are ordinary functions. Now imagine that you'd like to replace functionfoo
with a macro of the above nature [namedCALL_FUNCS
]:if (<condition>) CALL_FUNCS(a); else bar(a);
Now, if your macro is defined in accordance with the second approach (just
{
and}
) the code will no longer compile, because the 'true' branch ofif
is now represented by a compound statement. And when you put a;
after this compound statement, you finished the wholeif
statement, thus orphaning theelse
branch (hence the compilation error).One way to correct this problem is to remember not to put
;
after macro "invocations":if (<condition>) CALL_FUNCS(a) else bar(a);
This will compile and work as expected, but this is not uniform. The more elegant solution is to make sure that macro expand into a regular statement, not into a compound one. One way to achieve that is to define the macro as follows:
#define CALL_FUNCS(x) \ do { \ func1(x); \ func2(x); \ func3(x); \ } while (0)
Now this code:
if (<condition>) CALL_FUNCS(a); else bar(a);
will compile without any problems.
However, note the small but important difference between my definition of
CALL_FUNCS
and the first version in your message. I didn't put a;
after} while (0)
. Putting a;
at the end of that definition would immediately defeat the entire point of using 'do/while' and make that macro pretty much equivalent to the compound-statement version.I don't know why the author of the code you quoted in your original message put this
;
afterwhile (0)
. In this form both variants are equivalent. The whole idea behind using 'do/while' version is not to include this final;
into the macro (for the reasons that I explained above).
I found that the formal way to do this is as follows:
Just install two (or more, using their installers) versions of Python on Windows 7 (for me work with 3.3 and 2.7).
Follow the instuctions below, changing the parameters for your needs.
Create the following environment variable (to default on double click):
Name: PY_PYTHON
Value: 3
To launch a script in a particular interpreter, add the following shebang (beginning of script):
#! python2
To execute a script using a specific interpreter, use the following prompt command:
> py -2 MyScript.py
To launch a specific interpreter:
> py -2
To launch the default interpreter (defined by the PY_PYTHON variable):
> py
Resources
Documentation: Using Python on Windows
PEP 397 - Python launcher for Windows
You can use the change
event to monitor what the user selects and notify them at that point that the file is not acceptable. It does not limit the actual list of files displayed, but it is the closest you can do client-side, besides the poorly supported accept
attribute.
var file = document.getElementById('someId');_x000D_
_x000D_
file.onchange = function(e) {_x000D_
var ext = this.value.match(/\.([^\.]+)$/)[1];_x000D_
switch (ext) {_x000D_
case 'jpg':_x000D_
case 'bmp':_x000D_
case 'png':_x000D_
case 'tif':_x000D_
alert('Allowed');_x000D_
break;_x000D_
default:_x000D_
alert('Not allowed');_x000D_
this.value = '';_x000D_
}_x000D_
};
_x000D_
<input type="file" id="someId" />
_x000D_
(Tested in Chrome while playing videos on YouTube, but should work anywhere--especially useful for speeding up online training videos).
For anyone wanting to add these as "bookmarklets" (bookmarks) to your browser, use these browser bookmark names and URLs, and add each of the following bookmarks to the top of your browser:
Name: 0.5x
URL:
javascript:
document.querySelector('video').playbackRate = 0.5;
Name: 1.0x
URL:
javascript:
document.querySelector('video').playbackRate = 1.0;
Name: 1.5x
URL:
javascript:
document.querySelector('video').playbackRate = 1.5;
Name: 2.0x
URL:
javascript:
document.querySelector('video').playbackRate = 2.0;
I faced a similar issue and this is how I fixed it,
The problem is due to the conversion process from JSON to Java, one need to have the right run time jackson libraries for the conversion to happen correctly.
Add the following jars (through dependency or by downloading and adding to the classpath.
<dependency>
<groupId>org.codehaus.jackson</groupId>
<artifactId>jackson-mapper-asl</artifactId>
<version>1.9.13</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.5.3</version>
</dependency>
This should fix the problem.
Complete Code:
function() {
$.ajax({
type: "POST",
url: "saveUserDetails.do",
data: JSON.stringify({
name: "Gerry",
ity: "Sydney"
}),
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
success: function(data) {
if (data.status == 'OK')
alert('Person has been added');
else
alert('Failed adding person: ' + data.status + ', ' + data.errorMessage);
}
and the controller signature looks like this:
@RequestMapping(value = "/saveUserDetails.do", method = RequestMethod.POST)
public @ResponseBody Person addPerson( @RequestBody final Person person) {
Hope this helps
Do not use passwords. Use peer authentication instead:
postgres://myuser@%2Fvar%2Frun%2Fpostgresql/mydb
Works Fine for App Notification settings on IOS 10 (tested)
if(&UIApplicationOpenSettingsURLString != nil){
[[UIApplication sharedApplication] openURL:[NSURL URLWithString:UIApplicationOpenSettingsURLString]];
}
Easiest method:
From Command Line, use:
for %f in (*.*) do echo %f
From a Batch File (double up the % percent signs):
for %%f in (*.*) do echo %%f
From a Batch File with folder specified as 1st parameter:
for %%f in (%1\*.*) do echo %%f
The following works in Python 2.6, 2.7, and 3.2:
import os
import sys
buf_arg = 0
if sys.version_info[0] == 3:
os.environ['PYTHONUNBUFFERED'] = '1'
buf_arg = 1
sys.stdout = os.fdopen(sys.stdout.fileno(), 'a+', buf_arg)
sys.stderr = os.fdopen(sys.stderr.fileno(), 'a+', buf_arg)
I wrote a very simple class for exporting to "Excel XML" aka SpreadsheetML. It's not quite as convenient for the end user as XSLX (depending on file extension and Excel version, they may get a warning message), but it's a lot easier to work with than XLS or XLSX.
Sometimes you'll need to specify PATH and GEM_PATH using crontab with rvm.
Like this:
# top of crontab file
PATH=/home/user_name/.rvm/gems/ruby-2.2.0/bin:/home/user_name/.rvm/gems/ruby-2.2.0@global/bin:/home/user_name/.rvm/rubies/ruby-2.2.$
GEM_PATH=/home/user_name/.rvm/gems/ruby-2.2.0:/home/user_name/.rvm/gems/ruby-2.2.0@global
# jobs
00 00 * * * ruby path/to/your/script.rb
00 */4 * * * ruby path/to/your/script2.rb
00 8,12,22 * * * ruby path/to/your/script3.rb
If you want to take advantage of the 60FPS smoothness that the "transform" property offers, you can combine the two:
@keyframes changewidth {
from {
transform: scaleX(1);
}
to {
transform: scaleX(2);
}
}
div {
animation-duration: 0.1s;
animation-name: changewidth;
animation-iteration-count: infinite;
animation-direction: alternate;
}
More explanation on why transform offers smoother transitions here: https://medium.com/outsystems-experts/how-to-achieve-60-fps-animations-with-css3-db7b98610108
Chrome keeps changing the way it handles autocomplete on each version, the way I came up was, to make the fields readonly and onclick/focus make it Not readonly. try this jQuery snippet.
jQuery(document).ready(function($){
//======fix for autocomplete
$('input, :input').attr('readonly',true);//readonly all inputs on page load, prevent autofilling on pageload
$('input, :input').on( 'click focus', function(){ //on input click
$('input, :input').attr('readonly',true);//make other fields readonly
$( this ).attr('readonly',false);//but make this field Not readonly
});
//======./fix for autocomplete
});
Well, for starters, a struct is passed by value rather than by reference. Structs are good for relatively simple data structures, while classes have a lot more flexibility from an architectural point of view via polymorphism and inheritance.
Others can probably give you more detail than I, but I use structs when the structure that I am going for is simple.
A slightly simplified version of Oglester's solution (the sequence doesn't require a select from DUAL:
INSERT INTO account_type_standard
(account_type_Standard_id, tax_status_id, recipient_id)
VALUES(
account_type_standard_seq.nextval,
(SELECT tax_status_id FROM tax_status WHERE tax_status_code = ?),
(SELECT recipient_id FROM recipient WHERE recipient_code = ?)
)
You can use pandas.cut
:
bins = [0, 1, 5, 10, 25, 50, 100]
df['binned'] = pd.cut(df['percentage'], bins)
print (df)
percentage binned
0 46.50 (25, 50]
1 44.20 (25, 50]
2 100.00 (50, 100]
3 42.12 (25, 50]
bins = [0, 1, 5, 10, 25, 50, 100]
labels = [1,2,3,4,5,6]
df['binned'] = pd.cut(df['percentage'], bins=bins, labels=labels)
print (df)
percentage binned
0 46.50 5
1 44.20 5
2 100.00 6
3 42.12 5
bins = [0, 1, 5, 10, 25, 50, 100]
df['binned'] = np.searchsorted(bins, df['percentage'].values)
print (df)
percentage binned
0 46.50 5
1 44.20 5
2 100.00 6
3 42.12 5
...and then value_counts
or groupby
and aggregate size
:
s = pd.cut(df['percentage'], bins=bins).value_counts()
print (s)
(25, 50] 3
(50, 100] 1
(10, 25] 0
(5, 10] 0
(1, 5] 0
(0, 1] 0
Name: percentage, dtype: int64
s = df.groupby(pd.cut(df['percentage'], bins=bins)).size()
print (s)
percentage
(0, 1] 0
(1, 5] 0
(5, 10] 0
(10, 25] 0
(25, 50] 3
(50, 100] 1
dtype: int64
By default cut
return categorical
.
Series
methods like Series.value_counts()
will use all categories, even if some categories are not present in the data, operations in categorical.
You could try to do this with getcode()
from urllib
>>> print urllib.urlopen("http://www.stackoverflow.com").getcode()
>>> 200
EDIT: For more modern python, i.e. python3
, use:
import urllib.request
print(urllib.request.urlopen("http://www.stackoverflow.com").getcode())
>>> 200
This recently happen to me when enabling JMX on two running tomcat service within Eclipse. I mistakenly put the same port for each server.
Simply give each jmx remote a different port
Server 1
-Dcom.sun.management.jmxremote.port=9000
Server 2
-Dcom.sun.management.jmxremote.port=9001
Running git add
sometimes helps.
Git status is showing changed files and git diff is showing nothing...
> git status
On branch master
Changes not staged for commit:
(use "git add <file>..." to update what will be committed)
(use "git checkout -- <file>..." to discard changes in working directory)
modified: package.json
no changes added to commit (use "git add" and/or "git commit -a")
> git diff
>
...running git add resolves the inconsistency.
> git add
> git status
On branch master
nothing to commit, working directory clean
>
I had a similar need and end up using componentDidMount(), that one is called long after component class constructor (where you can initialize state from props - as an exmple using redux )
Inside componentDidMount you can then invoke your handleChange method for some UI animation or perform any kind of component properties updates required.
As an example I had an issue updating an input checkbox type programatically, that's why I end up using this code, as onChange handler was not firing at component load:
componentDidMount() {
// Update checked
const checkbox = document.querySelector('[type="checkbox"]');
if (checkbox)
checkbox.checked = this.state.isChecked;
}
State was first updated in component class constructor and then utilized to update some input component behavior
This piece of snippet is from c++ primer book. Although I am sure this is wrong.
Each type parameter must be preceded by the keyword class or typename:
// error: must precede U with either typename or class
template <typename T, U> T calc(const T&, const U&);
These keywords have the same meaning and can be used interchangeably inside a template parameter list. A template parameter list can use both keywords:
// ok: no distinction between typename and class in a template parameter list
template <typename T, class U> calc (const T&, const U&);
It may seem more intuitive to use the keyword typename rather than class to designate a template type parameter. After all, we can use built-in (nonclass) types as a template type argument. Moreover, typename more clearly indicates that the name that follows is a type name. However, typename was added to C++ after templates were already in widespread use; some programmers continue to use class exclusively
javascript uses dynamic arrays, no need to declare the size beforehand
you can push and shift to arrays as many times as you want, javascript will handle allocation and stuff for you
I was having the same issue and this works excellently.
Private Sub DataGridView17_CellFormatting(sender As Object, e As System.Windows.Forms.DataGridViewCellFormattingEventArgs) Handles DataGridView17.CellFormatting
'Display complete contents in tooltip even though column display cuts off part of it.
DataGridView17.Rows(e.RowIndex).Cells(e.ColumnIndex).ToolTipText = DataGridView17.Rows(e.RowIndex).Cells(e.ColumnIndex).Value
End Sub
A short demonstration of @gregmac's (excellent and detailed) answer, which essentially recommends $PSCommandPath
as the only reliable command to return the currently running script where Powershell 3.0 and above is used.
Here I show returning either the full path or just the file name.
Test.ps1:
'Direct:'
$PSCommandPath # Full Path
Split-Path -Path $PSCommandPath -Leaf # File Name only
function main () {
''
'Within a function:'
$PSCommandPath
Split-Path -Path $PSCommandPath -Leaf
}
main
Output:
PS> .\Test.ps1
Direct:
C:\Users\John\Documents\Sda\Code\Windows\PowerShell\Apps\xBankStatementRename\Test.ps1
Test.ps1
Within a function:
C:\Users\John\Documents\Sda\Code\Windows\PowerShell\Apps\xBankStatementRename\Test.ps1
Test.ps1
In Windows you can just import the subprocess
module and run external commands by calling subprocess.Popen()
, subprocess.Popen().communicate()
and subprocess.Popen().wait()
as below:
# Python script to run a command line
import subprocess
def execute(cmd):
"""
Purpose : To execute a command and return exit status
Argument : cmd - command to execute
Return : exit_code
"""
process = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
(result, error) = process.communicate()
rc = process.wait()
if rc != 0:
print "Error: failed to execute command:", cmd
print error
return result
# def
command = "tasklist | grep python"
print "This process detail: \n", execute(command)
Output:
This process detail:
python.exe 604 RDP-Tcp#0 4 5,660 K
Displaying an Image
in WPF is much easier than that. Try this:
<Image Source="{Binding DisplayedImagePath}" HorizontalAlignment="Left"
Margin="0,0,0,0" Name="image1" Stretch="Fill" VerticalAlignment="Bottom"
Grid.Row="8" Width="200" Grid.ColumnSpan="2" />
And the property can just be a string
:
public string DisplayedImage
{
get { return @"C:\Users\Public\Pictures\Sample Pictures\Chrysanthemum.jpg"; }
}
Although you really should add your images to a folder named Images
in the root of your project and set their Build Action to Resource in the Properties Window in Visual Studio... you could then access them using this format:
public string DisplayedImage
{
get { return "/AssemblyName;component/Images/ImageName.jpg"; }
}
UPDATE >>>
As a final tip... if you ever have a problem with a control not working as expected, simply type 'WPF', the name of that control and then the word 'class' into a search engine. In this case, you would have typed 'WPF Image Class'. The top result will always be MSDN and if you click on the link, you'll find out all about that control and most pages have code examples as well.
UPDATE 2 >>>
If you followed the examples from the link to MSDN and it's not working, then your problem is not the Image
control. Using the string
property that I suggested, try this:
<StackPanel>
<Image Source="{Binding DisplayedImagePath}" />
<TextBlock Text="{Binding DisplayedImagePath}" />
</StackPanel>
If you can't see the file path in the TextBlock
, then you probably haven't set your DataContext
to the instance of your view model. If you can see the text, then the problem is with your file path.
UPDATE 3 >>>
In .NET 4, the above Image.Source
values would work. However, Microsoft made some horrible changes in .NET 4.5 that broke many different things and so in .NET 4.5, you'd need to use the full pack
path like this:
<Image Source="pack://application:,,,/AssemblyName;component/Images/image_to_use.png">
For further information on pack URIs, please see the Pack URIs in WPF page on Microsoft Docs.
Recently I had the need to perform some encryption/decryption interoperability between javascript and python.
Specifically...
1) Using AES to encrypt in javascript and decrypt in python (Google App Engine) 2) Using RSA to encrypt in javascript and decrypt in python (Google App Engine) 3) Using pycrypto
I found lots and lots of different versions of RSA and AES floating around the web and they were all different in their approach but I did not find a good example of end to end javascript and python interoperability.
Eventually I managed to cobble together something that suited my needs after a lot of trial and error.
Anyhow I knocked up an example of a js/webapp talking to a google app engine hosted python server that uses AES and public key and private key RSA stuff.
I though I'd include it here by link in case it will be of some use to others who need to accomplish the same thing.
http://www.ipowow.com/files/aesrsademo.tar.gz
and see demo at rsa-aes-demo DOT appspot DOT com
edit: look at the browser console output and also view source to get some hints and useful messages as to what's going on in the demo
edit: updated very old and defunct link to source to now point to
The arguments
object is where the functions arguments are stored.
The arguments object acts and looks like an array, it basically is, it just doesn't have the methods that arrays do, for example:
Array.forEach(callback[, thisArg]);
Array.map(callback[, thisArg])
Array.filter(callback[, thisArg]);
Array.indexOf(searchElement[, fromIndex])
I think the best way to convert a arguments
object to a real Array is like so:
argumentsArray = [].slice.apply(arguments);
That will make it an array;
reusable:
function ArgumentsToArray(args) {
return [].slice.apply(args);
}
(function() {
args = ArgumentsToArray(arguments);
args.forEach(function(value) {
console.log('value ===', value);
});
})('name', 1, {}, 'two', 3)
result:
>
value === name
>value === 1
>value === Object {}
>value === two
>value === 3
Contrary to .NET where all types derive from an "object", in TypeScript, all types derive from "any". I just wanted to add this comparison as I think it will be a common one made as more .NET developers give TypeScript a try.
Usually, best is to see a character in his context.
Here is the full list of Unicode chars, and how your browser currently displays them. I am seeing this list evolving, browser versions after others.
This list is obtained by iteration in decimal of the html entities unicode table, it may take some seconds, but is very useful to me in many cases.
By hovering quickly a given char you will get the dec and hex and the shortcuts to generate it with a keyboard.
var i = 0
do document.write("<a title='(Linux|Hex): [CTRL+SHIFT]+u"+(i).toString(16)+"\nHtml entity: &# "+i+";\n&#x"+(i).toString(16)+";\n(Win|Dec): [ALT]+"+i+"' onmouseover='this.focus()' onclick='this.href=\"//google.com/?q=\"+this.innerHTML' style='cursor:pointer' target='new'>"+"&#"+i+";</a>"),i++
while (i<136690)
window.stop()
// From https://codepen.io/Nico_KraZhtest/pen/mWzXqy
_x000D_
The same snippet as a bookmarklet:
javascript:void%20!function(){var%20t=0;do{document.write(%22%3Ca%20title='(Linux|Hex):%20[CTRL+SHIFT]+u%22+t.toString(16)+%22\nHtml%20entity:%20%26%23%20%22+t+%22;\n%26%23x%22+t.toString(16)+%22;\n(Win|Dec):%20[ALT]+%22+t+%22'%20onmouseover='this.focus()'%20onclick='this.href=\%22https://google.com/%3Fq=\%22+this.innerHTML'%20style='cursor:pointer'%20target='new'%3E%26%23%22+t+%22;%3C/a%3E%22),t++}while(t%3C136690);window.stop()}();
To generate that list from php:
for ($x = 0; $x < 136690; $x++) {
echo html_entity_decode('&#'.$x.';',ENT_NOQUOTES,'UTF-8');
}
To generate that list into the console, using php:
php -r 'for ($x = 0; $x < 136690; $x++) { echo html_entity_decode("&#".$x.";",ENT_NOQUOTES,"UTF-8");}'
Here is a plain text extract, of arrows, some are coming with unicode 10.0. http://unicode.org/versions/Unicode10.0.0/
Unicode 10.0 adds 8,518 characters, for a total of 136,690 characters.
???????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????
Hey, did you notice the plain html <details>
element has a drop down arrow? This is sometimes all what we need.
<details>
<summary>Morning</summary>
<p>Hello world!</p>
</details>
<details>
<summary>Evening</summary>
<p>How sweat?</p>
</details>
_x000D_
To access the convert datatable value in Json method follow the below steps:
$.ajax({
type: "POST",
url: "/Services.asmx/YourMethodName",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
var parsed = $.parseJSON(data.d);
$.each(parsed, function (i, jsondata) {
$("#dividtodisplay").append("Title: " + jsondata.title + "<br/>" + "Latitude: " + jsondata.lat);
});
},
error: function (XHR, errStatus, errorThrown) {
var err = JSON.parse(XHR.responseText);
errorMessage = err.Message;
alert(errorMessage);
}
});
After creating a file you must force the stream to release the resources:
//FSm is stream for creating file on a path//
System.IO.FileStream FS = new System.IO.FileStream(path + fname,
System.IO.FileMode.Create);
pro.CopyTo(FS);
FS.Dispose();
The answer should be Jain. You can not select an element via pseudo-selector, but you can add a new rule to your stylesheet with insertRule
.
I made something that should work for you:
var addRule = function(sheet, selector, styles) {
if (sheet.insertRule) return sheet.insertRule(selector + " {" + styles + "}", sheet.cssRules.length);
if (sheet.addRule) return sheet.addRule(selector, styles);
};
addRule(document.styleSheets[0], "body:before", "content: 'foo'");
http://fiddle.jshell.net/MDyxg/1/
To be super-cool (and to answer the question really) I rolled it out again and wrapped this in a jQuery-plugin (however, jquery is still not required!):
/*!
* jquery.addrule.js 0.0.1 - https://gist.github.com/yckart/5563717/
* Add css-rules to an existing stylesheet.
*
* @see http://stackoverflow.com/a/16507264/1250044
*
* Copyright (c) 2013 Yannick Albert (http://yckart.com)
* Licensed under the MIT license (http://www.opensource.org/licenses/mit-license.php).
* 2013/05/12
**/
(function ($) {
window.addRule = function (selector, styles, sheet) {
styles = (function (styles) {
if (typeof styles === "string") return styles;
var clone = "";
for (var p in styles) {
if (styles.hasOwnProperty(p)) {
var val = styles[p];
p = p.replace(/([A-Z])/g, "-$1").toLowerCase(); // convert to dash-case
clone += p + ":" + (p === "content" ? '"' + val + '"' : val) + "; ";
}
}
return clone;
}(styles));
sheet = sheet || document.styleSheets[document.styleSheets.length - 1];
if (sheet.insertRule) sheet.insertRule(selector + " {" + styles + "}", sheet.cssRules.length);
else if (sheet.addRule) sheet.addRule(selector, styles);
return this;
};
if ($) $.fn.addRule = function (styles, sheet) {
addRule(this.selector, styles, sheet);
return this;
};
}(window.jQuery));
The usage is quite simple:
$("body:after").addRule({
content: "foo",
color: "red",
fontSize: "32px"
});
// or without jquery
addRule("body:after", {
content: "foo",
color: "red",
fontSize: "32px"
});
You can add this code:
function parseBool(str) {
if (str.length == null) {
return str == 1 ? true : false;
} else {
return str == "true" ? true : false;
}
}
Works like this:
parseBool(1) //true
parseBool(0) //false
parseBool("true") //true
parseBool("false") //false
You can try to use underscore.js
First convert the lines in arrays using the toArray function :
var letters = _.toArray(a,b,c,d);
var numbers = _.toArray(1,2,3,4);
Then object the arrays together using the object function :
var json = _.object(letters, numbers);
By then, the json var should contain something like :
{"a": 1,"b": 2,"c": 3,"d": 4}
import nltk
nltk.download()
Click on download button when gui prompted. It worked for me.(nltk.download('stopwords')
doesn't work for me)
If Folder getting from other, and host file is already generated on ProjectName\.vs\config
folder, then it conflicts with a new one and gets this error.
So delete host file from ProjectName\.vs\config
and restart project once again. It was worked for me
Use of folloing command is depreciated
hadoop job -list
hadoop job -kill $jobId
consider using
mapred job -list
mapred job -kill $jobId
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:background="#000"
android:gravity="center"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<ImageView
android:scaleType="fitXY"
android:layout_marginTop="5dp"
android:layout_marginBottom="60dp"
android:src="@drawable/lwt_placeholder"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:adjustViewBounds="true"
android:visibility="visible"
android:id="@+id/imageView"
android:layout_centerInParent="true"/></RelativeLayout>
and in activity
final ImageView imageView = (ImageView) itemView.findViewById(R.id.imageView);
PhotoViewAttacher photoAttacher;
photoAttacher= new PhotoViewAttacher(imageView);
photoAttacher.update();
Picasso.with(ImageGallery.this).load(imageUrl).placeholder(R.drawable.lwt_placeholder)
.into(imageView);
Thats it!
This variant is better because you could not know whether file exists or not. You should send correct header when you know for certain that you can read contents of your file. Also, if you have branches of code that does not finish with '.end()', browser will wait until it get them. In other words, your browser will wait a long time.
var fs = require("fs");
var filename = "./index.html";
function start(resp) {
fs.readFile(filename, "utf8", function(err, data) {
if (err) {
// may be filename does not exists?
resp.writeHead(404, {
'Content-Type' : 'text/html'
});
// log this error into browser
resp.write(err.toString());
resp.end();
} else {
resp.writeHead(200, {
"Content-Type": "text/html"
});
resp.write(data.toString());
resp.end();
}
});
}
You can try this way
String input = "";
try {
int x = Integer.parseInt(input);
// You can use this method to convert String to int, But if input
//is not an int value then this will throws NumberFormatException.
System.out.println("Valid input");
}catch(NumberFormatException e) {
System.out.println("input is not an int value");
// Here catch NumberFormatException
// So input is not a int.
}
If you have some params, you can do this.
$results = DB::table('rooms')
->distinct()
->leftJoin('bookings', function($join) use ($param1, $param2)
{
$join->on('rooms.id', '=', 'bookings.room_type_id');
$join->on('arrival','=',DB::raw("'".$param1."'"));
$join->on('arrival','=',DB::raw("'".$param2."'"));
})
->where('bookings.room_type_id', '=', NULL)
->get();
and then return your query
return $results;
An extension to Joachim Isaksson's answer: Quite often I need something from the middle of a long file, e.g. lines 5001 to 5020, in which case you can combine head
with tail
:
head -5020 file.txt | tail -20 | grep x
This gets the first 5020 lines, then shows only the last 20 of those, then pipes everything to grep.
(Edited: fencepost error in my example numbers, added pipe to grep)
When you create more than one instance of MyClass , you will still only have only one instance of publicMethod in memory but in case of privilegedMethod you will end up creating lots of instances and staticMethod has no relationship with an object instance.
That's why prototypes save memory.
Also, if you change the parent object's properties, is the child's corresponding property hasn't been changed, it'll be updated.
$foo = 42;
$bar = function($x = 0) use ($foo){
return $x + $foo;
};
var_dump($bar(10)); // int(52)
UPDATE: there is now support for arrow functions, but i will let for someone that used it more to create the answer
Use File.ReadAllText(path_to_file)
to read
There also exists a UNIQUE KEY. The main difference between PRIMARY KEY and UNIQUE KEY is that the PRIMARY KEY never takes NULL value while a UNIQUE KEY may take NULL value. Also, there can be only one PRIMARY KEY in a table while UNIQUE KEY may be more than one.
git reflog
is your friend. Find the commit that you want to be on in that list and you can reset to it (for example:git reset --hard e870e41
).
(If you didn't commit your changes... you might be in trouble - commit early, and commit often!)
This is how I accomplished reading a table in javascript. Basically I drilled down into the rows and then I was able to drill down into the individual cells for each row. This should give you an idea
//gets table
var oTable = document.getElementById('myTable');
//gets rows of table
var rowLength = oTable.rows.length;
//loops through rows
for (i = 0; i < rowLength; i++){
//gets cells of current row
var oCells = oTable.rows.item(i).cells;
//gets amount of cells of current row
var cellLength = oCells.length;
//loops through each cell in current row
for(var j = 0; j < cellLength; j++){
/* get your cell info here */
/* var cellVal = oCells.item(j).innerHTML; */
}
}
UPDATED - TESTED SCRIPT
<table id="myTable">
<tr>
<td>A1</td>
<td>A2</td>
<td>A3</td>
</tr>
<tr>
<td>B1</td>
<td>B2</td>
<td>B3</td>
</tr>
</table>
<script>
//gets table
var oTable = document.getElementById('myTable');
//gets rows of table
var rowLength = oTable.rows.length;
//loops through rows
for (i = 0; i < rowLength; i++){
//gets cells of current row
var oCells = oTable.rows.item(i).cells;
//gets amount of cells of current row
var cellLength = oCells.length;
//loops through each cell in current row
for(var j = 0; j < cellLength; j++){
// get your cell info here
var cellVal = oCells.item(j).innerHTML;
alert(cellVal);
}
}
</script>
As of jQuery version 1.1.3, event.which
normalizes event.keyCode
and event.charCode
so you don't have to worry about browser compatibility issues. Documentation on event.which
event.which
will give 1, 2 or 3 for left, middle and right mouse buttons respectively so:
$('#element').mousedown(function(event) {
switch (event.which) {
case 1:
alert('Left Mouse button pressed.');
break;
case 2:
alert('Middle Mouse button pressed.');
break;
case 3:
alert('Right Mouse button pressed.');
break;
default:
alert('You have a strange Mouse!');
}
});
@Prashant Tukadiya answer works. But if you want to save the value in UserDefaults and then compare it to other date you get yout int64 truncated so it can cause problems. I found a solution.
Swift 4:
You can save int64 as string in UserDefaults:
let value: String(Date().millisecondsSince1970)
let stringValue = String(value)
UserDefaults.standard.set(stringValue, forKey: "int64String")
Like that you avoid Int truncation.
And then you can recover the original value:
let int64String = UserDefaults.standard.string(forKey: "int64String")
let originalValue = Int64(int64String!)
This allow you to compare it with other date values:
let currentTime = Date().millisecondsSince1970
let int64String = UserDefaults.standard.string(forKey: "int64String")
let originalValue = Int64(int64String!) ?? 0
if currentTime < originalValue {
return false
} else {
return true
}
Hope this helps someone who has same problem
On Linux when write()ing into a socket which the other side, unknown to you, closed will provoke a SIGPIPE signal/exception however you want to call it. However if you don't want to be caught out by the SIGPIPE you can use send() with the flag MSG_NOSIGNAL. The send() call will return with -1 and in this case you can check errno which will tell you that you tried to write a broken pipe (in this case a socket) with the value EPIPE which according to errno.h is equivalent to 32. As a reaction to the EPIPE you could double back and try to reopen the socket and try to send your information again.
Easy Way:
[Flags]
public enum MyFlags {
None = 0,
Susan = 1,
Alice = 2,
Bob = 4,
Eve = 8
}
To set the flags use logical "or" operator |
:
MyFlags f = new MyFlags();
f = MyFlags.Alice | MyFlags.Bob;
And to check if a flag is included use HasFlag
:
if(f.HasFlag(MyFlags.Alice)) { /* true */}
if(f.HasFlag(MyFlags.Eve)) { /* false */}
WINDOWS: If you have git for windows installed go to its folder.
Look in the bin directory. There is a sh.exe file. Run that.
Then type:
ssh-keygen -t rsa -C "your email here"
Follow through instructions and then type:
cat ~/.ssh/id_rsa.pub | clip
It copies the key to your clipboard. Now you can paste that public key to the server side.
In spring boot 2.x you need to reference provider specific properties.
The default, hikari can be set with spring.datasource.hikari.maximum-pool-size
.
Another possible option, but it depends if what you mean by before:
undefined = object()
class Widget:
def __init__(self):
self.bar = 1
def zoom(self):
print("zoom!")
a = Widget()
bar = getattr(a, "bar", undefined)
if bar is not undefined:
print("bar:%s" % (bar))
foo = getattr(a, "foo", undefined)
if foo is not undefined:
print("foo:%s" % (foo))
zoom = getattr(a, "zoom", undefined)
if zoom is not undefined:
zoom()
output:
bar:1
zoom!
This allows you to even check for None-valued attributes.
But! Be very careful you don't accidentally instantiate and compare undefined
multiple places because the is
will never work in that case.
because of what I was warning about in the above paragraph, having multiple undefineds that never match, I have recently slightly modified this pattern:
undefined = NotImplemented
NotImplemented
, not to be confused with NotImplementedError
, is a built-in: it semi-matches the intent of a JS undefined
and you can reuse its definition everywhere and it will always match. The drawbacks is that it is "truthy" in booleans and it can look weird in logs and stack traces (but you quickly get over it when you know it only appears in this context).
In modern browsers you do not need JQuery for this. Instead use
document.querySelectorAll('option:checked')
Or specify any DOM element instead of document
Immutable :
When you do some operation on a object, it creates a new object hence state is not modifiable as in case of string.
Mutable
When you perform some operation on a object, object itself modified no new obect created as in case of StringBuilder
I found the solution in this topic and I code this:
$cards = DB::select("SELECT
cards.id_card,
cards.hash_card,
cards.`table`,
users.name,
0 as total,
cards.card_status,
cards.created_at as last_update
FROM cards
LEFT JOIN users
ON users.id_user = cards.id_user
WHERE hash_card NOT IN ( SELECT orders.hash_card FROM orders )
UNION
SELECT
cards.id_card,
orders.hash_card,
cards.`table`,
users.name,
sum(orders.quantity*orders.product_price) as total,
cards.card_status,
max(orders.created_at) last_update
FROM menu.orders
LEFT JOIN cards
ON cards.hash_card = orders.hash_card
LEFT JOIN users
ON users.id_user = cards.id_user
GROUP BY hash_card
ORDER BY id_card ASC");
With PostgreSQL there are a number of date/time functions available, see here.
In your example, you could use:
SELECT * FROM myTable WHERE date_trunc('day', dt) = 'YYYY-MM-DD';
If you are running this query regularly, it is possible to create an index using the date_trunc
function as well:
CREATE INDEX date_trunc_dt_idx ON myTable ( date_trunc('day', dt) );
One advantage of this is there is some more flexibility with timezones if required, for example:
CREATE INDEX date_trunc_dt_idx ON myTable ( date_trunc('day', dt at time zone 'Australia/Sydney') );
SELECT * FROM myTable WHERE date_trunc('day', dt at time zone 'Australia/Sydney') = 'YYYY-MM-DD';
You can use appJar
for basic GUI development.
from appJar import gui
num=1
def myfcn(btnName):
global num
num +=1
win.setLabel("mylabel", num)
win = gui('Test')
win.addButtons(["Set"], [myfcn])
win.addLabel("mylabel", "Press the Button")
win.go()
See documentation at appJar site.
Installation is made with pip install appjar
from command line.
I know it is a bit late to answer this question, but it is the first entry in google, so I think it is worth to answer it.
The problem is not a coding problem, it is an architecture problem.
You have created an interface class Event: public Item
to define the methods which all events should implement. Then you have defined two types of events which inherits from class Event: public Item
; Arrival and Landing and then, you have added a method Landing* createNewLanding(Arrival* arrival);
from the landing functionality in the class Event: public Item
interface. You should move this method to the class Landing: public Event
class because it only has sense for a landing. class Landing: public Event
and class Arrival: public Event
class should know class Event: public Item
but event should not know class Landing: public Event
nor class Arrival: public Event
.
I hope this helps, regards, Alberto
Create an index.scss and there you can import all file structure you have. I will paste you my index from an enterprise project, maybe it will help other how to structure files in css:
@import 'base/_reset';
@import 'helpers/_variables';
@import 'helpers/_mixins';
@import 'helpers/_functions';
@import 'helpers/_helpers';
@import 'helpers/_placeholders';
@import 'base/_typography';
@import 'pages/_versions';
@import 'pages/_recording';
@import 'pages/_lists';
@import 'pages/_global';
@import 'forms/_buttons';
@import 'forms/_inputs';
@import 'forms/_validators';
@import 'forms/_fieldsets';
@import 'sections/_header';
@import 'sections/_navigation';
@import 'sections/_sidebar-a';
@import 'sections/_sidebar-b';
@import 'sections/_footer';
@import 'vendors/_ui-grid';
@import 'components/_modals';
@import 'components/_tooltip';
@import 'components/_tables';
@import 'components/_datepickers';
And you can watch them with gulp/grunt/webpack etc, like:
gulpfile.js
// SASS Task
var gulp = require('gulp');
var sass = require('gulp-sass');
//var concat = require('gulp-concat');
var uglifycss = require('gulp-uglifycss');
var sourcemaps = require('gulp-sourcemaps');
gulp.task('styles', function(){
return gulp
.src('sass/**/*.scss')
.pipe(sourcemaps.init())
.pipe(sass().on('error', sass.logError))
.pipe(concat('styles.css'))
.pipe(uglifycss({
"maxLineLen": 80,
"uglyComments": true
}))
.pipe(sourcemaps.write('.'))
.pipe(gulp.dest('./build/css/'));
});
gulp.task('watch', function () {
gulp.watch('sass/**/*.scss', ['styles']);
});
gulp.task('default', ['watch']);
I changed scrollable div to be with absolute position, and everything works for me
div.sidebar {
overflow: hidden;
background-color: green;
padding: 5px;
position: fixed;
right: 20px;
width: 40%;
top: 30px;
padding: 20px;
bottom: 30%;
}
div#fixed {
background: #76a7dc;
color: #fff;
height: 30px;
}
div#scrollable {
overflow-y: scroll;
background: lightblue;
position: absolute;
top:55px;
left:20px;
right:20px;
bottom:10px;
}
All are good answers explaining why you cannot modify string literals because they are placed in read-only memory. However, when push comes to shove, there is a way to do this. Check out this example:
#include <sys/mman.h>
#include <unistd.h>
#include <stddef.h>
#include <string.h>
#include <stdlib.h>
#include <stdio.h>
int take_me_back_to_DOS_times(const void *ptr, size_t len);
int main()
{
const *data = "Bender is always sober.";
printf("Before: %s\n", data);
if (take_me_back_to_DOS_times(data, sizeof(data)) != 0)
perror("Time machine appears to be broken!");
memcpy((char *)data + 17, "drunk!", 6);
printf("After: %s\n", data);
return 0;
}
int take_me_back_to_DOS_times(const void *ptr, size_t len)
{
int pagesize;
unsigned long long pg_off;
void *page;
pagesize = sysconf(_SC_PAGE_SIZE);
if (pagesize < 0)
return -1;
pg_off = (unsigned long long)ptr % (unsigned long long)pagesize;
page = ((char *)ptr - pg_off);
if (mprotect(page, len + pg_off, PROT_READ | PROT_WRITE | PROT_EXEC) == -1)
return -1;
return 0;
}
I have written this as part of my somewhat deeper thoughts on const-correctness, which you might find interesting (I hope :)).
Hope it helps. Good Luck!
To use the new date range picker, you can use the mat-date-range-input
and mat-date-range-picker
components.
Example
HTML
<mat-form-field>
<mat-label>Enter a date range</mat-label>
<mat-date-range-input [rangePicker]="picker">
<input matStartDate matInput placeholder="Start date">
<input matEndDate matInput placeholder="End date">
</mat-date-range-input>
<mat-datepicker-toggle matSuffix [for]="picker"></mat-datepicker-toggle>
<mat-date-range-picker #picker></mat-date-range-picker>
</mat-form-field>
You can read and learn more about this in their official documentation.
Unfortunately, they still haven't build a timepicker
on this release.
An official list of mime types can be found at The Internet Assigned Numbers Authority (IANA) . According to their list Content-Type
header for zip
is application/zip
.
The media type for rar
files is not officially registered at IANA but the unofficial commonly used mime-type value is application/x-rar-compressed
.
application/octet-stream
means as much as: "I send you a file stream and the content of this stream is not specified" (so it is true that it can be a zip
or rar
file as well). The server is supposed to detect what the actual content of the stream is.
Note: For upload it is not safe to rely on the mime type set in the Content-Type
header. The header is set on the client and can be set to any random value. Instead you can use the php file info functions to detect the file mime-type on the server.
If you want to download a zip
file and nothing else you should only set one single Accept
header value. Any additional values set will be used as a fallback in case the server cannot satisfy your in the Accept
header requested mime-type.
According to the WC3 specifications this:
application/zip, application/octet-stream
will be intrepreted as: "I prefer a application/zip
mime-type, but if you cannot deliver this an application/octet-stream
(a file stream) is also fine".
So only a single:
application/zip
Will guarantee you a zip
file (or a 406 - Not Acceptable
response in case the server is unable to satisfy your request).
This post asks the same question, but for linux - you may find it helpful. Send a ping to each IP on a subnet
nmap is probably the best tool to use, as it can help identify host OS as well as being faster. It is available for the windows platform on the nmap.org site
The answer is right on the error message, you need to indicate that it's standalone and therefore it doesn't conflict with the form controls:
[ngModelOptions]="{standalone: true}"
No, in C++ you cannot call a constructor from a constructor. What you can do, as warren pointed out, is:
Note that in the first case, you cannot reduce code duplication by calling one constructor from another. You can of course have a separate, private/protected, method that does all the initialization, and let the constructor mainly deal with argument handling.
Not sure if this answers the question. But I know this took me a while to figure out. I was looping through a website and all of sudden the name of the authors weren't there anymore. So needed a check statement.
if type(author) == type(None):
my if body
else:
my else body
Author can be any variable in this case, and None
can be any type that you are checking for.
This is for others who would have struggled like me to get this working....I wasted more than half a day on a seemingly trivial thing...
If you want to use SQL Express 2012 LocalDB from VS2010 you must have this patch installed http://www.microsoft.com/en-us/download/details.aspx?id=27756
Just like mentioned in the comments above I too had Microsoft .NET Framework Version 4.0.30319 SP1Rel and since its mentioned everywhere that you need "Framework 4.0.2 or Above" I thought I am good to go...
However, when I explicitly downloaded that 4.0.2 patch and installed it I got it working....
You could use what PHP has built in to assist...
$withoutExt = pathinfo($path, PATHINFO_DIRNAME) . '/' . pathinfo($path, PATHINFO_FILENAME);
Though if you are only dealing with a filename (.somefile.jpg
), you will get...
./somefile
Or use a regex...
$withoutExt = preg_replace('/\.' . preg_quote(pathinfo($path, PATHINFO_EXTENSION), '/') . '$/', '', $path);
If you don't have a path, but just a filename, this will work and be much terser...
$withoutExt = pathinfo($path, PATHINFO_FILENAME);
Of course, these both just look for the last period (.
).
For those still looking for a simple answer, check out git cherry. It compares actual diffs instead of commit hashes. That means it accommodates commits that have been cherry picked or rebased.
First checkout the branch you want to delete:
git checkout [branch-to-delete]
then use git cherry to compare it to your main development branch:
git cherry -v master
Example output:
+ 8a14709d08c99c36e907e47f9c4dacebeff46ecb Commit message
+ b30ccc3fb38d3d64c5fef079a761c7e0a5c7da81 Another commit message
- 85867e38712de930864c5edb7856342e1358b2a0 Yet another message
Note: The -v
flag is to include the commit message along with the SHA hash.
Lines with the '+' in front are in the branch-to-delete, but not the master branch. Those with a '-' in front have an equivalent commit in master.
For JUST the commits that aren't in master, combine cherry pick with grep:
git cherry -v master | grep "^\+"
Example output:
+ 8a14709d08c99c36e907e47f9c4dacebeff46ecb Commit message
+ b30ccc3fb38d3d64c5fef079a761c7e0a5c7da81 Another commit message
I guess that what you want to do is an UNION
of both tables.
If both tables have the same columns then you can just do
SELECT category_id, col1, col2, col3
FROM items_a
UNION
SELECT category_id, col1, col2, col3
FROM items_b
Else, you might have to do something like
SELECT category_id, col1, col2, col3
FROM items_a
UNION
SELECT category_id, col_1 as col1, col_2 as col2, col_3 as col3
FROM items_b
If you want a fixed size website this should be fairly simple:
// Override container sizes_x000D_
@container-sm: 700px;_x000D_
@container-md: 700px;_x000D_
@container-lg: 700px;_x000D_
_x000D_
// Fixate media queries to tablet view only (lower viewports set to 0px, desired one to 1px, and the higher to ~9999px)_x000D_
_x000D_
@screen-xs-min: 0px;_x000D_
@screen-sm-min: 1px;_x000D_
@screen-md-min: 9999px;_x000D_
@screen-lg-min: 9999px;_x000D_
_x000D_
// Disable responsive features such as navbar-collapse_x000D_
@grid-float-breakpoint: 9999px;
_x000D_
Unless you are using .container-fluid, then also add:
.container-fluid {
width: 700px;
}
body {
width: 700px + @general-min-width;
}
Find the file "config.inc.php" under your phpMyAdmin directory and edit the following lines:
$cfg['Servers'][$i]['auth_type'] = 'config'; // config, http, cookie
$cfg['Servers'][$i]['user'] = 'root'; // MySQL user
$cfg['Servers'][$i]['password'] = 'TYPE_YOUR_PASSWORD_HERE'; // MySQL password
Note that the password used in the 'password' field must be the same for the MySQL root password. Also, you should check if root login is allowed in this line:
$cfg['Servers'][$i]['AllowRoot'] = TRUE; // true = allow root login
This way you have your root password set.
If you have this :
a = [[1, 1], [2, 1],[3, 1]]
You can easily access this by using :
print(a[0][2])
a[0][1] = 7
print(a)
Credit to: curiousmind.jlion.com/exceltotextfile (Link no longer exists)
Script:
Sub MakeXML(iCaptionRow As Integer, iDataStartRow As Integer, sOutputFileName As String)
Dim Q As String
Q = Chr$(34)
Dim sXML As String
sXML = "<?xml version=" & Q & "1.0" & Q & " encoding=" & Q & "UTF-8" & Q & "?>"
sXML = sXML & "<rows>"
''--determine count of columns
Dim iColCount As Integer
iColCount = 1
While Trim$(Cells(iCaptionRow, iColCount)) > ""
iColCount = iColCount + 1
Wend
Dim iRow As Integer
iRow = iDataStartRow
While Cells(iRow, 1) > ""
sXML = sXML & "<row id=" & Q & iRow & Q & ">"
For icol = 1 To iColCount - 1
sXML = sXML & "<" & Trim$(Cells(iCaptionRow, icol)) & ">"
sXML = sXML & Trim$(Cells(iRow, icol))
sXML = sXML & "</" & Trim$(Cells(iCaptionRow, icol)) & ">"
Next
sXML = sXML & "</row>"
iRow = iRow + 1
Wend
sXML = sXML & "</rows>"
Dim nDestFile As Integer, sText As String
''Close any open text files
Close
''Get the number of the next free text file
nDestFile = FreeFile
''Write the entire file to sText
Open sOutputFileName For Output As #nDestFile
Print #nDestFile, sXML
Close
End Sub
Sub test()
MakeXML 1, 2, "C:\Users\jlynds\output2.xml"
End Sub
Surprisingly my solution is not yet given :) This is the simplest way for me. It doesn't need a function:
IFS=, eval 'joined="${foo[*]}"'
Note: This solution was observed to work well in non-POSIX mode. In POSIX mode, the elements are still joined properly, but IFS=,
becomes permanent.
TLS (Transport Level Security) is the slightly broader term that has replaced SSL (Secure Sockets Layer) in securing HTTP communications. So what you are being asked to do is enable SSL.
How reliable is your format? If the seperator is always exactly ': ', the following works. If not, a comparatively simple regex should do the job.
As long as you're working with fairly simple variable types, Python's eval function makes persisting variables to files surprisingly easy.
(The below gives you a dictionary, btw, which you mentioned was one of your prefered solutions).
def read_config(filename):
f = open(filename)
config_dict = {}
for lines in f:
items = lines.split(': ', 1)
config_dict[items[0]] = eval(items[1])
return config_dict
I almost always use curly-braces; however, in some cases where I'm writing tests, I do keyword packing/unpacking, and in these cases dict() is much more maintainable, as I don't need to change:
a=1,
b=2,
to:
'a': 1,
'b': 2,
It also helps in some circumstances where I think I might want to turn it into a namedtuple or class instance at a later time.
In the implementation itself, because of my obsession with optimisation, and when I don't see a particularly huge maintainability benefit, I'll always favour curly-braces.
In tests and the implementation, I would never use dict() if there is a chance that the keys added then, or in the future, would either:
dict(1foo=2)
raises a SyntaxError)Instead of creating a thread, and using runOnUIThread
, this is a perfect job for ASyncTask:
In onPreExecute
, create & show the dialog.
in doInBackground
prepare the data, but don't touch the UI -- store each prepared datum in a field, then call publishProgress
.
In onProgressUpdate
read the datum field & make the appropriate change/addition to the UI.
In onPostExecute
dismiss the dialog.
If you have other reasons to want a thread, or are adding UI-touching logic to an existing thread, then do a similar technique to what I describe, to run on UI thread only for brief periods, using runOnUIThread
for each UI step. In this case, you will store each datum in a local final
variable (or in a field of your class), and then use it within a runOnUIThread
block.
You can simplify the 5 through 21 part:
=IF(E9>21,"Text1",IF(E9>4,"Text2","Text3"))
You can also throw exceptions as documented here: http://blogs.msdn.com/b/youssefm/archive/2012/06/28/error-handling-in-asp-net-webapi.aspx
Note, to do what that article suggests, remember to include System.Net.Http
Nikita's point is an excellent one: don't confuse mature with bad. XML hasn't changed much.
JDOM would be another alternative to DOM4J.
You could do this:
var timer = NSTimer.scheduledTimerWithTimeInterval(0.1, target: self, selector: Selector("someSelector"), userInfo: nil, repeats: false)
func someSelector() {
// Something after a delay
}
let timer = Timer.scheduledTimer(timeInterval: 0.1, target: self, selector: #selector(someSelector), userInfo: nil, repeats: false)
func someSelector() {
// Something after a delay
}
Use onmouseleave
.
Or, in jQuery, use mouseleave()
It is the exact thing you are looking for. Example:
<div class="outer" onmouseleave="yourFunction()">
<div class="inner">
</div>
</div>
or, in jQuery:
$(".outer").mouseleave(function(){
//your code here
});
an example is here.
Just making simple to understand for beginners.
Check your git stash list with below command :
git stash list
And then apply with below command:
git stash apply stash@{n}
For example: I am applying my latest stash(latest is always index {0} on top of the stash list).
git stash apply stash@{0}
tv.setText( a1 + " ");
This will resolve your problem.
Get Network and Local Printer List in ASP.NET
This method uses the Windows Management Instrumentation or the WMI interface. It’s a technology used to get information about various systems (hardware) running on a Windows Operating System.
private void GetAllPrinterList()
{
ManagementScope objScope = new ManagementScope(ManagementPath.DefaultPath); //For the local Access
objScope.Connect();
SelectQuery selectQuery = new SelectQuery();
selectQuery.QueryString = "Select * from win32_Printer";
ManagementObjectSearcher MOS = new ManagementObjectSearcher(objScope, selectQuery);
ManagementObjectCollection MOC = MOS.Get();
foreach (ManagementObject mo in MOC)
{
lstPrinterList.Items.Add(mo["Name"].ToString());
}
}
Click here to download source and application demo
Demo of application which listed network and local printer
I tried the marked solution here first. It worked but it is kind hacky, and you need to redo it every time you update the gcc. I finally find a better solution by doing the followings:
Project
-> Properties
-> C/C++ General
-> Preprocessor Include Paths, Macros, etc.
Providers
-> CDT GCC built-in compiler settings
Use global provider shared between projects
(you can also modify the global provider if it fits your need)Command to get compiler specs
, add -std=c++11
at the endIndex
->Rebuild
Voila, easy and simple. Hopefully this helps.
Note: I am on Kepler. I am not sure if this works on earlier Eclipse.
Well, you don't want to execute 1000 query calls, but doing this is fine:
$stmt= array( 'array of statements' );
$query= 'INSERT INTO yourtable (col1,col2,col3) VALUES ';
foreach( $stmt AS $k => $v ) {
$query.= '(' .$v. ')'; // NOTE: you'll have to change to suit
if ( $k !== sizeof($stmt)-1 ) $query.= ', ';
}
$r= mysql_query($query);
Depending on your data source, populating the array might be as easy as opening a file and dumping the contents into an array via file()
.
with awk, just check for number of fields. no need regex
$ more file
hello
world
foo
bar
$ awk 'NF' file
hello
world
foo
bar
An elegant solution with dplyr would be:
df %>%
# recode empty strings "" by NAs
na_if("") %>%
# remove NAs
na.omit
If you want to serve .html files, you must add this <mvc:default-servlet-handler />
in your spring config file. .html files are static.
Hope that this can help someone.
eval()
can not handle the list object
tf.reset_default_graph()
a = tf.Variable(0.2, name="a")
b = tf.Variable(0.3, name="b")
z = tf.constant(0.0, name="z0")
for i in range(100):
z = a * tf.cos(z + i) + z * tf.sin(b - i)
grad = tf.gradients(z, [a, b])
init = tf.global_variables_initializer()
with tf.Session() as sess:
init.run()
print("z:", z.eval())
print("grad", grad.eval())
but Session.run()
can
print("grad", sess.run(grad))
correct me if I am wrong
I recommend you start reading the documentation (4.6.18. Formatting cells). When applying a lot of formatting it's better to use applyFromArray()
According to the documentation this method is also suppose to be faster when you're setting many style properties. There's an annex where you can find all the possible keys for this function.
This will work for you:
$phpExcel = new PHPExcel();
$styleArray = array(
'font' => array(
'bold' => true,
'color' => array('rgb' => 'FF0000'),
'size' => 15,
'name' => 'Verdana'
));
$phpExcel->getActiveSheet()->getCell('A1')->setValue('Some text');
$phpExcel->getActiveSheet()->getStyle('A1')->applyFromArray($styleArray);
To apply font style to complete excel document:
$styleArray = array(
'font' => array(
'bold' => true,
'color' => array('rgb' => 'FF0000'),
'size' => 15,
'name' => 'Verdana'
));
$phpExcel->getDefaultStyle()
->applyFromArray($styleArray);
try putting username in double quote "username", somehow that fixed for me.
You can implement Drag&Drop in WinForms and WPF.
You should add mousemove event:
private void YourElementControl_MouseMove(object sender, MouseEventArgs e)
{
...
if (e.Button == MouseButtons.Left)
{
DoDragDrop(new DataObject(DataFormats.FileDrop, new string[] { PathToFirstFile,PathToTheNextOne }), DragDropEffects.Move);
}
...
}
You should add DragDrop event:
private void YourElementControl_DragDrop(object sender, DragEventArgs e)
{
...
foreach (string path in (string[])e.Data.GetData(DataFormats.FileDrop))
{
File.Copy(path, DirPath + Path.GetFileName(path));
}
...
}
I've seen many variants of this problem. One of the main differences (that determines the difficulty) is whether there is some centralized attempt to have a "smart and efficient system" that would have load balancing (e.g., send more idle elevators to lobby in morning). If that is the case, the design will include a whole subsystem with really fun design.
A full design is obviously too much to present here and there are many altenatives. The breadth is also not clear. In an interview, they'll try to figure out how you would think. However, these are some of the things you would need:
Representation of the central controller (assuming there is one).
Representations of elevators
Representations of the interface units of the elevator (these may be different from elevator to elevator). Obviously also call buttons on every floor, etc.
Representations of the arrows or indicators on each floor (almost a "view" of the elevator model).
Representation of a human and cargo (may be important for factoring in maximal loads)
Representation of the building (in some cases, as certain floors may be blocked at times, etc.)
Why not to use Python 3's inbuilt ast library's function literal_eval. It is better to use literal_eval instead of eval
import ast
str_of_dict = "{'key1': 'key1value', 'key2': 'key2value'}"
ast.literal_eval(str_of_dict)
will give output as actual Dictionary
{'key1': 'key1value', 'key2': 'key2value'}
And If you are asking to convert a Dictionary to a String then, How about using str() method of Python.
Suppose the dictionary is :
my_dict = {'key1': 'key1value', 'key2': 'key2value'}
And this will be done like this :
str(my_dict)
Will Print :
"{'key1': 'key1value', 'key2': 'key2value'}"
This is the easy as you like.
Run:
docker version
If docker is running you will see:
Client: Docker Engine - Community
Version: ...
[omitted]
Server: Docker Engine - Community
Engine:
Version: ...
[omitted]
If docker is not running you will see:
Client: Docker Engine - Community
Version: ...
[omitted]
Error response from daemon: Bad response from Docker engine
The backslash \
is reserved for use as an escape character in Javascript.
To use a backslash literally you need to use two backslashes
\\
More compact way to get the difference between two datetime objects and then convert the difference into seconds is shown below (Python 3x):
from datetime import datetime
time1 = datetime.strftime('18 01 2021', '%d %m %Y')
time2 = datetime.strftime('19 01 2021', '%d %m %Y')
difference = time2 - time1
difference_in_seconds = difference.total_seconds()
You have to roll your own. E.g.,
/* from :http://www.builderau.com.au/architect/database/soa/Create-functions-to-join-and-split-strings-in-Oracle/0,339024547,339129882,00.htm
select split('foo,bar,zoo') from dual;
select * from table(split('foo,bar,zoo'));
pipelined function is SQL only (no PL/SQL !)
*/
create or replace type split_tbl as table of varchar2(32767);
/
show errors
create or replace function split
(
p_list varchar2,
p_del varchar2 := ','
) return split_tbl pipelined
is
l_idx pls_integer;
l_list varchar2(32767) := p_list;
l_value varchar2(32767);
begin
loop
l_idx := instr(l_list,p_del);
if l_idx > 0 then
pipe row(substr(l_list,1,l_idx-1));
l_list := substr(l_list,l_idx+length(p_del));
else
pipe row(l_list);
exit;
end if;
end loop;
return;
end split;
/
show errors;
/* An own implementation. */
create or replace function split2(
list in varchar2,
delimiter in varchar2 default ','
) return split_tbl as
splitted split_tbl := split_tbl();
i pls_integer := 0;
list_ varchar2(32767) := list;
begin
loop
i := instr(list_, delimiter);
if i > 0 then
splitted.extend(1);
splitted(splitted.last) := substr(list_, 1, i - 1);
list_ := substr(list_, i + length(delimiter));
else
splitted.extend(1);
splitted(splitted.last) := list_;
return splitted;
end if;
end loop;
end;
/
show errors
declare
got split_tbl;
procedure print(tbl in split_tbl) as
begin
for i in tbl.first .. tbl.last loop
dbms_output.put_line(i || ' = ' || tbl(i));
end loop;
end;
begin
got := split2('foo,bar,zoo');
print(got);
print(split2('1 2 3 4 5', ' '));
end;
/
I think best option is like same:
foreach ($lists as $key=>$value) {
echo $key+1;
}
it is easy and normally
You can add style to your text:
style="-webkit-tap-highlight-color: rgba(0, 0, 0, 0);
text-shadow: rgb(255, 255, 255) -2px -2px 0px, rgb(255, 255, 255) -2px 2px 0px,
rgb(255, 255, 255) 2px -2px 0px, rgb(255, 255, 255) 2px 2px 0px;"
White, in this example. Does not work in IE :)
Actually, we really do not need to import any python library. We can separate the year, month, date using simple SQL. See the below example,
+----------+
| _c0|
+----------+
|1872-11-30|
|1873-03-08|
|1874-03-07|
|1875-03-06|
|1876-03-04|
|1876-03-25|
|1877-03-03|
|1877-03-05|
|1878-03-02|
|1878-03-23|
|1879-01-18|
I have a date column in my data frame which contains the date, month and year and assume I want to extract only the year from the column.
df.createOrReplaceTempView("res")
sqlDF = spark.sql("SELECT EXTRACT(year from `_c0`) FROM res ")
Here I'm creating a temporary view and store the year values using this single line and the output will be,
+-----------------------+
|year(CAST(_c0 AS DATE))|
+-----------------------+
| 1872|
| 1873|
| 1874|
| 1875|
| 1876|
| 1876|
| 1877|
| 1877|
| 1878|
| 1878|
| 1879|
| 1879|
| 1879|
POCOs(Plain old CLR objects) are simply entities of your Domain. Normally when we use entity framework the entities are generated automatically for you. This is great but unfortunately these entities are interspersed with database access functionality which is clearly against the SOC (Separation of concern). POCOs are simple entities without any data access functionality but still gives the capabilities all EntityObject functionalities like
Here is a good start for this
You can also generate POCOs so easily from your existing Entity framework project using Code generators.
For IntelliJ IDEA 2017.2 I did the following to fix this issue: Go to your project structure Now go to SDKs under platform settings and click the green add button. Add your JDK path. In my case it was this path C:\Program Files\Java\jdk1.8.0_144 Now Just go Project under Project settings and select the project SDK.
They are hint to the compiler to emit instructions that will cause branch prediction to favour the "likely" side of a jump instruction. This can be a big win, if the prediction is correct it means that the jump instruction is basically free and will take zero cycles. On the other hand if the prediction is wrong, then it means the processor pipeline needs to be flushed and it can cost several cycles. So long as the prediction is correct most of the time, this will tend to be good for performance.
Like all such performance optimisations you should only do it after extensive profiling to ensure the code really is in a bottleneck, and probably given the micro nature, that it is being run in a tight loop. Generally the Linux developers are pretty experienced so I would imagine they would have done that. They don't really care too much about portability as they only target gcc, and they have a very close idea of the assembly they want it to generate.
I think this is the cleanest solution:
class MyTableViewCell: UITableViewCell {
override func awakeFromNib() {
super.awakeFromNib()
layoutMargins = UIEdgeInsetsMake(8, 0, 8, 0)
}
}
Checked the evironment path, I have two paths navigated to two pip.exe and this caused this error. After deleting the redundant one and restart the PC, this issue has been fixed. The same issue for the jupyter command fixed as well.
If you write
a = [1, 2, 3, 4, 5]
print(*a, sep = ',')
You get this output: 1,2,3,4,5
>ssh user@serverip -p portnumber
>sudo bash (if user does not have bash shell else skip this line)
>cd /home/user/.ssh
>echo ssh_rsa...this is the key >> authorized_keys