<?php
$dbName = $_SERVER["DOCUMENT_ROOT"] . "products\products.mdb";
if (!file_exists($dbName)) {
die("Could not find database file.");
}
$db = new PDO("odbc:DRIVER={Microsoft Access Driver (*.mdb)}; DBQ=$dbName; Uid=; Pwd=;");
A successful connection will allow SQL commands to be executed from PHP to read or write the database. If, however, you get the error message “PDOException Could not find driver” then it’s likely that the PDO ODBC driver is not installed. Use the phpinfo() function to check your installation for references to PDO.
If an entry for PDO ODBC is not present, you will need to ensure your installation includes the PDO extension and ODBC drivers. To do so on Windows, uncomment the line extension=php_pdo_odbc.dll in php.ini, restart Apache, and then try to connect to the database again.
With the driver installed, the output from phpinfo() should include information like this:https://www.diigo.com/item/image/5kc39/hdse
Replace the username and password with Integrated Security=SSPI;
So the connection string should be
<connectionStrings>
<add name="NorthwindContex"
connectionString="data source=localhost;
initial catalog=northwind;persist security info=True;
Integrated Security=SSPI;"
providerName="System.Data.SqlClient" />
</connectionStrings>
Adding MaxHeight
and VerticalScrollBarVisibility="Auto"
on the DataGrid
solved my problem.
It depends..
SELECT x.col
FROM big_table x
WHERE x.key IN( SELECT key FROM really_big_table );
would not be relatively slow the isn't much to limit size of what the query check to see if they key is in. EXISTS would be preferable in this case.
But, depending on the DBMS's optimizer, this could be no different.
As an example of when EXISTS is better
SELECT x.col
FROM big_table x
WHERE EXISTS( SELECT key FROM really_big_table WHERE key = x.key);
AND id = very_limiting_criteria
SUMMARY: In ASP.NET, every Web page derives from the System.Web.UI.Page class. The Page class aggregates an instance of the HttpSession object for session data. The Page class exposes different events and methods for customization. In particular, the OnInit method is used to set the initialize state of the Page object. If the request does not have the Session cookie, a new Session cookie will be issued to the requester.
EDIT:
Session: A Concept for Beginners
SUMMARY: Session is created when user sends a first request to the server for any page in the web application, the application creates the Session and sends the Session ID back to the user with the response and is stored in the client machine as a small cookie. So ideally the "machine that has disabled the cookies, session information will not be stored".
in laravel-8 default remove namespace prefix so you can set old way in laravel-7 like:
in RouteServiceProvider.php
add this variable
protected $namespace = 'App\Http\Controllers';
and update boot
method
public function boot()
{
$this->configureRateLimiting();
$this->routes(function () {
Route::middleware('web')
->namespace($this->namespace)
->group(base_path('routes/web.php'));
Route::prefix('api')
->middleware('api')
->namespace($this->namespace)
->group(base_path('routes/api.php'));
});
}
I've managed to successfully install wkhtmltopdf-amd64 on my shared hosting account without root access.
Here's what i did:
Downloaded the relevant static binary v0.10.0 from here: http://code.google.com/p/wkhtmltopdf/downloads/list
EDIT: The above has moved to here
via ssh on my shared host typed the following:
$ wget {relavant url to binary from link above}
$ tar -xvf {filename of above wget'd file}
you'll then have the binary on your host and will be able to run it regardless of if its in the /usr/bin/ folder or not. (or at least i was able to)
To test:
$ ./wkhtmltopdf-amd64 http://www.example.com example.pdf
./
just to be sure.Worked for me anyway
You can use round function. Here some example
numpy.round([2.15295647e+01, 8.12531501e+00, 3.97113829e+00, 1.00777250e+01],2)
array([ 21.53, 8.13, 3.97, 10.08])
IF you want change just display representation, I would not recommended to alter printing format globally, as it suggested above. I would format my output in place.
>>a=np.array([2.15295647e+01, 8.12531501e+00, 3.97113829e+00, 1.00777250e+01])
>>> print([ "{:0.2f}".format(x) for x in a ])
['21.53', '8.13', '3.97', '10.08']
Have you tried performing an svn cleanup?
$ git rebase --abort
Run this code at any time if you want to undo the git rebase
$ git rebase -i HEAD~2
To reapply last two commits. The above command will open a code editor
After :wq you will be in active rebase mode
Note: You'll get another editor if no warning/error messages, If there is an error or warning another editor will not show, you may abort by runnning
$ git rebase --abort
if you see an error or warning else just continue by running $ git rebase --continue
You will see your 2 commit message. Choose one or write your own commit message, save and quit [:wq]
Note 2: You may need to force push your changes to the remote repo if you run rebase command
$ git push -f
$ git push -f origin master
I used @jensgram solution to hide a div that contains a disabled input. So I hide the entire parent of the input.
Here is the code :
div:has(>input[disabled=disabled]) {
display: none;
}
Maybe it could help some of you.
string s = (string)o; // 1
Throws InvalidCastException if o
is not a string
. Otherwise, assigns o
to s
, even if o
is null
.
string s = o as string; // 2
Assigns null
to s
if o
is not a string
or if o
is null
. For this reason, you cannot use it with value types (the operator could never return null
in that case). Otherwise, assigns o
to s
.
string s = o.ToString(); // 3
Causes a NullReferenceException if o
is null
. Assigns whatever o.ToString()
returns to s
, no matter what type o
is.
Use 1 for most conversions - it's simple and straightforward. I tend to almost never use 2 since if something is not the right type, I usually expect an exception to occur. I have only seen a need for this return-null type of functionality with badly designed libraries which use error codes (e.g. return null = error, instead of using exceptions).
3 is not a cast and is just a method invocation. Use it for when you need the string representation of a non-string object.
XmlDocument doc = new XmlDocument();
doc.Load("MonFichierXML.xml");
XmlNode node = doc.SelectSingleNode("Magasin");
XmlNodeList prop = node.SelectNodes("Items");
foreach (XmlNode item in prop)
{
items Temp = new items();
Temp.AssignInfo(item);
lstitems.Add(Temp);
}
You can't: It's a security feature in all modern browsers.
For IE8, it's off by default, but can be reactivated using a security setting:
When a file is selected by using the input type=file object, the value of the value property depends on the value of the "Include local directory path when uploading files to a server" security setting for the security zone used to display the Web page containing the input object.
The fully qualified filename of the selected file is returned only when this setting is enabled. When the setting is disabled, Internet Explorer 8 replaces the local drive and directory path with the string C:\fakepath\ in order to prevent inappropriate information disclosure.
In all other current mainstream browsers I know of, it is also turned off. The file name is the best you can get.
More detailed info and good links in this question. It refers to getting the value server-side, but the issue is the same in JavaScript before the form's submission.
Hex to Decimal Conversion
Convert.ToInt32(number, 16);
Decimal to Hex Conversion
int.Parse(number, System.Globalization.NumberStyles.HexNumber)
If you are in the console window for the device and if you use Teraterm, then from the Menu do a File | Log and it will automatically save to file.
A server-side solution is more compatible, until the "download" attribute is implemented in all the browsers.
One Python example could be a custom HTTP request handler for a filestore. The links that point to the filestore are generated like this:
http://www.myfilestore.com/filestore/13/130787e71/download_as/desiredName.pdf
Here is the code:
class HTTPFilestoreHandler(SimpleHTTPRequestHandler):
def __init__(self, fs_path, *args):
self.fs_path = fs_path # Filestore path
SimpleHTTPRequestHandler.__init__(self, *args)
def send_head(self):
# Overwrite SimpleHTTPRequestHandler.send_head to force download name
path = self.path
get_index = (path == '/')
self.log_message("path: %s" % path)
if '/download_as/' in path:
p_parts = path.split('/download_as/')
assert len(p_parts) == 2, 'Bad download link:' + path
path, download_as = p_parts
path = self.translate_path(path )
f = None
if os.path.isdir(path):
if not self.path.endswith('/'):
# Redirect browser - doing basically what Apache does
self.send_response(301)
self.send_header("Location", self.path + "/")
self.end_headers()
return None
else:
return self.list_directory(path)
ctype = self.guess_type(path)
try:
f = open(path, 'rb')
except IOError:
self.send_error(404, "File not found")
return None
self.send_response(200)
self.send_header("Content-type", ctype)
fs = os.fstat(f.fileno())
self.send_header("Expires", '0')
self.send_header("Last-Modified", self.date_time_string(fs.st_mtime))
self.send_header("Cache-Control", 'must-revalidate, post-check=0, pre-check=0')
self.send_header("Content-Transfer-Encoding", 'binary')
if download_as:
self.send_header("Content-Disposition", 'attachment; filename="%s"' % download_as)
self.send_header("Content-Length", str(fs[6]))
self.send_header("Connection", 'close')
self.end_headers()
return f
class HTTPFilestoreServer:
def __init__(self, fs_path, server_address):
def handler(*args):
newHandler = HTTPFilestoreHandler(fs_path, *args)
newHandler.protocol_version = "HTTP/1.0"
self.server = BaseHTTPServer.HTTPServer(server_address, handler)
def serve_forever(self, *args):
self.server.serve_forever(*args)
def start_server(fs_path, ip_address, port):
server_address = (ip_address, port)
httpd = HTTPFilestoreServer(fs_path, server_address)
sa = httpd.server.socket.getsockname()
print "Serving HTTP on", sa[0], "port", sa[1], "..."
httpd.serve_forever()
With VSCode you can find the merge conflicts easily with the following UI.
(if you do not have the topbar, set "editor.codeLens": true
in User Preferences)
It indicates the current change that you have and incoming change from the server. This makes it easy to resolve the conflicts - just press the buttons above <<<< HEAD
.
If you have multiple changes and want to apply all of them at once - open command palette (View -> Command Palette) and start typing merge - multiple options will appear including Merge Conflict: Accept Incoming
, etc.
I write a method to show the four corners of the data and monkey-patch to dataframe to do so:
def _sw(df, up_rows=10, down_rows=5, left_cols=4, right_cols=3, return_df=False):
''' display df data at four corners
A,B (up_pt)
C,D (down_pt)
parameters : up_rows=10, down_rows=5, left_cols=4, right_cols=3
usage:
df = pd.DataFrame(np.random.randn(20,10), columns=list('ABCDEFGHIJKLMN')[0:10])
df.sw(5,2,3,2)
df1 = df.set_index(['A','B'], drop=True, inplace=False)
df1.sw(5,2,3,2)
'''
#pd.set_printoptions(max_columns = 80, max_rows = 40)
ncol, nrow = len(df.columns), len(df)
# handle columns
if ncol <= (left_cols + right_cols) :
up_pt = df.ix[0:up_rows, :] # screen width can contain all columns
down_pt = df.ix[-down_rows:, :]
else: # screen width can not contain all columns
pt_a = df.ix[0:up_rows, 0:left_cols]
pt_b = df.ix[0:up_rows, -right_cols:]
pt_c = df[-down_rows:].ix[:,0:left_cols]
pt_d = df[-down_rows:].ix[:,-right_cols:]
up_pt = pt_a.join(pt_b, how='inner')
down_pt = pt_c.join(pt_d, how='inner')
up_pt.insert(left_cols, '..', '..')
down_pt.insert(left_cols, '..', '..')
overlap_qty = len(up_pt) + len(down_pt) - len(df)
down_pt = down_pt.drop(down_pt.index[range(overlap_qty)]) # remove overlap rows
dt_str_list = down_pt.to_string().split('\n') # transfer down_pt to string list
# Display up part data
print up_pt
start_row = (1 if df.index.names[0] is None else 2) # start from 1 if without index
# Display omit line if screen height is not enought to display all rows
if overlap_qty < 0:
print "." * len(dt_str_list[start_row])
# Display down part data row by row
for line in dt_str_list[start_row:]:
print line
# Display foot note
print "\n"
print "Index :",df.index.names
print "Column:",",".join(list(df.columns.values))
print "row: %d col: %d"%(len(df), len(df.columns))
print "\n"
return (df if return_df else None)
DataFrame.sw = _sw #add a method to DataFrame class
Here is the sample:
>>> df = pd.DataFrame(np.random.randn(20,10), columns=list('ABCDEFGHIJKLMN')[0:10])
>>> df.sw()
A B C D .. H I J
0 -0.8166 0.0102 0.0215 -0.0307 .. -0.0820 1.2727 0.6395
1 1.0659 -1.0102 -1.3960 0.4700 .. 1.0999 1.1222 -1.2476
2 0.4347 1.5423 0.5710 -0.5439 .. 0.2491 -0.0725 2.0645
3 -1.5952 -1.4959 2.2697 -1.1004 .. -1.9614 0.6488 -0.6190
4 -1.4426 -0.8622 0.0942 -0.1977 .. -0.7802 -1.1774 1.9682
5 1.2526 -0.2694 0.4841 -0.7568 .. 0.2481 0.3608 -0.7342
6 0.2108 2.5181 1.3631 0.4375 .. -0.1266 1.0572 0.3654
7 -1.0617 -0.4743 -1.7399 -1.4123 .. -1.0398 -1.4703 -0.9466
8 -0.5682 -1.3323 -0.6992 1.7737 .. 0.6152 0.9269 2.1854
9 0.2361 0.4873 -1.1278 -0.2251 .. 1.4232 2.1212 2.9180
10 2.0034 0.5454 -2.6337 0.1556 .. 0.0016 -1.6128 -0.8093
..............................................................
15 1.4091 0.3540 -1.3498 -1.0490 .. 0.9328 0.3668 1.3948
16 0.4528 -0.3183 0.4308 -0.1818 .. 0.1295 1.2268 0.1365
17 -0.7093 1.3991 0.9501 2.1227 .. -1.5296 1.1908 0.0318
18 1.7101 0.5962 0.8948 1.5606 .. -0.6862 0.9558 -0.5514
19 1.0329 -1.2308 -0.6896 -0.5112 .. 0.2719 1.1478 -0.1459
Index : [None]
Column: A,B,C,D,E,F,G,H,I,J
row: 20 col: 10
>>> df.sw(4,2,3,4)
A B C .. G H I J
0 -0.8166 0.0102 0.0215 .. 0.3671 -0.0820 1.2727 0.6395
1 1.0659 -1.0102 -1.3960 .. 1.0984 1.0999 1.1222 -1.2476
2 0.4347 1.5423 0.5710 .. 1.6675 0.2491 -0.0725 2.0645
3 -1.5952 -1.4959 2.2697 .. 0.4856 -1.9614 0.6488 -0.6190
4 -1.4426 -0.8622 0.0942 .. -0.0947 -0.7802 -1.1774 1.9682
..............................................................
18 1.7101 0.5962 0.8948 .. -0.8592 -0.6862 0.9558 -0.5514
19 1.0329 -1.2308 -0.6896 .. -0.3954 0.2719 1.1478 -0.1459
Index : [None]
Column: A,B,C,D,E,F,G,H,I,J
row: 20 col: 10
Here is a solution with requests Response class. It is cleaner IMHO.
from unittest.mock import patch
from requests.models import Response
def mocked_request_get(*args, **kwargs):
response_content = None
request_url = kwargs.get('url', None)
if request_url == 'aurl':
response_content = json.dumps('a response')
elif request_url == 'burl':
response_content = json.dumps('b response')
elif request_url == 'curl':
response_content = json.dumps('c response')
response = Response()
response.status_code = 200
response._content = str.encode(response_content)
return response
@mock.patch('requests.get', side_effect=mocked_requests_get)
def test_fetch(self, mock_get):
response = call_your_view()
assert ...
For Python2.7 - modifying MYGz's answer to not strip milliseconds:
from datetime import datetime
d = datetime.strptime("20.12.2016 09:38:42,76", "%d.%m.%Y %H:%M:%S,%f").strftime('%s.%f')
d_in_ms = int(float(d)*1000)
print(d_in_ms)
print(datetime.fromtimestamp(float(d)))
Output:
1482248322760
2016-12-20 09:38:42.760000
Take care not to include
#include <string.h>
but only
#include <string>
It took me 1 hour to find this in my code.
Hope this can help
A minimalist implementation of the \url
macro that uses only Tex primitives:
\def\url#1{\expandafter\string\csname #1\endcsname}
This url absolutely won't break over lines, though; the hypperef package is better for that.
INSERT INTO target( userid, rightid, count )
SELECT userid, rightid, count
FROM batch
WHERE NOT EXISTS (
SELECT * FROM target t2, batch b2
WHERE t2.userid = b2.userid
-- ... other keyfields ...
)
;
BTW: if you want the whole batch to fail in case of a duplicate, then (given a primary key constraint)
INSERT INTO target( userid, rightid, count )
SELECT userid, rightid, count
FROM batch
;
will do exactly what you want: either it succeeds, or it fails.
If ctrl+c doesn't respond right away because your script is too long/complex, hold it.
The break command doesn't run when matlab is executing some of its deeper scripts, and either it won't log a ctrl sequence in the buffer, or it clears the buffer just before or just after it completes those pieces of code. In either case, when matlab returns to execute more of your script, it will recognize that you are holding ctrl+c and terminate.
For longer running programs, I usually try to find a good place to provide a status update and I always accompany that with some measure of time using tic and toc. Depending on what I am doing, I might use run time, segment time, some kind of average, etc...
For really long running programs, I found this to be exceptionally useful http://www.mathworks.com/matlabcentral/fileexchange/16649-send-text-message-to-cell-phone/content/send_text_message.m
but it looks like they have some newer functions for this too.
To set your App or any individual activity display in Full Screen mode, insert the code
<application
android:icon="@drawable/icon"
android:label="@string/app_name"
android:theme="@android:style/Theme.NoTitleBar.Fullscreen">
in AndroidManifest.xml, under application or activity tab.
TL;DR version: remote-tracking branch origin/master
used to exist, but does not now, so local branch source
is tracking something that does not exist, which is suspicious at best—it means a different Git feature is unable to do anything for you—and Git is warning you about it. You have been getting along just fine without having the "upstream tracking" feature work as intended, so it's up to you whether to change anything.
For another take on upstream settings, see Why do I have to "git push --set-upstream origin <branch>"?
This warning is a new thing in Git, appearing first in Git 1.8.5. The release notes contain just one short bullet-item about it:
- "git branch -v -v" (and "git status") did not distinguish among a branch that is not based on any other branch, a branch that is in sync with its upstream branch, and a branch that is configured with an upstream branch that no longer exists.
To describe what it means, you first need to know about "remotes", "remote-tracking branches", and how Git handles "tracking an upstream". (Remote-tracking branches is a terribly flawed term—I've started using remote-tracking names instead, which I think is a slight improvement. Below, though, I'll use "remote-tracking branch" for consistency with Git documentation.)
Each "remote" is simply a name, like origin
or octopress
in this case. Their purpose is to record things like the full URL of the places from which you git fetch
or git pull
updates. When you use git fetch remote,
1 Git goes to that remote (using the saved URL) and brings over the appropriate set of updates. It also records the updates, using "remote-tracking branches".
A "remote-tracking branch" (or remote-tracking name) is simply a recording of a branch name as-last-seen on some "remote". Each remote is itself a Git repository, so it has branches. The branches on remote "origin" are recorded in your local repository under remotes/origin/
. The text you showed says that there's a branch named source
on origin
, and branches named 2.1
, linklog
, and so on on octopress
.
(A "normal" or "local" branch, of course, is just a branch-name that you have created in your own repository.)
Last, you can set up a (local) branch to "track" a "remote-tracking branch". Once local branch L
is set to track remote-tracking branch R
, Git will call R
its "upstream" and tell you whether you're "ahead" and/or "behind" the upstream (in terms of commits). It's normal (even recommend-able) for the local branch and remote-tracking branches to use the same name (except for the remote prefix part), like source
and origin/source
, but that's not actually necessary.
And in this case, that's not happening. You have a local branch source
tracking a remote-tracking branch origin/master
.
You're not supposed to need to know the exact mechanics of how Git sets up a local branch to track a remote one, but they are relevant below, so I'll show how this works. We start with your local branch name, source
. There are two configuration entries using this name, spelled branch.source.remote
and branch.source.merge
. From the output you showed, it's clear that these are both set, so that you'd see the following if you ran the given commands:
$ git config --get branch.source.remote
origin
$ git config --get branch.source.merge
refs/heads/master
Putting these together,2 this tells Git that your branch source
tracks your "remote-tracking branch", origin/master
.
But now look at the output of git branch -a
, which shows all the local and remote-tracking branch names in your repository. The remote-tracking names are listed under remotes/
... and there is no remotes/origin/master
. Presumably there was, at one time, but it's gone now.
Git is telling you that you can remove the tracking information with --unset-upstream
. This will clear out both branch.source.origin
and branch.source.merge
, and stop the warning.
It seems fairly likely that what you want, though, is to switch from tracking origin/master
, to tracking something else: probably origin/source
, but maybe one of the octopress/
names.
You can do this with git branch --set-upstream-to
,3 e.g.:
$ git branch --set-upstream-to=origin/source
(assuming you're still on branch "source", and that origin/source
is the upstream you want—there is no way for me to tell which one, if any, you actually want, though).
(See also How do you make an existing Git branch track a remote branch?)
I think the way you got here is that when you first did a git clone
, the thing you cloned-from had a branch master
. You also had a branch master
, which was set to track origin/master
(this is a normal, standard setup for git). This meant you had branch.master.remote
and branch.master.merge
set, to origin
and refs/heads/master
. But then your origin
remote changed its name from master
to source
. To match, I believe you also changed your local name from master
to source
. This changed the names of your settings, from branch.master.remote
to branch.source.remote
and from branch.master.merge
to branch.source.merge
... but it left the old values, so branch.source.merge
was now wrong.
It was at this point that the "upstream" linkage broke, but in Git versions older than 1.8.5, Git never noticed the broken setting. Now that you have 1.8.5, it's pointing this out.
That covers most of the questions, but not the "do I need to fix it" one. It's likely that you have been working around the broken-ness for years now, by doing git pull remote branch
(e.g., git pull origin source
). If you keep doing that, it will keep working around the problem—so, no, you don't need to fix it. If you like, you can use --unset-upstream
to remove the upstream and stop the complaints, and not have local branch source
marked as having any upstream at all.
The point of having an upstream is to make various operations more convenient. For instance, git fetch
followed by git merge
will generally "do the right thing" if the upstream is set correctly, and git status
after git fetch
will tell you whether your repo matches the upstream one, for that branch.
If you want the convenience, re-set the upstream.
1git pull
uses git fetch
, and as of Git 1.8.4, this (finally!) also updates the "remote-tracking branch" information. In older versions of Git, the updates did not get recorded in remote-tracking branches with git pull
, only with git fetch
. Since your Git must be at least version 1.8.5 this is not an issue for you.
2Well, this plus a configuration line I'm deliberately ignoring that is found under remote.origin.fetch
. Git has to map the "merge" name to figure out that the full local name for the remote-branch is refs/remotes/origin/master
. The mapping almost always works just like this, though, so it's predictable that master
goes to origin/master
.
3Or, with git config
. If you just want to set the upstream to origin/source
the only part that has to change is branch.source.merge
, and git config branch.source.merge refs/heads/source
would do it. But --set-upstream-to
says what you want done, rather than making you go do it yourself manually, so that's a "better way".
If a case-insensitive comparison is acceptable, just use =
:
=IF(A1="ENG",1,0)
This is documented in the 'R Installation and Administration' manual that came with your installation.
On my Linux box:
R> .libPaths()
[1] "/usr/local/lib/R/site-library" "/usr/lib/R/site-library"
[3] "/usr/lib/R/library"
R>
meaning that the default path is the first of these. You can override that via an argument to both install.packages()
(from inside R) or R CMD INSTALL
(outside R).
You can also override by setting the R_LIBS_USER variable.
Based on Robm's answer I have created a Docker image and a Bash script called portcat
.
Using portcat, you can easily map multiple ports to an existing Docker container. An example using the (optional) Bash script:
curl -sL https://raw.githubusercontent.com/archan937/portcat/master/script/install | sudo bash
portcat my-awesome-container 3456 4444:8080
And there you go! Portcat is mapping:
3456
to my-awesome-container:3456
4444
to my-awesome-container:8080
Please note that the Bash script is optional, the following commands:
ipAddress=$(docker inspect my-awesome-container | grep IPAddress | grep -o '[0-9]\{1,3\}\(\.[0-9]\{1,3\}\)\{3\}' | head -n 1)
docker run -p 3456:3456 -p 4444:4444 --name=alpine-portcat -it pmelegend/portcat:latest $ipAddress 3456 4444:8080
I hope portcat
will come in handy for you guys. Cheers!
I was having this problem, when I was calling a soap method to obtain my data, and then return a json string, when I tried to do json_decode I just keep getting null.
Since I was using nusoap to do the soap call I tried to just return json string and now I could do a json_decode, since I really neaded to get my data with a SOAP call, what I did was add ob_start() before include nusoap, id did my call genereate json string, and then before returning my json string I did ob_end_clean(), and GOT MY PROBLEM FIXED :)
EXAMPLE
//HRT - SIGNED
//20130116
//verifica se um num assoc deco é valido
ob_start();
require('/nusoap.php');
$aResponse['SimpleIsMemberResult']['IsMember'] = FALSE;
if(!empty($iNumAssociadoTmp))
{
try
{
$client = new soapclientNusoap(PartnerService.svc?wsdl',
array(
// OPTS
'trace' => 0,
'exceptions' => false,
'cache_wsdl' => WSDL_CACHE_NONE
)
);
//MENSAGEM A ENVIAR
$sMensagem1 = '
<SimpleIsMember>
<request>
<CheckDigit>'.$iCheckDigitAssociado.'</CheckDigit>
<Country>Portugal</Country>
<MemberNumber">'.$iNumAssociadoDeco.'</MemberNumber>
</request>
</SimpleIsMember>';
$aResponse = $client->call('SimpleIsMember',$sMensagem1);
$aData = array('dados'=>$aResponse->xpto, 'success'=>$aResponse->example);
}
}
ob_end_clean();
return json_encode($aData);
Building off of @Bohemian, I think the easiest approach would be to just use a regex literal, e.g.:
if (name.search(/[\[\]?*+|{}\\()@.\n\r]/) != -1) {
// ... stuff ...
}
Regex literals are nice because you don't have to escape the escape character, and some IDE's will highlight invalid regex (very helpful for me as I constantly screw them up).
A probably convenient way to enter multi-line strings is by using macro's. This only works if quotes and parentheses are balanced and it does not contain 'top level' comma's:
#define MULTI_LINE_STRING(a) #a
const char *text = MULTI_LINE_STRING(
Using this trick(,) you don't need to use quotes.
Though newlines and multiple white spaces
will be replaced by a single whitespace.
);
printf("[[%s]]\n",text);
Compiled with gcc 4.6 or g++ 4.6, this produces: [[Using this trick(,) you don't need to use quotes. Though newlines and multiple white spaces will be replaced by a single whitespace.]]
Note that the ,
cannot be in the string, unless it is contained within parenthesis or quotes. Single quotes is possible, but creates compiler warnings.
Edit: As mentioned in the comments, #define MULTI_LINE_STRING(...) #__VA_ARGS__
allows the use of ,
.
I'd like to emphasize that order of arguments is important.
For me java -agentlib:jdwp=transport=dt_socket,server=y,suspend=n,address=8000 -jar app.jar
command opens debugger port,
but java -jar app.jar -agentlib:jdwp=transport=dt_socket,server=y,suspend=n,address=8000
command doesn't.
To elaborate on @Bakuriu's answer above, I've found that this enables me to catch a runtime warning in a similar fashion to how I would catch an error warning, printing out the warning nicely:
import warnings
with warnings.catch_warnings():
warnings.filterwarnings('error')
try:
answer = 1 / 0
except Warning as e:
print('error found:', e)
You will probably be able to play around with placing of the warnings.catch_warnings() placement depending on how big of an umbrella you want to cast with catching errors this way.
Math.floor(Math.random()*limit)+1
This is how you would drop the constraint
ALTER TABLE <schema_name, sysname, dbo>.<table_name, sysname, table_name>
DROP CONSTRAINT <default_constraint_name, sysname, default_constraint_name>
GO
With a script
-- t-sql scriptlet to drop all constraints on a table
DECLARE @database nvarchar(50)
DECLARE @table nvarchar(50)
set @database = 'dotnetnuke'
set @table = 'tabs'
DECLARE @sql nvarchar(255)
WHILE EXISTS(select * from INFORMATION_SCHEMA.TABLE_CONSTRAINTS where constraint_catalog = @database and table_name = @table)
BEGIN
select @sql = 'ALTER TABLE ' + @table + ' DROP CONSTRAINT ' + CONSTRAINT_NAME
from INFORMATION_SCHEMA.TABLE_CONSTRAINTS
where constraint_catalog = @database and
table_name = @table
exec sp_executesql @sql
END
Credits go to Jon Galloway http://weblogs.asp.net/jgalloway/archive/2006/04/12/442616.aspx
You can also use
model.People = model.People.OrderBy(x => x.Name).ToList();
To complement Jon Lin's answer, here is a no-trailing-slash technique that also works if the website is located in a directory (like example.org/blog/):
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_URI} (.+)/$
RewriteRule ^ %1 [R=301,L]
For the sake of completeness, here is an alternative emphasizing that REQUEST_URI
starts with a slash (at least in .htaccess
files):
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_URI} /(.*)/$
RewriteRule ^ /%1 [R=301,L] <-- added slash here too, don't forget it
Just don't use %{REQUEST_URI} (.*)/$
. Because in the root directory REQUEST_URI
equals /
, the leading slash, and it would be misinterpreted as a trailing slash.
If you are interested in more reading:
(update: this technique is now implemented in Laravel 5.5)
I came across same old issue and found below code more understandable which is in a way per above solutions.
std::set<int*>::iterator beginIt = listOfInts.begin();
while(beginIt != listOfInts.end())
{
// Use your member
std::cout<<(*beginIt)<<std::endl;
// delete the object
delete (*beginIt);
// erase item from vector
listOfInts.erase(beginIt );
// re-calculate the begin
beginIt = listOfInts.begin();
}
If by "empty" you mean undefined
, it is the way ng-expressions are interpreted. Then, you could use :
<a ng-if="!item.photo" href="#/details/{{item.id}}"><img src="/img.jpg" class="img-responsive"></a>
with UnionTable as
(
SELECT a.id, a.time FROM dbo.a
UNION
SELECT b.id, b.time FROM dbo.b
) SELECT id FROM UnionTable GROUP BY id
A simple "window" with some text and a button is just a MessageBox. You can create them with a single function call; you don't need any library whatsoever.
Using Javascript
<div id="mydiv" style="width:200px;background:white" onmouseover="this.style.background='gray';" onmouseout="this.style.background='white';">
Jack and Jill went up the hill
To fetch a pail of water.
Jack fell down and broke his crown,
And Jill came tumbling after.
</div>
First, create a function (using CTE, common table expression does away with the need for a temp table)
create function dbo.SplitString
(
@str nvarchar(4000),
@separator char(1)
)
returns table
AS
return (
with tokens(p, a, b) AS (
select
1,
1,
charindex(@separator, @str)
union all
select
p + 1,
b + 1,
charindex(@separator, @str, b + 1)
from tokens
where b > 0
)
select
p-1 zeroBasedOccurance,
substring(
@str,
a,
case when b > 0 then b-a ELSE 4000 end)
AS s
from tokens
)
GO
Then, use it as any table (or modify it to fit within your existing stored proc) like this.
select s
from dbo.SplitString('Hello John Smith', ' ')
where zeroBasedOccurance=1
Update
Previous version would fail for input string longer than 4000 chars. This version takes care of the limitation:
create function dbo.SplitString
(
@str nvarchar(max),
@separator char(1)
)
returns table
AS
return (
with tokens(p, a, b) AS (
select
cast(1 as bigint),
cast(1 as bigint),
charindex(@separator, @str)
union all
select
p + 1,
b + 1,
charindex(@separator, @str, b + 1)
from tokens
where b > 0
)
select
p-1 ItemIndex,
substring(
@str,
a,
case when b > 0 then b-a ELSE LEN(@str) end)
AS s
from tokens
);
GO
Usage remains the same.
I you only want to see what was printed in the console you could simple add the "printed" part somewhere in your HTML so it will appear in on the webpage. You could do it for yourself, but there is a javascript file that does this for you. You can read about it here:
http://www.hnldesign.nl/work/code/mobileconsole-javascript-console-for-mobile-devices/
The code is available from Github; you can download it and paste it into a javascipt file and add it in to your HTML
Use header
to modify the HTTP header:
header('Content-Type: text/html; charset=utf-8');
Note to call this function before any output has been sent to the client. Otherwise the header has been sent too and you obviously can’t change it any more. You can check that with headers_sent
. See the manual page of header
for more information.
No need to add a containing div.
The default for the css "align-items" property is "stretch" which is what is causing your images to be stretched to its full original height. Setting the css "align-items" property to "flex-start" fixes your issue.
.slider {
display: flex;
align-items: flex-start; /* ADD THIS! */
}
To avoid any ambiguity, use the utilities methods from SwingUtilities :
SwingUtilities.isLeftMouseButton(MouseEvent anEvent)
SwingUtilities.isRightMouseButton(MouseEvent anEvent)
SwingUtilities.isMiddleMouseButton(MouseEvent anEvent)
Solution
You can use the troubleshooting tips below.
Troubleshooting Tip #1
Exit Eclipse
Open a web browser and visit, http://localhost:8080
If you see a "Tomcat" web page then that means Tomcat is running as a Windows service. To stop Tomcat running as a Windows services, open your Windows Control Panel. Find the service "Apache Tomcat" and stop it.
If you don't see a "Tomcat" web page, then stop the appropriate process displayed.
-- Troubleshooting Tip #2 - GUI Option
Steps to free port which is already used to run Tomcat server in Eclipse
On MS Windows, select Start > All Programs > Accessories > System Tools >Resource Monitor
Expand the Network Tab
Move to the section for Listening Ports
Look in the Port column and scroll to find entry for port 8080
Select the given process and delete/kill the process
Return back to Eclipse and start the Tomcat Server, it should start up now.
Troubleshooting Tip #3 - Command-Line Option
Steps to free port which is already used to run Tomcat server in Eclipse
For example , suppose 8080 port is used , we need to make free 8080 to run tomcat
Step 1: (open the CMD command)
C:\Users\username>netstat -o -n -a | findstr 0.0:8080
TCP 0.0.0.0:3000 0.0.0.0:0 LISTENING 3116
Now , we can see that LISTENING port is 3116 for 8080 ,
We need to kill 3116 now
Step 2:
C:\Users\username>taskkill /F /PID 3116
Step 3: Return back to Eclipse and start the Tomcat Server, it should start up now.
====
Mac/Linux SOLUTION
Step 0: Exit Eclipse
Step 1: Open a terminal window
Step 2: Enter the following command to find the process id
lsof -i :8080 This will give output of the application that is running on port 8080
Step 3: Enter the following command to kill the process
kill $(lsof -t -i :8080)
Step 4: Return back to Eclipse and start the Tomcat Server, it should start up now.
This was a strange problem since my hosts IIS shouldn't complain that it requires integrated pipeline mode when it already is in that mode as I stated in my question as:
I have searched a lot and unable to find anything except for directing the reader to change the pipeline from classic mode to integrated mode that which I already did with no luck..
Using Levi's directions, I put and <%: System.Web.Hosting.HttpRuntime.UsingIntegratedPipeline %>
* on an empty aspx page and told my host what going on and asked them to fix the problem and confirm the problem using the page I uploaded... I checked very often if something has changed at the state of the page and I can see that they struggled 3-4 hours to solve it... <%: System.Web.Hosting.HttpRuntime.IISVersion %>
When I asked what they have done to solve the problem, their answer was kind of 'classified', since they said:
Our team made the required changes on the server
The problem was all with my host.
* Update: As Ben stated in the comments
<%: System.Web.Hosting.HttpRuntime.UsingIntegratedPipeline %>
and<%: System.Web.Hosting.HttpRuntime.IISVersion %>
are no longer valid and they are now:
The ?type=daily
argument (ending up in the $_GET
array) is only valid for web-accessed pages.
You'll need to call it like php myfile.php daily
and retrieve that argument from the $argv
array (which would be $argv[1]
, since $argv[0]
would be myfile.php
).
If the page is used as a webpage as well, there are two options you could consider. Either accessing it with a shell script and Wget, and call that from cron:
#!/bin/sh
wget http://location.to/myfile.php?type=daily
Or check in the PHP file whether it's called from the command line or not:
if (defined('STDIN')) {
$type = $argv[1];
} else {
$type = $_GET['type'];
}
(Note: You'll probably need/want to check if $argv
actually contains enough variables and such)
You may use YQL however yahoo.finance.* tables are not the core yahoo tables. It is an open data table which uses the 'csv api' and converts it to json or xml format. It is more convenient to use but it's not always reliable. I could not use it just a while ago because it the table hits its storage limit or something...
You may use this php library to get historical data / quotes using YQL https://github.com/aygee/php-yql-finance
How about using XQuery with a one liner:
DECLARE @MalformedXML xml, @StrippedText varchar(max)
SET @MalformedXML = @xml.query('for $x in //. return ($x)//text()')
SET @StrippedText = CAST(@MalformedXML as varchar(max))
This loops through all elements and returns the text() only.
To avoid text between elements concatenating without spaces, use:
DECLARE @MalformedXML xml, @StrippedText varchar(max)
SET @MalformedXML = @xml.query('for $x in //. return concat((($x)//text())[1]," ")')
SET @StrippedText = CAST(@MalformedXML as varchar(max))
And to respond to "How do you use this for a column:
SELECT CAST(html_column.query('for $x in //. return concat((($x)//text()) as varchar(max))
FROM table
For the above code, ensure your html_column
is of data type xml
, if not, you need to save a casted version of the html as xml
. I would do this as a separate exercise when you are loading HTML data, as SQL will throw an error if it finds malformed xml, e.g. mismatched start/end tags, invalid characters.
These are excellent for when you want to build seachh phrases, strip HTML, etc.
Just note that this returns type xml, so CAST or COVERT to text where appropriate. The xml version of this data type is useless, as it is not a well formed XML.
I just use the "New Class" dialog in Eclipse and set the base class as Activity. I'm not aware of any other way to do this. What other method would you expect to be available?
If you happen to need this in Android and want to make it work with anything older than FroYo, you can also use EncodingUtils.getAsciiBytes():
byte[] bytes = EncodingUtils.getAsciiBytes("ASCII Text");
At the moment there is no command in MongoDB that would do this. Please note the JIRA ticket with related feature request.
You could do something like:
db.<collection_name>.find().forEach(function(d){ db.getSiblingDB('<new_database>')['<collection_name>'].insert(d); });
Please note that with this, the two databases would need to share the same mongod for this to work.
Besides this, you can do a mongodump of a collection from one database and then mongorestore the collection to the other database.
IF you want to derive usg Boolean true False need to add "[]" around value
<form [formGroup]="form">
<input type="radio" [value]=true formControlName="gender" >Male
<input type="radio" [value]=false formControlName="gender">Female
</form>
std::move
?A: std::move()
is a function from the C++ Standard Library for casting to a rvalue reference.
Simplisticly std::move(t)
is equivalent to:
static_cast<T&&>(t);
An rvalue is a temporary that does not persist beyond the expression that defines it, such as an intermediate function result which is never stored in a variable.
int a = 3; // 3 is a rvalue, does not exist after expression is evaluated
int b = a; // a is a lvalue, keeps existing after expression is evaluated
An implementation for std::move() is given in N2027: "A Brief Introduction to Rvalue References" as follows:
template <class T>
typename remove_reference<T>::type&&
std::move(T&& a)
{
return a;
}
As you can see, std::move
returns T&&
no matter if called with a value (T
), reference type (T&
), or rvalue reference (T&&
).
A: As a cast, it does not do anything during runtime. It is only relevant at compile time to tell the compiler that you would like to continue considering the reference as an rvalue.
foo(3 * 5); // obviously, you are calling foo with a temporary (rvalue)
int a = 3 * 5;
foo(a); // how to tell the compiler to treat `a` as an rvalue?
foo(std::move(a)); // will call `foo(int&& a)` rather than `foo(int a)` or `foo(int& a)`
What it does not do:
A: You should use std::move
if you want to call functions that support move semantics with an argument which is not an rvalue (temporary expression).
This begs the following follow-up questions for me:
What is move semantics? Move semantics in contrast to copy semantics is a programming technique in which the members of an object are initialized by 'taking over' instead of copying another object's members. Such 'take over' makes only sense with pointers and resource handles, which can be cheaply transferred by copying the pointer or integer handle rather than the underlying data.
What kind of classes and objects support move semantics? It is up to you as a developer to implement move semantics in your own classes if these would benefit from transferring their members instead of copying them. Once you implement move semantics, you will directly benefit from work from many library programmers who have added support for handling classes with move semantics efficiently.
Why can't the compiler figure it out on its own? The compiler cannot just call another overload of a function unless you say so. You must help the compiler choose whether the regular or move version of the function should be called.
In which situations would I want to tell the compiler that it should treat a variable as an rvalue? This will most likely happen in template or library functions, where you know that an intermediate result could be salvaged.
Addressing cases that some of the other answers don't handle well:
Many of the solutions on this page involve polling Console.KeyAvailable
or blocking on Console.ReadKey
. While it's true that the .NET Console
is not very cooperative here, you can use Task.Run
to move towards a more modern Async
mode of listening.
The main issue to be aware of is that, by default, your console thread isn't set up for Async
operation--meaning that, when you fall out of the bottom of your main
function, instead of awaiting Async
completions, your AppDoman and process will end. A proper way to address this would be to use Stephen Cleary's AsyncContext to establish full Async
support in your single-threaded console program. But for simpler cases, like waiting for a keypress, installing a full trampoline may be overkill.
The example below would be for a console program used in some kind of iterative batch file. In this case, when the program is done with its work, normally it should exit without requiring a keypress, and then we allow an optional key press to prevent the app from exiting. We can pause the cycle to examine things, possibly resuming, or use the pause as a known 'control point' at which to cleanly break out of the batch file.
static void Main(String[] args)
{
Console.WriteLine("Press any key to prevent exit...");
var tHold = Task.Run(() => Console.ReadKey(true));
// ... do your console app activity ...
if (tHold.IsCompleted)
{
#if false // For the 'hold' state, you can simply halt forever...
Console.WriteLine("Holding.");
Thread.Sleep(Timeout.Infinite);
#else // ...or allow continuing to exit
while (Console.KeyAvailable)
Console.ReadKey(true); // flush/consume any extras
Console.WriteLine("Holding. Press 'Esc' to exit.");
while (Console.ReadKey(true).Key != ConsoleKey.Escape)
;
#endif
}
}
The closest equivalent to Java's toString
is to implement __str__
for your class. Put this in your class definition:
def __str__(self):
return "foo"
You may also want to implement __repr__
to aid in debugging.
See here for more information:
This..
(
(meta_key = 'lat' AND meta_value >= '60.23457047672217')
OR
(meta_key = 'lat' AND meta_value <= '60.23457047672217')
)
is the same as
(
(meta_key = 'lat')
)
Adding it all together (the same applies to the long
filter) you have this impossible WHERE clause which will give no rows because meta_key
cannot be 2 values in one row
WHERE
(meta_key = 'lat' AND meta_key = 'long' )
You need to review your operators to make sure you get the correct logic
The best solution for this is to create a simple parent pom file project (with packaging 'pom') generically for all projects from your organization.
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>your.company</groupId>
<artifactId>company-parent</artifactId>
<version>1.0.0-SNAPSHOT</version>
<packaging>pom</packaging>
<distributionManagement>
<repository>
<id>nexus-site</id>
<url>http://central_nexus/server</url>
</repository>
</distributionManagement>
</project>
This can be built, released, and deployed to your local nexus so everyone has access to its artifact.
Now for all projects which you wish to use it, simply include this section:
<parent>
<groupId>your.company</groupId>
<artifactId>company-parent</artifactId>
<version>1.0.0</version>
</parent>
This solution will allow you to easily add other common things to all your company's projects. For instance if you wanted to standardize your JUnit usage to a specific version, this would be the perfect place for that.
If you have projects that use multi-module structures that have their own parent, Maven also supports chaining inheritance so it is perfectly acceptable to make your project's parent pom file refer to your company's parent pom and have the project's child modules not even aware of your company's parent.
I see from your example project structure that you are attempting to put your parent project at the same level as your aggregator pom. If your project needs its own parent, the best approach I have found is to include the parent at the same level as the rest of the modules and have your aggregator pom.xml file at the root of where all your modules' directories exist.
- pom.xml (aggregator)
- project-parent
- project-module1
- project-module2
What you do with this structure is include your parent module in the aggregator and build everything with a mvn install
from the root directory.
We use this exact solution at my organization and it has stood the test of time and worked quite well for us.
Here is the complete procedure for IDEA IntelliJ 2019.3:
File > Project Structure
Under Project Settings > Modules
Under 'Sources' tab, right-click on 'src' folder and select 'Sources'.
Apply changes.
Look at the ToLookup
and/or ToDictionary
extension methods.
Just as Daniel said "Git and TFVC are the two source control options in TFS
". Fortunately both are supported for now in VS Code.
You need to install the Azure Repos Extension for Visual Studio Code. The process of installing is pretty straight forward.
Add the following lines to your user settings
If you have VS 2015 installed on your machine, your path to Team Foundation tool (tf.exe) may look like this:
{ "tfvc.location": "C:\\Program Files (x86)\\Microsoft Visual Studio 14.0\\Common7\\IDE\\tf.exe", "tfvc.restrictWorkspace": true }
Or for VS 2017:
{ "tfvc.location": "C:\\Program Files (x86)\\Microsoft Visual Studio\\2017\\Enterprise\\Common7\\IDE\\CommonExtensions\\Microsoft\\TeamFoundation\\Team Explorer\\tf.exe", "tfvc.restrictWorkspace": true }
Open a local folder (repository), From View -> Command Pallette ..., type team signin
Provide user name --> Enter --> Provide password to connect to TFS.
Please refer to below links for more details:
Note that Server Workspaces are not supported:
"TFVC support is limited to Local workspaces":
C99 added a builtin _Bool
data type (see Wikipedia for details), and if you #include <stdbool.h>
, it provides bool
as a macro to _Bool
.
You asked about the Linux kernel in particular. It assumes the presence of _Bool
and provides a bool
typedef itself in include/linux/types.h.
Remove last comma. Working example
function truncateText() {_x000D_
var str= document.getElementById('input').value;_x000D_
str = str.replace(/,\s*$/, "");_x000D_
console.log(str);_x000D_
}
_x000D_
<input id="input" value="address line one,"/>_x000D_
<button onclick="truncateText()">Truncate</button>
_x000D_
If both "document.ready" variants are used they will both fire, in the order of appearance
$(function(){
alert('shorthand document.ready');
});
//try changing places
$(document).ready(function(){
alert('document.ready');
});
Css render is browser specific and I don't know any fine tuning on it, you should work with images as recommended by Ham. Reference: http://www.w3.org/TR/CSS2/box.html#border-style-properties
You are looking for the insert
function, found in the table
section of the main library.
foo = {}
table.insert(foo, "bar")
table.insert(foo, "baz")
The delete button is right there where the help page says it is.
To shut down a project using the Cloud Platform Console:
Open the Settings page in the Google Cloud Platform Console.
Click Select a project.
- Select a project you wish to delete, and click Open.
- Click Shut down.
- Enter the Project ID and click Shut down.
Please note that there is a 7-day grace period before the project is actually purged from the system. Which means you won't be able to immediately create another project with the same name.
If you cannot utilize the ActiveDirectory
Module or the Get-ADGroupMember
cmdlet, you can do it with the LDAP "in chain"-matching rule:
$GroupDN = "CN=MyGroup,OU=Groups,DC=mydomain,DC=tld"
$LDAPFilter = "(&(objectClass=user)(objectCategory=Person)(memberOf:1.2.840.113556.1.4.1941:=$GroupDN))"
# Ideally using an instance of adsisearcher here:
Get-ADObject -LDAPFilter $LDAPFilter
See MSDN for additional LDAP matching rules implemented in Active Directory
To switch to a popup window, you need to use getWindowHandles()
and iterate through them.
In your code you are using getWindowHandle()
which will give you the parent window itself.
String parentWindowHandler = driver.getWindowHandle(); // Store your parent window
String subWindowHandler = null;
Set<String> handles = driver.getWindowHandles(); // get all window handles
Iterator<String> iterator = handles.iterator();
while (iterator.hasNext()){
subWindowHandler = iterator.next();
}
driver.switchTo().window(subWindowHandler); // switch to popup window
// Now you are in the popup window, perform necessary actions here
driver.switchTo().window(parentWindowHandler); // switch back to parent window
You can also used below code
<html>
<head>
<style>
.labelClass{
float: left;
width: 113px;
}
</style>
</head>
<body>
<form action="yourclassName.jsp">
<span class="labelClass">First name: </span><input type="text" name="fname"><br>
<span class="labelClass">Last name: </span><input type="text" name="lname"><br>
<input type="submit" value="Submit">
</form>
</body>
</html>
In my case, I also needed to reset the cached config files:
php artisan key:generate
php artisan config:cache
Adding to previous answers, it is valid Ruby to use ::
to access instance methods. All the following are valid:
MyClass::new::instance_method
MyClass::new.instance_method
MyClass.new::instance_method
MyClass.new.instance_method
As per best practices I believe only the last one is recommended.
Try:
$number = 1234545454;
echo $english_format_number = number_format($number, 2);
The output will be:
1,234,545,454.00
For the same reason you can also use inheritIO()
to map Java console with external app console like:
ProcessBuilder pb = new ProcessBuilder(appPath, arguments);
pb.directory(new File(appFile.getParent()));
pb.inheritIO();
Process process = pb.start();
int success = process.waitFor();
Solving the problem by grouping the data - DrTech's answer used facets in managing this but, will be deprecated according to Elasticsearch 1.0 reference.
Warning
Facets are deprecated and will be removed in a future release. You are encouraged to
migrate to aggregations instead.
Facets are replaced by aggregates - Introduced in an accessible manner in the Elasticsearch Guide - which loads an example into sense..
The solution is the same except aggregations require aggs
instead of facets
and with a count of 0 which sets limit to max integer - the example code requires the Marvel Plugin
# Basic aggregation
GET /houses/occupier/_search?search_type=count
{
"aggs" : {
"indexed_occupier_names" : { <= Whatever you want this to be
"terms" : {
"field" : "first_name", <= Name of the field you want to aggregate
"size" : 0
}
}
}
}
Here is the Sense code to test it out - example of a houses index, with an occupier type, and a field first_name:
DELETE /houses
# Index example docs
POST /houses/occupier/_bulk
{ "index": {}}
{ "first_name": "john" }
{ "index": {}}
{ "first_name": "john" }
{ "index": {}}
{ "first_name": "mark" }
# Basic aggregation
GET /houses/occupier/_search?search_type=count
{
"aggs" : {
"indexed_occupier_names" : {
"terms" : {
"field" : "first_name",
"size" : 0
}
}
}
}
Response showing the relevant aggregation code. With two keys in the index, John and Mark.
....
"aggregations": {
"indexed_occupier_names": {
"buckets": [
{
"key": "john",
"doc_count": 2 <= 2 documents matching
},
{
"key": "mark",
"doc_count": 1 <= 1 document matching
}
]
}
}
....
I had a similar problem, where I couldn't even install local::lib
I created an installer that installed the module somewhere relative to the .pl files
The install goes like:
perl Makefile.PL PREFIX=./modulos
make
make install
Then, in the .pl file that requires the module, which is in ./
use lib qw(./modulos/share/perl/5.8.8/); # You may need to change this path
use module::name;
The rest of the files (makefile.pl, module.pm, etc) require no changes.
You can call the .pl file with just
perl file.pl
You can try the FileReader API. Do something like this:
<!DOCTYPE html>
<html>
<head>
<script>
function handleFileSelect()
{
if (!window.File || !window.FileReader || !window.FileList || !window.Blob) {
alert('The File APIs are not fully supported in this browser.');
return;
}
var input = document.getElementById('fileinput');
if (!input) {
alert("Um, couldn't find the fileinput element.");
}
else if (!input.files) {
alert("This browser doesn't seem to support the `files` property of file inputs.");
}
else if (!input.files[0]) {
alert("Please select a file before clicking 'Load'");
}
else {
var file = input.files[0];
var fr = new FileReader();
fr.onload = receivedText;
//fr.readAsText(file);
//fr.readAsBinaryString(file); //as bit work with base64 for example upload to server
fr.readAsDataURL(file);
}
}
function receivedText() {
document.getElementById('editor').appendChild(document.createTextNode(fr.result));
}
</script>
</head>
<body>
<input type="file" id="fileinput"/>
<input type='button' id='btnLoad' value='Load' onclick='handleFileSelect();' />
<div id="editor"></div>
</body>
</html>
_x000D_
I had the same problem. I'm very new to iphone development and it was my first time trying to load my program onto my iphone. The message is correct, you need to create a certificate in the keychain. The best walkthrough is here:
http://developer.apple.com/ios/manage/overview/index.action
You of course need to have a developer account (need to have paid the $100 yearly fee).
I hope this helps.
Tim's answer is correct, however I wanted to add another suggestion, because in my case there was a simpler solution altogether.
I was looking to set the UIButton
image insets because I didn't realize that I could set the content mode on the button's UIImageView
, which would have prevented the need to use UIEdgeInsets and hard-coded values altogether. Simply access the underlying imageview on the button and set the content mode:
myButton.imageView.contentMode = UIViewContentModeScaleAspectFit;
See UIButton doesn't listen to content mode setting?
Swift 3
myButton.imageView?.contentMode = .scaleAspectFit
I got the same problem in my console application development and as a quick workaround,
go to project properties
then,
click on signing
tab and uncheck "Sign the ClickOnce Manifest".
Image Description:
FYI You can also see this less one minute video solution. The above picture is taken form the video.
Here is the fastest solution in Typescript, which works also on arrays with multiple levels of nesting:
export function flatten<T>(input: Array<any>, output: Array<T> = []): Array<T> {
for (const value of input) {
Array.isArray(value) ? flatten(value, output) : output.push(value);
}
return output;
}
and than:
const result = flatten<MyModel>(await Promise.all(promises));
A program I wrote, farmComm, may solve this. I released it as open-source and Public Domain.
If it doesn't meet your criteria, you may be able to easily alter it to do so.
farmComm:
The source scripts are available here:
If you want to use the IDE to accept the license, I also found it easy to open up Android Studio and create a new basic project to trigger the license agreements. Once I created a project, the following licensing dialog was presented that I needed to agree to:
I documented fully the information in the following post: Accepting the Android SDK License via Android Studio
Two quick possibilities:
if(!('foo' in myObj)) { ... }
or
if(myObj['foo'] === undefined) { ... }
Overloading means having methods with same name but different signature Overriding means rewriting the virtual method of the base class.............
This would do
string x = TextBoxD1.Text;
int xi = Convert.ToInt32(x);
Or you can use
int xi = Int32.Parse(x);
On what basis should the merging take place? Your question is rather vague. Also, I assume a, b, ..., f are supposed to be strings, that is, 'a', 'b', ..., 'f'.
>>> x = ['a', 'b', 'c', 'd', 'e', 'f', 'g']
>>> x[3:6] = [''.join(x[3:6])]
>>> x
['a', 'b', 'c', 'def', 'g']
Check out the documentation on sequence types, specifically on mutable sequence types. And perhaps also on string methods.
You should not extend the JFrame
class unnecessarily (only if you are adding extra functionality to the JFrame
class)
JFrame:
JFrame
extends Component
and Container
.
It is a top level container used to represent the minimum requirements for a window. This includes Border
s, resizability (is the JFrame
resizeable?), title bar, controls (minimize/maximize allowed?), and event handlers for various Event
s like windowClose
, windowOpened
etc.
JPanel:
JPanel
extends Component
, Container
and JComponent
It is a generic class used to group other Component
s together.
It is useful when working with LayoutManager
s e.g. GridLayout
f.i adding components to different JPanel
s which will then be added to the JFrame
to create the gui. It will be more manageable in terms of Layout
and re-usability.
It is also useful for when painting/drawing in Swing, you would override paintComponent(..)
and of course have the full joys of double buffering.
A Swing GUI cannot exist without a top level container like (JWindow
, Window
, JFrame
Frame
or Applet
), while it may exist without JPanel
s.
After rigorous testing, I found out that the source of my problem is Hash::make('password'). Apparently this kept generating a different hash each time. SO I replaced this with my own hashing function (wrote previously in codeigniter) and viola! things worked well.
Thanks again for helping out :) Really appreciate it!
Just catch the submit event and prevent that, then do ajax
$(document).ready(function () {
$('#myform').on('submit', function(e) {
e.preventDefault();
$.ajax({
url : $(this).attr('action') || window.location.pathname,
type: "GET",
data: $(this).serialize(),
success: function (data) {
$("#form_output").html(data);
},
error: function (jXHR, textStatus, errorThrown) {
alert(errorThrown);
}
});
});
});
For SQL Server:
GROUP BY datepart(year,datefield),
datepart(month,datefield),
datepart(day,datefield)
or faster (from Q8-Coder):
GROUP BY dateadd(DAY,0, datediff(day,0, created))
For MySQL:
GROUP BY year(datefield), month(datefield), day(datefield)
or better (from Jon Bright):
GROUP BY date(datefield)
For Oracle:
GROUP BY to_char(datefield, 'yyyy-mm-dd')
or faster (from IronGoofy):
GROUP BY trunc(created);
For Informix (by Jonathan Leffler):
GROUP BY date_column
GROUP BY EXTEND(datetime_column, YEAR TO DAY)
It's easy if you are somewhat constrained.
If you have one thread, you just use uniqueID++; Be sure to store the current uniqueID when you exit.
If you have multiple threads, a common synchronized generateUniqueID method works (Implemented the same as above).
The problem is when you have many CPUs--either in a cluster or some distributed setup like a peer-to-peer game.
In that case, you can generally combine two parts to form a single number. For instance, each process that generates a unique ID can have it's own 2-byte ID number assigned and then combine it with a uniqueID++. Something like:
return (myID << 16) & uniqueID++
It can be tricky distributing the "myID" portion, but there are some ways. You can just grab one out of a centralized database, request a unique ID from a centralized server, ...
If you had a Long instead of an Int, one of the common tricks is to take the device id (UUID) of ETH0, that's guaranteed to be unique to a server--then just add on a serial number.
Are you using the .NET framework? If so, let me introduce you to the DateTimeOffset type, added with .NET 3.5.
This structure holds both a DateTime
and an Offset (TimeSpan
), which specifies the difference between the DateTimeOffset
instance's date and time and Coordinated Universal Time (UTC).
The DateTimeOffset.Now
static method will return a DateTimeOffset
instance consisting of the current (local) time, and the local offset
(as defined in the operating system's regional info).
The DateTimeOffset.UtcNow
static method will return a
DateTimeOffset
instance consisting of the current time in UTC (as
if you were in Greenwich).
Other helpful types are the TimeZone and TimeZoneInfo classes.
If you use NetBeans IDE right click form then
Properties ->Code -> check out Generate Center
The three constants have similar functions nowadays, but different historical origins, and very occasionally you may be required to use one or the other.
You need to think back to the days of old manual typewriters to get the origins of this. There are two distinct actions needed to start a new line of text:
In computers, these two actions are represented by two different characters - carriage return is CR
, ASCII character 13, vbCr
; line feed is LF
, ASCII character 10, vbLf
. In the old days of teletypes and line printers, the printer needed to be sent these two characters -- traditionally in the sequence CRLF
-- to start a new line, and so the CRLF
combination -- vbCrLf
-- became a traditional line ending sequence, in some computing environments.
The problem was, of course, that it made just as much sense to only use one character to mark the line ending, and have the terminal or printer perform both the carriage return and line feed actions automatically. And so before you knew it, we had 3 different valid line endings: LF
alone (used in Unix and Macintoshes), CR
alone (apparently used in older Mac OSes) and the CRLF
combination (used in DOS, and hence in Windows). This in turn led to the complications of DOS / Windows programs having the option of opening files in text mode
, where any CRLF
pair read from the file was converted to a single CR
(and vice versa when writing).
So - to cut a (much too) long story short - there are historical reasons for the existence of the three separate line separators, which are now often irrelevant: and perhaps the best course of action in .NET is to use Environment.NewLine
which means someone else has decided for you which to use, and future portability issues should be reduced.
Better approch is use alt+right and alt+left keys to navigate like Jetbrains IDE Webstorm does
Here is my config. it also include create new file and folder
{
"key": "ctrl+n",
"command": "explorer.newFile"
},
{
"key": "ctrl+shift+n",
"command": "explorer.newFolder"
},
{
"key": "alt+left",
"command": "workbench.action.previousEditor"
},
{
"key": "alt+right",
"command": "workbench.action.nextEditor"
}
The easiest way is to use JarURLConnection class :
String className = getClass().getSimpleName() + ".class";
String classPath = getClass().getResource(className).toString();
if (!classPath.startsWith("jar")) {
return DEFAULT_PROPERTY_VALUE;
}
URL url = new URL(classPath);
JarURLConnection jarConnection = (JarURLConnection) url.openConnection();
Manifest manifest = jarConnection.getManifest();
Attributes attributes = manifest.getMainAttributes();
return attributes.getValue(PROPERTY_NAME);
Because in some cases ...class.getProtectionDomain().getCodeSource().getLocation();
gives path with vfs:/
, so this should be handled additionally.
With pyEnchant.checker SpellChecker:
from enchant.checker import SpellChecker
def is_in_english(quote):
d = SpellChecker("en_US")
d.set_text(quote)
errors = [err.word for err in d]
return False if ((len(errors) > 4) or len(quote.split()) < 3) else True
print(is_in_english('“??????????????????????Q/V2166384296???????????????????'))
print(is_in_english('“Two things are infinite: the universe and human stupidity; and I\'m not sure about the universe.”'))
> False
> True
Starting PHP5.5+ you have array_column() available to you, which makes all of the below obsolete.
$ids = array_map(function ($ar) {return $ar['id'];}, $users);
Solution by @phihag will work flawlessly in PHP starting from PHP 5.3.0, if you need support before that, you will need to copy that wp_list_pluck.
In Wordpress there is a function called wp_list_pluck If you're using Wordpress that solves your problem.
PHP < 5.3If you're not using Wordpress, since the code is open source you can copy paste the code in your project (and rename the function to something you prefer, like array_pick). View source here
use DATE
and CURDATE()
SELECT * FROM `table` WHERE DATE(`timestamp`) = CURDATE()
Warning! This query doesn't use an index efficiently. For the more efficient solution see the answer below
When you have a conflict during rebase you have three options:
You can run git rebase --abort
to completely undo the rebase. Git will return you to your branch's state as it was before git rebase was called.
You can run git rebase --skip
to completely skip the commit. That means
that none of the changes introduced by the problematic commit will be included. It is very rare that you would choose this option.
You can fix the conflict as iltempo said. When you're finished, you'll need to call git rebase --continue
. My mergetool is kdiff3 but there are many more which you can use to solve conflicts. You only need to set your merge tool in git's settings so it can be invoked when you call git mergetool
https://git-scm.com/docs/git-mergetool
If none of the above works for you, then go for a walk and try again :)
Using UIScrollView's setContentOffset:animated:
function to scroll to the bottom in Swift.
let bottomOffset : CGPoint = CGPointMake(0, scrollView.contentSize.height - scrollView.bounds.size.height + scrollView.contentInset.bottom)
scrollView.setContentOffset(bottomOffset, animated: true)
Yes this post is 8 years old, but incase someone comes on here also looking for an answer: you can now just use semicolons. However, you cannot use if/elif/else staments, for/while loops, and you can't define functions. The main use of this would be when using imported modules where you don't have to define any functions or use any if/elif/else/for/while statements/loops.
Here's an example that takes the artist of a song, the song name, and searches genius for the lyrics:
import bs4, requests; song = input('Input artist then song name\n'); print(bs4.BeautifulSoup(requests.get(f'https://genius.com/{song.replace(" ", "-")}-lyrics').text,'html.parser').select('.lyrics')[0].text.strip())
This will give a list of selected
List<ListItem> items = checkboxlist.Items.Cast<ListItem>().Where(n => n.Selected).ToList();
This will give a list of the selected boxes' values (change Value for Text if that is wanted):
var values = checkboxlist.Items.Cast<ListItem>().Where(n => n.Selected).Select(n => n.Value ).ToList()
Did you try
for line in open("masters", "r").readlines(): print line
?
readline()
only reads "a line", on the other hand
readlines()
reads whole lines and gives you a list of all lines.
The **
syntax tells Python to collect keyword arguments into a dictionary. The save2
is passing it down as a non-keyword argument (a dictionary object). The openX
is not seeing any keyword arguments so the **args
doesn't get used. It's instead getting a third non-keyword argument (the dictionary). To fix that change the definition of the openX
function.
def openX(filename, mode, kwargs):
pass
the following code worked fine for me. kindly check other setting in your web config
<system.webServer>
<defaultDocument>
<files>
<clear />
<add value="Login.aspx"/>
</files>
</defaultDocument>
</system.webServer>
Use the Apache Commons library BooleanUtils
class:
String[] values= new String[]{"y","Y","n","N","Yes","YES","yes","no","No","NO","true","false","True","False","TRUE","FALSE",null};
for(String booleanStr : values){
System.out.println("Str ="+ booleanStr +": boolean =" +BooleanUtils.toBoolean(booleanStr));
}
Result:
Str =N: boolean =false
Str =Yes: boolean =true
Str =YES: boolean =true
Str =yes: boolean =true
Str =no: boolean =false
Str =No: boolean =false
Str =NO: boolean =false
Str =true: boolean =true
Str =false: boolean =false
Str =True: boolean =true
Str =False: boolean =false
Str =TRUE: boolean =true
Str =FALSE: boolean =false
Str =null: boolean =false
Use the annotation @Deprecated
for your method, and you should also mention it in your javadocs.
maybe there are some unmerged paths in your git repository that you have to resolve before stashing.
You should also be aware of the fact, that with utf8_general_ci when using a varchar field as unique or primary index inserting 2 values like 'a' and 'á' would give a duplicate key error.
I had the same problem and solved it by using EnumMemberAttribute for enum member's attribute. If you are using enum type as data contract and its members attributed with DataMemberAttribute, same error occurs. You must use EnumMemberAttribute for members of enum
In PhoneGap 3.4.0 you can call:
cordova build android --release
If you have set up the 'ant.properties' file in 'platforms/android' directory like the following:
key.store=/Path/to/KeyStore/myapp-release-key.keystore
key.alias=myapp
Then you will be prompted for your keystore password and the output file (myapp-release.apk) ends up in the 'platforms/android/ant-build' directory already signed and aligned and ready to deploy.
If you're outside the request-response handling, you can still:
import os
import signal
sig = getattr(signal, "SIGKILL", signal.SIGTERM)
os.kill(os.getpid(), sig)
padde's solution is right, but risen up another problem i.e.
As said by Adam (the questioner) that it is showing empty popup. Here is the complete and working solution
<html>
<head>
<script type="text/javascript" charset="utf-8" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script type="text/javascript" src="http://fancyapps.com/fancybox/source/jquery.fancybox.pack.js?v=2.0.5"></script>
<link rel="stylesheet" type="text/css" href="http://fancyapps.com/fancybox/source/jquery.fancybox.css?v=2.0.5" media="screen" />
</head>
<body>
<a href="#divForm" id="btnForm">Load Form</a>
<div id="divForm" style="display:none">
<form action="tbd">
File: <input type="file" /><br /><br />
<input type="submit" />
</form>
</div>
<script type="text/javascript">
$(function() {
$("#btnForm").fancybox({
'onStart': function() { $("#divForm").css("display","block"); },
'onClosed': function() { $("#divForm").css("display","none"); }
});
});
</script>
</body>
</html>
You're probably just getting a stack overflow here. The array is too big to fit in your program's stack address space.
If you allocate the array on the heap you should be fine, assuming your machine has enough memory.
int* array = new int[1000000];
But remember that this will require you to delete[]
the array. A better solution would be to use std::vector<int>
and resize it to 1000000 elements.
There are 2 solutions for your problem:
mw.geometry('500x500')
OR
back.place(x = 0, y = 0, relwidth = 1, relheight = 1)
*The second option should be used in place of back.pack()
I'm going to try a simpler answer:
First, let's understand the flow of events when a page is served from our server:
So really, the core thing to remember here is that HTTP is stateless. Once a request left the server, the server can not touch it. So, that leaves our options to:
That's the core question you should be asking yourself is:
Websites are mainly page based, and the page load times needs to be as fast as possible (for example - Wikipedia). Web applications are more AJAX heavy and perform a lot of round trips to get the client fast information (for example - a stock dashboard).
Sending more requests from the client after the initial request is done is slow as it requires more HTTP requests which have significant overhead. Moreover, it requires asynchronousity as making an AJAX request requires a handler for when it's complete.
I would not recommend making another request unless your site is an application for getting that information from the server.
You want fast response times which have a huge impact on conversion and load times. Making Ajax requests is slow for the initial uptime in this case and unneeded.
You have two ways to tackle the issue
Setting a cookie is really not very difficult, you just assign it a value:
setcookie("MyCookie", $value); // Sets the cookie to the value, remember, do not
// Set it with HTTP only to true.
Then, you can read it with JavaScript using document.cookie
:
Here is a short hand rolled parser, but the answer I linked to right above this has better tested ones:
var cookies = document.cookie.split(";").
map(function(el){ return el.split("="); }).
reduce(function(prev,cur){ prev[cur[0]] = cur[1];return prev },{});
cookies["MyCookie"] // Value set with PHP.
Cookies are good for a little data. This is what tracking services often do.
Once we have more data, we can encode it with JSON inside a JavaScript variable instead:
<script>
var myServerData = <?=json_encode($value)?>; // Don't forget to sanitize
//server data
</script>
Assuming $value
is json_encode
able on the PHP side (it usually is). This technique is what Stack Overflow does with its chat for example (only using .NET instead of PHP).
If you're writing an application - suddenly the initial load time isn't always as important as the ongoing performance of the application, and it starts to pay off to load data and code separately.
My answer here explains how to load data using AJAX in JavaScript:
function callback(data){
// What do I do with the response?
}
var httpRequest = new XMLHttpRequest;
httpRequest.onreadystatechange = function(){
if (httpRequest.readyState === 4) { // Request is done
if (httpRequest.status === 200) { // successfully
callback(httpRequest.responseText); // We're calling our method
}
}
};
httpRequest.open('GET', "/echo/json");
httpRequest.send();
Or with jQuery:
$.get("/your/url").done(function(data){
// What do I do with the data?
});
Now, the server just needs to contain a /your/url
route/file that contains code that grabs the data and does something with it, in your case:
<$php
...
$val = myService->getValue(); // Makes an API and database call
echo json_encode($val); // Write it to the output
$>
This way, our JavaScript file asks for the data and shows it rather than asking for code or for layout. This is cleaner and starts to pay off as the application gets higher. It's also better separation of concerns and it allows testing the client side code without any server side technology involved which is another plus.
Postscript: You have to be very aware of XSS attack vectors when you inject anything from PHP to JavaScript. It's very hard to escape values properly and it's context sensitive. If you're unsure how to deal with XSS, or unaware of it - please read this OWASP article, this one and this question.
Pyexcel works great with both Python2 and Python3 without troubles.
Fast installation with pip:
pip install pyexcel
After that, only 3 lines of code and the job is done:
import pyexcel
data = [['Me', 'You'], ['293', '219'], ['54', '13']]
pyexcel.save_as(array = data, dest_file_name = 'csv_file_name.csv')
Use the -S
option to gcc (or g++).
gcc -S helloworld.c
This will run the preprocessor (cpp) over helloworld.c, perform the initial compilation and then stop before the assembler is run.
By default this will output a file helloworld.s
. The output file can be still be set by using the -o
option.
gcc -S -o my_asm_output.s helloworld.c
Of course this only works if you have the original source.
An alternative if you only have the resultant object file is to use objdump
, by setting the --disassemble
option (or -d
for the abbreviated form).
objdump -S --disassemble helloworld > helloworld.dump
This option works best if debugging option is enabled for the object file (-g
at compilation time) and the file hasn't been stripped.
Running file helloworld
will give you some indication as to the level of detail that you will get by using objdump.
We can also use readr::parse_number
, the columns must be characters though. If we want to apply it for multiple columns we can loop through columns using lapply
df[2:3] <- lapply(df[2:3], readr::parse_number)
df
# a b c
#1 a 12234 12
#2 b 123 1234123
#3 c 1234 1234
#4 d 13456234 15342
#5 e 12312 12334512
Or use mutate_at
from dplyr
to apply it to specific variables.
library(dplyr)
df %>% mutate_at(2:3, readr::parse_number)
#Or
df %>% mutate_at(vars(b:c), readr::parse_number)
data
df <- data.frame(a = letters[1:5],
b = c("12,234", "123", "1,234", "13,456,234", "123,12"),
c = c("12", "1,234,123","1234", "15,342", "123,345,12"),
stringsAsFactors = FALSE)
Although BETWEEN
is easy to read and maintain, I rarely recommend its use because it is a closed interval and as mentioned previously this can be a problem with dates - even without time components.
For example, when dealing with monthly data it is often common to compare dates BETWEEN first AND last
, but in practice this is usually easier to write dt >= first AND dt < next-first
(which also solves the time part issue) - since determining last
usually is one step longer than determining next-first
(by subtracting a day).
In addition, another gotcha is that lower and upper bounds do need to be specified in the correct order (i.e. BETWEEN low AND high
).
You can use an array in the select() to define more columns and you can use the DB::raw() there with aliasing it to followers. Should look like this:
$query = DB::table('category_issue')
->select(array('issues.*', DB::raw('COUNT(issue_subscriptions.issue_id) as followers')))
->where('category_id', '=', 1)
->join('issues', 'category_issue.issue_id', '=', 'issues.id')
->left_join('issue_subscriptions', 'issues.id', '=', 'issue_subscriptions.issue_id')
->group_by('issues.id')
->order_by('followers', 'desc')
->get();
I know this post is closed but I think my way could help some people. So there it is :
My dataset is very similar but is a bit more complex. It has numbers, alphanumeric data :
1
2
Chair
3
0
4
5
-
Table
10
13
19
Windows
99
102
Dog
I would like to have the '-' symbol at first, then the numbers, then the text.
So I go like this :
SELECT name, (name = '-') boolDash, (name = '0') boolZero, (name+0 > 0) boolNum
FROM table
ORDER BY boolDash DESC, boolZero DESC, boolNum DESC, (name+0), name
The result should be something :
-
0
1
2
3
4
5
10
13
99
102
Chair
Dog
Table
Windows
The whole idea is doing some simple check into the SELECT and sorting with the result.
The user "geoand" is right in pointing out the reasons here and giving a solution. But a better approach is to encapsulate your configuration into a separate class, say SystemContiguration java class and then inject this class into what ever services you want to use those fields.
Your current way(@grahamrb) of reading config values directly into services is error prone and would cause refactoring headaches if config setting name is changed.
I have found out, that if you use the .getWidth/2 etc... that it won't work you need to get the number of pixels the image is and divide it by 2 yourself and then just type in the number for the last 2 arguments.
so say your image was a 120 pixel by 120 pixel square, ur x and y would equal 60 pixels. so in your code, you would right:
RotateAnimation anim = new RotateAnimation(0f, 350f, 60f, 60f);
anim.setInterpolator(new LinearInterpolator());
anim.setRepeatCount(Animation.INFINITE);
anim.setDuration(700);
and now your image will pivot round its center.
This could help:
public static String getCorporateID(String fileName) {
String corporateId = null;
try {
corporateId = fileName.substring(0, fileName.indexOf("_"));
// System.out.println(new Date() + ": " + "Corporate:
// "+corporateId);
return corporateId;
} catch (Exception e) {
corporateId = null;
e.printStackTrace();
}
return corporateId;
}
Instead of overflow:auto
, try overflow-y:auto
. Should work like a charm!
Here are the selectors used in Bootstrap 4. There is no "lowest" setting in BS4 because "extra small" is the default. I.e. you would first code the XS size and then have these media overrides afterwards.
@media(min-width:576px){}
@media(min-width:768px){}
@media(min-width:992px){}
@media(min-width:1200px){}
This will match up to the first occurrence only in each string and will ignore subsequent occurrences.
/^([^;]*);*/
You need to set line-height.
<div style="border: 1px solid red;">
<span style="font-size: 38px; vertical-align:middle; float:left; line-height: 38px">Hejsan</span>
<span style="font-size: 13px; vertical-align:middle; float:right; line-height: 38px">svejsan</span>
<div style="clear: both;"></div>
I'm not sure if this has been changed, or if it has something to do with which version of PS you're using, but using Andy's example, I can remove the -Name parameter and I still get the value of the reg item:
PS C:\> $key = 'HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion'
PS C:\> (Get-ItemProperty -Path $key).ProgramFilesDir
C:\Program Files
PS C:\> $psversiontable.psversion
Major Minor Build Revision
----- ----- ----- --------
2 0 -1 -1
This is not possible with native HTML input elements. You can use webshim polyfill, which gives you this option by using this markup.
<input type="date" data-date-inline-picker="true" />
Here is a small demo
The easiest way to check is
"key" in object
for example:
var obj = {
a: 1,
b: 2,
}
"a" in obj // true
"c" in obj // false
Return value as true implies that key exists in the object.
VS is kinda funny about C++ and IntelliSense. There are times it won't notice that it's supposed to be popping up something. This is due in no small part to the complexity of the language, and all the compiling (or at least parsing) that'd need to go on in order to make it better.
If it doesn't work for you at all, and it used to, and you've checked the VS options, maybe this can help.
def updateJsonFile():
jsonFile = open("replayScript.json", "r") # Open the JSON file for reading
data = json.load(jsonFile) # Read the JSON into the buffer
jsonFile.close() # Close the JSON file
## Working with buffered content
tmp = data["location"]
data["location"] = path
data["mode"] = "replay"
## Save our changes to JSON file
jsonFile = open("replayScript.json", "w+")
jsonFile.write(json.dumps(data))
jsonFile.close()
As of Angular 6+, this is handled slightly differently than in previous versions. As @BeetleJuice mentions in the answer above, paramMap
is new interface for getting route params, but the execution is a bit different in more recent versions of Angular. Assuming this is in a component:
private _entityId: number;
constructor(private _route: ActivatedRoute) {
// ...
}
ngOnInit() {
// For a static snapshot of the route...
this._entityId = this._route.snapshot.paramMap.get('id');
// For subscribing to the observable paramMap...
this._route.paramMap.pipe(
switchMap((params: ParamMap) => this._entityId = params.get('id'))
);
// Or as an alternative, with slightly different execution...
this._route.paramMap.subscribe((params: ParamMap) => {
this._entityId = params.get('id');
});
}
I prefer to use both because then on direct page load I can get the ID param, and also if navigating between related entities the subscription will update properly.
Your executable's working directory is probably set to something other than the directory where it is saved. Check your IDE settings.
You can use json
like the following example.
PHP code:
echo json_encode($array);
$array
is array data, and the jQuery code is:
$.get("period/education/ajaxschoollist.php?schoolid="+schoolid, function(responseTxt, statusTxt, xhr){
var a = JSON.parse(responseTxt);
$("#hideschoolid").val(a.schoolid);
$("#section_id").val(a.section_id);
$("#schoolname").val(a.schoolname);
$("#country_id").val(a.country_id);
$("#state_id").val(a.state_id);
}
This worked for me in laravel 4.2
$id = User::insertGetId([
'username' => Input::get('username'),
'password' => Hash::make('password'),
'active' => 0
]);
If they fall into logical groups, I would probably go with the class approach already listed here.
Many people seem to forget that you can actually select several items by id in the same jQuery selector, as well:
$("#div1, #div2, #div3").show();
Where 'div1', 'div2', and 'div3' are all id attributes on various divs you want to show at once.
Using the new nested query syntax
with q(name, id, parent_id, parent_name) as (
select
t1.name, t1.id,
null as parent_id, null as parent_name
from t1
where t1.id = 1
union all
select
t1.name, t1.id,
q.id as parent_id, q.name as parent_name
from t1, q
where t1.parent_id = q.id
)
select * from q
This method will create the folder if it does not exist and do nothing if it exists:
Directory.CreateDirectory(path);
For very simple pseudorandom-looking stuff, I use this oneliner that I found on the internet somewhere:
float rand(vec2 co){
return fract(sin(dot(co.xy ,vec2(12.9898,78.233))) * 43758.5453);
}
You can also generate a noise texture using whatever PRNG you like, then upload this in the normal fashion and sample the values in your shader; I can dig up a code sample later if you'd like.
Also, check out this file for GLSL implementations of Perlin and Simplex noise, by Stefan Gustavson.
If you are in an XML file, use the following to make your imageview transparent!
android:background="@null"
You can use a for loop with window.scrollTo and setTimeout to scroll smoothly with plain Javascript. To scroll to an element with my scrollToSmoothly
function: scrollToSmoothly(elem.offsetTop)
(assuming elem
is a DOM element). You can use this to scroll smoothly to any y-position in the document.
function scrollToSmoothly(pos, time){
/*Time is only applicable for scrolling upwards*/
/*Code written by hev1*/
/*pos is the y-position to scroll to (in pixels)*/
if(isNaN(pos)){
throw "Position must be a number";
}
if(pos<0){
throw "Position can not be negative";
}
var currentPos = window.scrollY||window.screenTop;
if(currentPos<pos){
var t = 10;
for(let i = currentPos; i <= pos; i+=10){
t+=10;
setTimeout(function(){
window.scrollTo(0, i);
}, t/2);
}
} else {
time = time || 2;
var i = currentPos;
var x;
x = setInterval(function(){
window.scrollTo(0, i);
i -= 10;
if(i<=pos){
clearInterval(x);
}
}, time);
}
}
Demo:
<button onClick="scrollToDiv()">Scroll To Element</button>_x000D_
<div style="margin: 1000px 0px; text-align: center;">Div element<p/>_x000D_
<button onClick="scrollToSmoothly(Number(0))">Scroll back to top</button>_x000D_
</div>_x000D_
<script>_x000D_
function scrollToSmoothly(pos, time){_x000D_
/*Time is only applicable for scrolling upwards*/_x000D_
/*Code written by hev1*/_x000D_
/*pos is the y-position to scroll to (in pixels)*/_x000D_
if(isNaN(pos)){_x000D_
throw "Position must be a number";_x000D_
}_x000D_
if(pos<0){_x000D_
throw "Position can not be negative";_x000D_
}_x000D_
var currentPos = window.scrollY||window.screenTop;_x000D_
if(currentPos<pos){_x000D_
var t = 10;_x000D_
for(let i = currentPos; i <= pos; i+=10){_x000D_
t+=10;_x000D_
setTimeout(function(){_x000D_
window.scrollTo(0, i);_x000D_
}, t/2);_x000D_
}_x000D_
} else {_x000D_
time = time || 2;_x000D_
var i = currentPos;_x000D_
var x;_x000D_
x = setInterval(function(){_x000D_
window.scrollTo(0, i);_x000D_
i -= 10;_x000D_
if(i<=pos){_x000D_
clearInterval(x);_x000D_
}_x000D_
}, time);_x000D_
}_x000D_
}_x000D_
function scrollToDiv(){_x000D_
var elem = document.querySelector("div");_x000D_
scrollToSmoothly(elem.offsetTop);_x000D_
}_x000D_
</script>
_x000D_
You should be aware that you should avoid file I/O from within Linux kernel when possible. The main idea is to go "one level deeper" and call VFS level functions instead of the syscall handler directly:
Includes:
#include <linux/fs.h>
#include <asm/segment.h>
#include <asm/uaccess.h>
#include <linux/buffer_head.h>
Opening a file (similar to open):
struct file *file_open(const char *path, int flags, int rights)
{
struct file *filp = NULL;
mm_segment_t oldfs;
int err = 0;
oldfs = get_fs();
set_fs(get_ds());
filp = filp_open(path, flags, rights);
set_fs(oldfs);
if (IS_ERR(filp)) {
err = PTR_ERR(filp);
return NULL;
}
return filp;
}
Close a file (similar to close):
void file_close(struct file *file)
{
filp_close(file, NULL);
}
Reading data from a file (similar to pread):
int file_read(struct file *file, unsigned long long offset, unsigned char *data, unsigned int size)
{
mm_segment_t oldfs;
int ret;
oldfs = get_fs();
set_fs(get_ds());
ret = vfs_read(file, data, size, &offset);
set_fs(oldfs);
return ret;
}
Writing data to a file (similar to pwrite):
int file_write(struct file *file, unsigned long long offset, unsigned char *data, unsigned int size)
{
mm_segment_t oldfs;
int ret;
oldfs = get_fs();
set_fs(get_ds());
ret = vfs_write(file, data, size, &offset);
set_fs(oldfs);
return ret;
}
Syncing changes a file (similar to fsync):
int file_sync(struct file *file)
{
vfs_fsync(file, 0);
return 0;
}
[Edit] Originally, I proposed using file_fsync, which is gone in newer kernel versions. Thanks to the poor guy suggesting the change, but whose change was rejected. The edit was rejected before I could review it.
Snapshot simply means depending on your configuration Maven will check latest changes on a special dependency. Snapshot is unstable because it is under development but if on a special project needs to has a latest changes you must configure your dependency version to snapshot version. This scenario occurs in big organizations with multiple products that these products related to each other very closely.
Set your own content container class with 1000px width property and then use container-fluid boostrap class instead of container.
Works but might not be the best solution.
I think that, we don't need parse the JSON object into a string, if the remote server accepts json into they request, just run:
const request = await fetch ('/echo/json', {
headers: {
'Content-type': 'application/json'
},
method: 'POST',
body: { a: 1, b: 2 }
});
Such as the curl request
curl -v -X POST -H 'Content-Type: application/json' -d '@data.json' '/echo/json'
In case to the remote serve not accept a json file as the body, just send a dataForm:
const data = new FormData ();
data.append ('a', 1);
data.append ('b', 2);
const request = await fetch ('/echo/form', {
headers: {
'Content-type': 'application/x-www-form-urlencoded'
},
method: 'POST',
body: data
});
Such as the curl request
curl -v -X POST -H 'Content-type: application/x-www-form-urlencoded' -d '@data.txt' '/echo/form'
You could use the "Shown" event: MSDN - Form.Shown
"The Shown event is only raised the first time a form is displayed; subsequently minimizing, maximizing, restoring, hiding, showing, or invalidating and repainting will not raise this event."
The easiest solution to make Angular 2+ application served from Amazon S3 and direct URLs working is to specify index.html both as Index and Error documents in S3 bucket configuration.
For client code, Promise is for observing or attaching callback when a result is available, whereas Future is to wait for result and then continue. Theoretically anything which is possible to do with futures what can done with promises, but due to the style difference, the resultant API for promises in different languages make chaining easier.
When inserting the generated ID is saved into the instance of the object being saved (see below):
protected void btnInsertProductCategory_Click(object sender, EventArgs e)
{
ProductCategory productCategory = new ProductCategory();
productCategory.Name = “Sample Category”;
productCategory.ModifiedDate = DateTime.Now;
productCategory.rowguid = Guid.NewGuid();
int id = InsertProductCategory(productCategory);
lblResult.Text = id.ToString();
}
//Insert a new product category and return the generated ID (identity value)
private int InsertProductCategory(ProductCategory productCategory)
{
ctx.ProductCategories.InsertOnSubmit(productCategory);
ctx.SubmitChanges();
return productCategory.ProductCategoryID;
}
reference: http://blog.jemm.net/articles/databases/how-to-common-data-patterns-with-linq-to-sql/#4
The duplicate values in any column can be deleted with a simple for loop.
Sub remove()
Dim a As Long
For a = Cells(Rows.Count, 1).End(xlUp).Row To 1 Step -1
If WorksheetFunction.CountIf(Range("A1:A" & a), Cells(a, 1)) > 1 Then Rows(a).Delete
Next
End Sub
I solved this problem using @Kjuly's answer and the specific line:
"The reason failed to build might be that, the project does not support the architecture of the device you connected."
With Xcode loaded it automatically set my iPad app to iPad Air
This caused the dependancy analysis error.
Changing the device type immediately solved the issue:
I don't know why this works but this is a very quick answer which saved me a lot of fiddling around in the background and instantly got the app working to test. I would never have thought that this could be a thing and something so simple would fix it but in this case it did.
While AngularJS allows you to get a hand on a click event (and thus a target of it) with the following syntax (note the $event
argument to the setMaster
function; documentation here: http://docs.angularjs.org/api/ng.directive:ngClick):
function AdminController($scope) {
$scope.setMaster = function(obj, $event){
console.log($event.target);
}
}
this is not very angular-way of solving this problem. With AngularJS the focus is on the model manipulation. One would mutate a model and let AngularJS figure out rendering.
The AngularJS-way of solving this problem (without using jQuery and without the need to pass the $event
argument) would be:
<div ng-controller="AdminController">
<ul class="list-holder">
<li ng-repeat="section in sections" ng-class="{active : isSelected(section)}">
<a ng-click="setMaster(section)">{{section.name}}</a>
</li>
</ul>
<hr>
{{selected | json}}
</div>
where methods in the controller would look like this:
$scope.setMaster = function(section) {
$scope.selected = section;
}
$scope.isSelected = function(section) {
return $scope.selected === section;
}
Here is the complete jsFiddle: http://jsfiddle.net/pkozlowski_opensource/WXJ3p/15/
Depending on what you want the file to contain:
touch /path/to/file
for an empty filesomecommand > /path/to/file
for a file containing the output of some command.
eg: grep --help > randomtext.txt
echo "This is some text" > randomtext.txt
nano /path/to/file
or vi /path/to/file
(or any other editor emacs,gedit etc
)
It either opens the existing one for editing or creates & opens the empty file to enter, if it doesn't exist
Create the file using cat
$ cat > myfile.txt
Now, just type whatever you want in the file:
Hello World!
CTRL-D to save and exit
There are several possible solutions:
touch file
>file
echo -n > file
printf '' > file
The echo
version will work only if your version of echo
supports the -n
switch to suppress newlines. This is a non-standard addition. The other examples will all work in a POSIX shell.
echo '' > file
printf '\n' > file
This is a valid "text file" because it ends in a newline.
"$EDITOR" file
echo 'text' > file
cat > file <<END \
text
END
printf 'text\n' > file
These are equivalent. The $EDITOR
command assumes that you have an interactive text editor defined in the EDITOR environment variable and that you interactively enter equivalent text. The cat
version presumes a literal newline after the \
and after each other line. Other than that these will all work in a POSIX shell.
Of course there are many other methods of writing and creating files, too.
I use both PuTTY and Bitvise SSH Client. PuTTY handles screen sessions better, but Bitvise automatically opens up a SFTP window so you can transfer files just like you would with an FTP client.
Hiya demo http://jsfiddle.net/LYTbc/
this is a reference to the DOM element, so you can wrap it directly.
attr
api: http://api.jquery.com/attr/
The .attr() method gets the attribute value for only the first element in the matched set.
have a nice one, cheers!
code
$(document).ready(function () {
$(".inputs").click(function () {
alert(this.id);
alert(" or " + $(this).attr("id"));
});
});?
The reason I used a +
instead of a '*' is because a plus is defined as one or more of the preceding element, where an asterisk is zero or more. In this case we want a delimiter that's a little more concrete, so "one or more" spaces.
word[Aa]\s+word[Bb]\s+word[Cc]
will match:
wordA wordB wordC
worda wordb wordc
wordA wordb wordC
The words, in this expression, will have to be specific, and also in order (a, b, then c)
It's virtual machine dependent.
Try this, Examples:
Math.Floor() vs Math.Truncate()
Math.Floor(2.56) = 2
Math.Floor(3.22) = 3
Math.Floor(-2.56) = -3
Math.Floor(-3.26) = -4
Math.Truncate(2.56) = 2
Math.Truncate(2.00) = 2
Math.Truncate(1.20) = 1
Math.Truncate(-3.26) = -3
Math.Truncate(-3.96) = -3
Also Math.Round()
Math.Round(1.6) = 2
Math.Round(-8.56) = -9
Math.Round(8.16) = 8
Math.Round(8.50) = 8
Math.Round(8.51) = 9
math.floor()
Returns the largest integer less than or equal to the specified number. MSDN system.math.floor
math.truncate()
Calculates the integral part of a number. MSDN system.math.truncate
It's better to use the select event instead. The change event is bound to keydown as Wil said. So if you want to listen to change on selection use select like that.
$("#yourcomponent").autocomplete({
select: function(event, ui) {
console.log(ui);
}
});
First of all, cp33 means that it is to be used when you have Python 3.3 running on your system. So if you have Python 2.7 on your system, try installing the cp27 version.
Installing scipy-0.18.1-cp27-cp27m-win_amd64.whl, needs a Python 2.7 running and a 64-bit system.
If you are still getting an error saying "scipy-0.18.1-cp27-cp27m-win_amd64.whl is not a supported wheel on this platform", then go for the win32 version. By this I mean install scipy-0.18.1-cp27-cp27m-win32.whl instead of the first one. This is because you might be running a 32-bit python on a 64-bit system. The last step successfully installed scipy for me.
You can use
if defined (variable) echo That's defined!
if not defined (variable) echo Nope. Undefined.
just make it function,
<script type="text/javascript">
function AlertIt() {
var answer = confirm ("Please click on OK to continue.")
if (answer)
window.location="http://www.continue.com";
}
</script>
<a href="javascript:AlertIt();">click me</a>
Turn the axes off with:
plt.axis('off')
And gridlines with:
plt.grid(b=None)
I wrote the following code to convert an image from sdcard to a Base64 encoded string to send as a JSON object.And it works great:
String filepath = "/sdcard/temp.png";
File imagefile = new File(filepath);
FileInputStream fis = null;
try {
fis = new FileInputStream(imagefile);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
Bitmap bm = BitmapFactory.decodeStream(fis);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bm.compress(Bitmap.CompressFormat.JPEG, 100 , baos);
byte[] b = baos.toByteArray();
encImage = Base64.encodeToString(b, Base64.DEFAULT);
Found it at http://www.linuxquestions.org/questions/suse-novell-60/howto-kill-defunct-processes-574612/
2) Here a great tip from another user (Thxs Bill Dandreta): Sometimes
kill -9 <pid>
will not kill a process. Run
ps -xal
the 4th field is the parent process, kill all of a zombie's parents and the zombie dies!
Example
4 0 18581 31706 17 0 2664 1236 wait S ? 0:00 sh -c /usr/bin/gcc -fomit-frame-pointer -O -mfpmat
4 0 18582 18581 17 0 2064 828 wait S ? 0:00 /usr/i686-pc-linux-gnu/gcc-bin/3.3.6/gcc -fomit-fr
4 0 18583 18582 21 0 6684 3100 - R ? 0:00 /usr/lib/gcc-lib/i686-pc-linux-gnu/3.3.6/cc1 -quie
18581
, 18582
, 18583
are zombies -
kill -9 18581 18582 18583
has no effect.
kill -9 31706
removes the zombies.
You could query the dataset and then loop the selected rows to set them as delete.
var rows = dt.Select("col1 > 5");
foreach (var row in rows)
row.Delete();
... and you could also create some extension methods to make it easier ...
myTable.Delete("col1 > 5");
public static DataTable Delete(this DataTable table, string filter)
{
table.Select(filter).Delete();
return table;
}
public static void Delete(this IEnumerable<DataRow> rows)
{
foreach (var row in rows)
row.Delete();
}
Enter the image and give height:100%;width:auto
then just change the height of navbar itself to resize image. There is a really good example in codepen. https://codepen.io/bootstrapped/pen/KwYGwq
The most you could do is to trigger a background image change when hovering the LI. If you want something to happen upon clicking an LI and then staying that way, then you'll need to use some JS.
I would name the images starting with bw_ and clr_ and just use JS to swap between them.
example:
$("#images").find('img').bind("click", function() {
var src = $(this).attr("src"),
state = (src.indexOf("bw_") === 0) ? 'bw' : 'clr';
(state === 'bw') ? src = src.replace('bw_','clr_') : src = src.replace('clr_','bw_');
$(this).attr("src", src);
});
link to fiddle: http://jsfiddle.net/felcom/J2ucD/
WebConfigurationManager.ConnectionStrings["YourConnectionString"].ProviderName;
Axes sizing in MATLAB can be a bit tricky sometimes. You are correct to suspect the paper sizing properties as one part of the problem. Another is the automatic margins MATLAB calculates. Fortunately, there are settable axes properties that allow you to circumvent these margins. You can reset the margins to be just big enough for axis labels using a combination of the Position
and TightInset
properties which are explained here. Try this:
>> h = figure; >> axes; >> set(h, 'InvertHardcopy', 'off'); >> saveas(h, 'WithMargins.pdf');
and you'll get a PDF that looks like: but now do this:
>> tightInset = get(gca, 'TightInset'); >> position(1) = tightInset(1); >> position(2) = tightInset(2); >> position(3) = 1 - tightInset(1) - tightInset(3); >> position(4) = 1 - tightInset(2) - tightInset(4); >> set(gca, 'Position', position); >> saveas(h, 'WithoutMargins.pdf');
and you'll get:
It all depends on what is your definition of 'clear'. One of the valid ones certainly is:
slice = slice[:0]
But there's a catch. If slice elements are of type T:
var slice []T
then enforcing len(slice)
to be zero, by the above "trick", doesn't make any element of
slice[:cap(slice)]
eligible for garbage collection. This might be the optimal approach in some scenarios. But it might also be a cause of "memory leaks" - memory not used, but potentially reachable (after re-slicing of 'slice') and thus not garbage "collectable".
Use -ms-border-radius: 15px
, any element that uses css -ms- is compatible with IE.
In Python 3, they made the /
operator do a floating-point division, and added the //
operator to do integer division (i.e., quotient without remainder); whereas in Python 2, the /
operator was simply integer division, unless one of the operands was already a floating point number.
In Python 2.X:
>>> 10/3
3
>>> # To get a floating point number from integer division:
>>> 10.0/3
3.3333333333333335
>>> float(10)/3
3.3333333333333335
In Python 3:
>>> 10/3
3.3333333333333335
>>> 10//3
3
For further reference, see PEP238.
I've found required options ('target bytecode version') in settings > compiler > java compiler in my case (intelij idea 12.1.3)
Move them to an array, sort that array, and then use that array for your purposes. Here's a solution:
var maxSpeed = {
car: 300,
bike: 60,
motorbike: 200,
airplane: 1000,
helicopter: 400,
rocket: 8 * 60 * 60
};
var sortable = [];
for (var vehicle in maxSpeed) {
sortable.push([vehicle, maxSpeed[vehicle]]);
}
sortable.sort(function(a, b) {
return a[1] - b[1];
});
//[["bike", 60], ["motorbike", 200], ["car", 300],
//["helicopter", 400], ["airplane", 1000], ["rocket", 28800]]
Once you have the array, you could rebuild the object from the array in the order you like, thus achieving exactly what you set out to do. That would work in all the browsers I know of, but it would be dependent on an implementation quirk, and could break at any time. You should never make assumptions about the order of elements in a JavaScript object.
var objSorted = {}
sortable.forEach(function(item){
objSorted[item[0]]=item[1]
})
In ES8, you can use Object.entries()
to convert the object into an array:
const maxSpeed = {
car: 300,
bike: 60,
motorbike: 200,
airplane: 1000,
helicopter: 400,
rocket: 8 * 60 * 60
};
const sortable = Object.entries(maxSpeed)
.sort(([,a],[,b]) => a-b)
.reduce((r, [k, v]) => ({ ...r, [k]: v }), {});
console.log(sortable);
_x000D_
In ES10, you can use Object.fromEntries()
to convert array to object. Then the code can be simplified to this:
const maxSpeed = {
car: 300,
bike: 60,
motorbike: 200,
airplane: 1000,
helicopter: 400,
rocket: 8 * 60 * 60
};
const sortable = Object.fromEntries(
Object.entries(maxSpeed).sort(([,a],[,b]) => a-b)
);
console.log(sortable);
_x000D_
When you use a web service you have a client and a server:
When you use a message queue like RabbitMQ, Beanstalkd, ActiveMQ, IBM MQ Series, Tuxedo you expect different and more fault tolerant results:
Message Queues has a lot more features but this is some rule of thumb to decide if you want to handle error conditions yourself or leave them to the message queue.
create a script including the following; (replace the ant and jdk paths with whatever is correct for your machine)
set PATH=%BASEPATH%
set ANT_HOME=c:\tools\apache-ant-1.9-bin
set JAVA_HOME=c:\tools\jdk7x64
set PATH=%ANT_HOME%\bin;%JAVA_HOME%\bin;%PATH%
run it in shell.
I'm going to show you an example that will help you to understand why it's important.
Such as you have some Box Widgets and you want to show some hidden content inside every single widget. You can do this easily when you have a different CSS class for the single widget but when it has the same class how can you do that?
Actually, that's why we use $(this)
**Please check the code and run it :) ** enter image description here
(function(){ _x000D_
_x000D_
jQuery(".single-content-area").hover(function(){_x000D_
jQuery(this).find(".hidden-content").slideDown();_x000D_
})_x000D_
_x000D_
jQuery(".single-content-area").mouseleave(function(){_x000D_
jQuery(this).find(".hidden-content").slideUp();_x000D_
})_x000D_
_x000D_
})();
_x000D_
.mycontent-wrapper {_x000D_
display: flex;_x000D_
width: 800px;_x000D_
margin: auto;_x000D_
} _x000D_
.single-content-area {_x000D_
background-color: #34495e;_x000D_
color: white; _x000D_
text-align: center;_x000D_
padding: 20px;_x000D_
margin: 15px;_x000D_
display: block;_x000D_
width: 33%;_x000D_
}_x000D_
.hidden-content {_x000D_
display: none;_x000D_
}
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
<div class="mycontent-wrapper">_x000D_
<div class="single-content-area">_x000D_
<div class="content">_x000D_
Name: John Doe <br/>_x000D_
Age: 33 <br/>_x000D_
Addres: Bangladesh_x000D_
</div> <!--/.normal-content-->_x000D_
<div class="hidden-content">_x000D_
This is hidden content_x000D_
</div> <!--/.hidden-content-->_x000D_
</div><!--/.single-content-area-->_x000D_
_x000D_
<div class="single-content-area">_x000D_
<div class="content">_x000D_
Name: John Doe <br/>_x000D_
Age: 33 <br/>_x000D_
Addres: Bangladesh_x000D_
</div> <!--/.normal-content-->_x000D_
<div class="hidden-content">_x000D_
This is hidden content_x000D_
</div> <!--/.hidden-content-->_x000D_
</div><!--/.single-content-area-->_x000D_
_x000D_
_x000D_
<div class="single-content-area">_x000D_
<div class="content">_x000D_
Name: John Doe <br/>_x000D_
Age: 33 <br/>_x000D_
Addres: Bangladesh_x000D_
</div> <!--/.normal-content-->_x000D_
<div class="hidden-content">_x000D_
This is hidden content_x000D_
</div> <!--/.hidden-content-->_x000D_
</div><!--/.single-content-area-->_x000D_
_x000D_
</div><!--/.mycontent-wrapper-->
_x000D_
DateTime
is a DataType which is used to store both Date
and Time
. But it provides Properties to get the Date
Part.
You can get the Date part from Date
Property.
http://msdn.microsoft.com/en-us/library/system.datetime.date.aspx
DateTime date1 = new DateTime(2008, 6, 1, 7, 47, 0);
Console.WriteLine(date1.ToString());
// Get date-only portion of date, without its time.
DateTime dateOnly = date1.Date;
// Display date using short date string.
Console.WriteLine(dateOnly.ToString("d"));
// Display date using 24-hour clock.
Console.WriteLine(dateOnly.ToString("g"));
Console.WriteLine(dateOnly.ToString("MM/dd/yyyy HH:mm"));
// The example displays the following output to the console:
// 6/1/2008 7:47:00 AM
// 6/1/2008
// 6/1/2008 12:00 AM
// 06/01/2008 00:00
The /EXCLUDE:
argument expects a file containing a list of excluded files.
So create a file called excludedfileslist.txt
containing:
.cs\
Then a command like this:
xcopy /r /d /i /s /y /exclude:excludedfileslist.txt C:\dev\apan C:\web\apan
Alternatively you could use Robocopy, but would require installing / copying a robocopy.exe
to the machines.
An anonymous comment edit which simply stated "This Solution exclude also css file!"
This is true creating a excludedfileslist.txt
file contain just:
.cs
(note no backslash on the end)
Will also exclude all of the following:
file1.cs
file2.css
dir1.cs\file3.txt
dir2\anyfile.cs.something.txt
Sometimes people don't read or understand the XCOPY command's help, here is an item I would like to highlight:
Using /exclude
- List each string in a separate line in each file. If any of the listed strings match any part of the absolute path of the file to be copied, that file is then excluded from the copying process. For example, if you specify the string "\Obj\", you exclude all files underneath the Obj directory. If you specify the string ".obj", you exclude all files with the .obj extension.
As the example states it excludes "all files with the .obj extension" but it doesn't state that it also excludes files or directories named file1.obj.tmp
or dir.obj.output\example2.txt
.
There is a way around .css
files being excluded also, change the excludedfileslist.txt
file to contain just:
.cs\
(note the backslash on the end).
Here is a complete test sequence for your reference:
C:\test1>ver
Microsoft Windows [Version 6.1.7601]
C:\test1>md src
C:\test1>md dst
C:\test1>md src\dir1
C:\test1>md src\dir2.cs
C:\test1>echo "file contents" > src\file1.cs
C:\test1>echo "file contents" > src\file2.css
C:\test1>echo "file contents" > src\dir1\file3.txt
C:\test1>echo "file contents" > src\dir1\file4.cs.txt
C:\test1>echo "file contents" > src\dir2.cs\file5.txt
C:\test1>xcopy /r /i /s /y .\src .\dst
.\src\file1.cs
.\src\file2.css
.\src\dir1\file3.txt
.\src\dir1\file4.cs.txt
.\src\dir2.cs\file5.txt
5 File(s) copied
C:\test1>echo .cs > excludedfileslist.txt
C:\test1>xcopy /r /i /s /y /exclude:excludedfileslist.txt .\src .\dst
.\src\dir1\file3.txt
1 File(s) copied
C:\test1>echo .cs\ > excludedfileslist.txt
C:\test1>xcopy /r /i /s /y /exclude:excludedfileslist.txt .\src .\dst
.\src\file2.css
.\src\dir1\file3.txt
.\src\dir1\file4.cs.txt
3 File(s) copied
This test was completed on a Windows 7 command line and retested on Windows 10 "10.0.14393".
Note that the last example does exclude .\src\dir2.cs\file5.txt
which may or may not be unexpected for you.
It is a very murky distinction, and in fact generally not a property of a language itself, but rather of the program you are using to execute code in that language.
However, most languages are used primarily in one form or the other, and yes, Java is essentially always compiled, while javascript is essentially always interpreted.
To compile source code is to run a program on it that generates a binary, executable file that, when run, has the behavior defined by the source. For instance, javac compiles human-readbale .java files into machine-readable .class files.
To interpret source code is run a program on it that produces the defined behavior right away, without generating an intermediary file. For instance, when your web browser loads stackoverflow.com, it interprets a bunch of javascript (which you can look at by viewing the page source) and produces lots of the nice effects these pages have - for instance, upvoting, or the little notifier bars across the top.
Here's a dplyr
option:
library(dplyr)
# across all columns:
df %>% filter_all(any_vars(. %in% c('M017', 'M018')))
# or in only select columns:
df %>% filter_at(vars(col1, col2), any_vars(. %in% c('M017', 'M018')))
Your best bet is KissFFT - as its name implies it's simple, but it's still quite respectably fast, and a lot more lightweight than FFTW. It's also free, wheras FFTW requires a hefty licence fee if you want to include it in a commercial product.
You can use Java jar
tool. List the content of jar file in a txt file and you can see all the classes in the jar.
jar tvf jarfile.jar
-t list table of contents for archive
-v generate verbose output on standard output
-f specify archive file name
I also encountered the same problem on Mac OSX 10.6.8 and unfortunately adding #include <stdint.h>
or <cstdint.h>
to the corresponding file did not solve my problem. However, after more search, I found this solution advicing to add #include <sys/types.h>
which worked well for me!
You cannot return value after resolving promise. Instead call another function when promise is resolved:
function justTesting() {
promise.then(function(output) {
// instead of return call another function
afterResolve(output + 1);
});
}
function afterResolve(result) {
// do something with result
}
var test = justTesting();
//You may use this example. Might be help you...
$user = User::select("users.*","items.id as itemId","jobs.id as jobId")
->join("items","items.user_id","=","users.id")
->join("jobs",function($join){
$join->on("jobs.user_id","=","users.id")
->on("jobs.item_id","=","items.id");
})
->get();
print_r($user);
Try this:
net use * /delete /y
The /y
key makes it select Yes in prompt silently
You have enabled CORS and enabled Access-Control-Allow-Origin : *
in the server.If still you get GET
method working and POST
method is not working then it might be because of the problem of Content-Type
and data
problem.
First AngularJS transmits data using Content-Type: application/json
which is not serialized natively by some of the web servers (notably PHP). For them we have to transmit the data as Content-Type: x-www-form-urlencoded
Example :-
$scope.formLoginPost = function () {
$http({
url: url,
method: "POST",
data: $.param({ 'username': $scope.username, 'Password': $scope.Password }),
headers: { 'Content-Type': 'application/x-www-form-urlencoded' }
}).then(function (response) {
// success
console.log('success');
console.log("then : " + JSON.stringify(response));
}, function (response) { // optional
// failed
console.log('failed');
console.log(JSON.stringify(response));
});
};
Note : I am using $.params
to serialize the data to use Content-Type: x-www-form-urlencoded
. Alternatively you can use the following javascript function
function params(obj){
var str = "";
for (var key in obj) {
if (str != "") {
str += "&";
}
str += key + "=" + encodeURIComponent(obj[key]);
}
return str;
}
and use params({ 'username': $scope.username, 'Password': $scope.Password })
to serialize it as the Content-Type: x-www-form-urlencoded
requests only gets the POST data in username=john&Password=12345
form.
the jnr-process project provides this capability.
It is part of the java native runtime used by jruby and can be considered a prototype for a future java-FFI
In addition to the anwsers above you can use PadLeft or PadRight:
string name = "John";
string surname = "Smith";
Console.WriteLine("Name:".PadRight(15)+"Surname:".PadRight(15));
Console.WriteLine( name.PadRight(15) + surname.PadRight(15));
This will fill in the string with spaces to the left or right.