I have been having the same problem. VB6 Win7 64 bit and have come across a very simple solution, so I figured it would be a good idea to share it here in case it helps anyone else.
First I have tried the following with no success:
unregistered and re-registering MSCOMCTL, MSCOMCTL2 and the barcode active X controls in every directory I could think of trying (VB98, system 32, sysWOW64, project folder.)
Deleting working folder and getting everything again. (through source safe)
Copying the OCX files from a machine with no problems and registering those.
Installing service pack 6
Installing MZ tools - it was worth a try
Installing the distributable version of the project.
Manually editing the vbp file (after making it writeable) to amend/remove the references and generally fiddling.
Un-Installing VB6 and re-Installing (this I thought was a last resort) The problem was occurring on a new project and not just existing ones.
NONE of the above worked but the following did
Open VB6
New project
>Project
>Components
Tick the following:
Microsoft flexigrid control 6.0 (sp6)
Microsoft MAPI controls 6.0
Microsoft Masked Edit Control 6.0 (sp3)
Microsoft Tabbed Dialog Control 6.0 (sp6)
>Apply
After this I could still not tick the Barcode Active X or the windows common contols 6.0 and windows common controls 2 6.0, but when I clicked apply, the message changed from unregistered, to that it was already in the project.
>exit the components dialog and then load project.
This time it worked. Tried the components dialog again and the missing three were now ticked. Everything seems fine now.
I encountered this error since my encoded image started with data:image/png;base64,iVBORw0...
.
This answer led me to the solution:
String partSeparator = ",";
if (data.contains(partSeparator)) {
String encodedImg = data.split(partSeparator)[1];
byte[] decodedImg = Base64.getDecoder().decode(encodedImg.getBytes(StandardCharsets.UTF_8));
Path destinationFile = Paths.get("/path/to/imageDir", "myImage.jpg");
Files.write(destinationFile, decodedImg);
}
Me, I'd do it something like this:
HTML:
onclick="myfunction({path:'/myController/myAction', ok:myfunctionOnOk, okArgs:['/myController2/myAction2','myParameter2'], cancel:myfunctionOnCancel, cancelArgs:['/myController3/myAction3','myParameter3']);"
JS:
function myfunction(params)
{
var path = params.path;
/* do stuff */
// on ok condition
params.ok(params.okArgs);
// on cancel condition
params.cancel(params.cancelArgs);
}
But then I'd also probable be binding a closure to a custom subscribed event. You need to add some detail to the question really, but being first-class functions are easily passable and getting params to them can be done any number of ways. I would avoid passing them as string labels though, the indirection is error prone.
Here is a link to the latest documentation as of today http://www.jetbrains.com/idea/webhelp/increasing-memory-heap.html
You could use dplyr
:
df %>% group_by("Amount") %>% slice(which.min(x))
I fixed this issue by steps :
turn off your network (wireless or wired...).
reboot your system.
before turning on your network on PC, execute command docker-compose up, it's going to create new network.
then you can turn network on and go on ...
It's actually not PHP, it's apache using mod_rewrite. What happens is the person requests the link, www.example.com/profile/12345 and then apache chops it up using a rewrite rule making it look like this, www.example.com/profile.php?u=12345, to the server. You can find more here: Rewrite Guide
In response to the good solution from macek. The solution didn't work for me. I have to bind the values of the datas to the export function. This solution works for me:
function exportToForm(a, b, c, d, e) {
console.log(a, b, c, d, e);
}
var images = document.getElementsByTagName("img");
for (var i=0, len=images.length, img; i<len; i++) {
var img = images[i];
var boundExportToForm = exportToForm.bind(undefined,
img.getAttribute("data-a"),
img.getAttribute("data-b"),
img.getAttribute("data-c"),
img.getAttribute("data-d"),
img.getAttribute("data-e"))
img.addEventListener("click", boundExportToForm);
}
Lists themselves are thread-safe. In CPython the GIL protects against concurrent accesses to them, and other implementations take care to use a fine-grained lock or a synchronized datatype for their list implementations. However, while lists themselves can't go corrupt by attempts to concurrently access, the lists's data is not protected. For example:
L[0] += 1
is not guaranteed to actually increase L[0] by one if another thread does the same thing, because +=
is not an atomic operation. (Very, very few operations in Python are actually atomic, because most of them can cause arbitrary Python code to be called.) You should use Queues because if you just use an unprotected list, you may get or delete the wrong item because of race conditions.
Sorry for resurrection. You could use child_process module to execute external js files in node.js
var child_process = require('child_process');
//EXECUTE yourExternalJsFile.js
child_process.exec('node yourExternalJsFile.js', (error, stdout, stderr) => {
console.log(`${stdout}`);
console.log(`${stderr}`);
if (error !== null) {
console.log(`exec error: ${error}`);
}
});
import requests
img_data = requests.get(image_url).content
with open('image_name.jpg', 'wb') as handler:
handler.write(img_data)
Here is the code to handle custom error message in HTML5:
<input type="text" id="username" required placeholder="Enter Name"
oninvalid="this.setCustomValidity('Enter User Name Here')"
oninput="this.setCustomValidity('')"/>
This part is important because it hides the error message when the user inputs new data:
oninput="this.setCustomValidity('')"
Ignoring the span stuff that other people have dealt with, to properly handle dictionary suggestions I found the following code works.
The source grows as the suggestion grows so we have to look at how many characters it's actually expecting us to replace before we return anything.
If we don't have any invalid characters, return null so that the default replacement occurs.
Otherwise we need to extract out the valid characters from the substring that's ACTUALLY going to be placed into the EditText.
InputFilter filter = new InputFilter() {
public CharSequence filter(CharSequence source, int start, int end,
Spanned dest, int dstart, int dend) {
boolean includesInvalidCharacter = false;
StringBuilder stringBuilder = new StringBuilder();
int destLength = dend - dstart + 1;
int adjustStart = source.length() - destLength;
for(int i=start ; i<end ; i++) {
char sourceChar = source.charAt(i);
if(Character.isLetterOrDigit(sourceChar)) {
if(i >= adjustStart)
stringBuilder.append(sourceChar);
} else
includesInvalidCharacter = true;
}
return includesInvalidCharacter ? stringBuilder : null;
}
};
With 4.0, you will need to manage this yourself by setting the culture for each thread as Alexei describes. But with 4.5, you can define a culture for the appdomain and that is the preferred way to handle this. The relevant apis are CultureInfo.DefaultThreadCurrentCulture and CultureInfo.DefaultThreadCurrentUICulture.
This can be easily done if you are using some Javascript framework like jQuery. Like so,
var x = $('script:first').attr('src'); //Fetch the source in the first script tag
var params = x.split('?')[1]; //Get the params
Now you can use these params by splitting as your variable parameters.
The same process can be done without any framework but will take some more lines of code.
As others have indicated, something of the form
x ? y : z
is an expression, not a (complete) statement. It is an rvalue which needs to get used someplace - like on the right side of an assignment, or a parameter to a function etc.
Perhaps you could look at this: http://download.oracle.com/javase/tutorial/java/nutsandbolts/expressions.html
Indeed using {{ URL:previous() }}
do work, but if you're using a same named route to display multiple views, it will take you back to the first endpoint of this route.
In my case, I have a named route, which based on a parameter selected by the user, can render 3 different views. Of course, I have a default case for the first enter in this route, when the user doesn't selected any option yet.
When I use URL:previous()
, Laravel take me back to the default view, even if the user has selected some other option. Only using javascript inside the button I accomplished to be returned to the correct view:
<a href="javascript:history.back()" class="btn btn-default">Voltar</a>
I'm tested this on Laravel 5.3, just for clarification.
Days
ClassUsing the Days
class with the withTimeAtStartOfDay
method should work:
Days.daysBetween(start.withTimeAtStartOfDay() , end.withTimeAtStartOfDay() ).getDays()
This is less for @easwee and more for others that might have the same question:
If you do not require support for IE < 10, you can use Flexbox. It's an exciting CSS3 property that unfortunately was implemented in several different versions,; add in vendor prefixes, and getting good cross-browser support suddenly requires quite a few more properties than it should.
With the current, final standard, you would be done with
.container {
display: flex;
}
.container div {
flex: 1;
}
.column_center {
order: 2;
}
That's it. If you want to support older implementations like iOS 6, Safari < 6, Firefox 19 or IE10, this blossoms into
.container {
display: -webkit-box; /* OLD - iOS 6-, Safari 3.1-6 */
display: -moz-box; /* OLD - Firefox 19- (buggy but mostly works) */
display: -ms-flexbox; /* TWEENER - IE 10 */
display: -webkit-flex; /* NEW - Chrome */
display: flex; /* NEW, Spec - Opera 12.1, Firefox 20+ */
}
.container div {
-webkit-box-flex: 1; /* OLD - iOS 6-, Safari 3.1-6 */
-moz-box-flex: 1; /* OLD - Firefox 19- */
-webkit-flex: 1; /* Chrome */
-ms-flex: 1; /* IE 10 */
flex: 1; /* NEW, Spec - Opera 12.1, Firefox 20+ */
}
.column_center {
-webkit-box-ordinal-group: 2; /* OLD - iOS 6-, Safari 3.1-6 */
-moz-box-ordinal-group: 2; /* OLD - Firefox 19- */
-ms-flex-order: 2; /* TWEENER - IE 10 */
-webkit-order: 2; /* NEW - Chrome */
order: 2; /* NEW, Spec - Opera 12.1, Firefox 20+ */
}
Here is an excellent article about Flexbox cross-browser support: Using Flexbox: Mixing Old And New
java.util.Date.from( // Transfer the moment in UTC, truncating any microseconds or nanoseconds to milliseconds.
Instant.now() ; // Capture current moment in UTC, with resolution as fine as nanoseconds.
)
Though there was no point in that code above. Both java.util.Date
and Instant
represent a moment in UTC, always in UTC. Code above has same effect as:
new java.util.Date() // Capture current moment in UTC.
No benefit here to using ZonedDateTime
. If you already have a ZonedDateTime
, adjust to UTC by extracting a Instant
.
java.util.Date.from( // Truncates any micros/nanos.
myZonedDateTime.toInstant() // Adjust to UTC. Same moment, same point on the timeline, different wall-clock time.
)
The Answer by ssoltanid correctly addresses your specific question, how to convert a new-school java.time object (ZonedDateTime
) to an old-school java.util.Date
object. Extract the Instant
from the ZonedDateTime and pass to java.util.Date.from()
.
Note that you will suffer data loss, as Instant
tracks nanoseconds since epoch while java.util.Date
tracks milliseconds since epoch.
Your Question and comments raise other issues.
Your servers should have their host OS set to UTC as a best practice generally. The JVM picks up on this host OS setting as its default time zone, in the Java implementations that I'm aware of.
But you should never rely on the JVM’s current default time zone. Rather than pick up the host setting, a flag passed when launching a JVM can set another time zone. Even worse: Any code in any thread of any app at any moment can make a call to java.util.TimeZone::setDefault
to change that default at runtime!
Timestamp
TypeAny decent database and driver should automatically handle adjusting a passed date-time to UTC for storage. I do not use Cassandra, but it does seem to have some rudimentary support for date-time. The documentation says its Timestamp
type is a count of milliseconds from the same epoch (first moment of 1970 in UTC).
Furthermore, Cassandra accepts string inputs in the ISO 8601 standard formats. Fortunately, java.time uses ISO 8601 formats as its defaults for parsing/generating strings. The Instant
class’ toString
implementation will do nicely.
But first we need to reduce the nanosecond precision of ZonedDateTime to milliseconds. One way is to create a fresh Instant using milliseconds. Fortunately, java.time has some handy methods for converting to and from milliseconds.
Here is some example code in Java 8 Update 60.
ZonedDateTime zdt = ZonedDateTime.now( ZoneId.of( "America/Montreal" ) );
…
Instant instant = zdt.toInstant();
Instant instantTruncatedToMilliseconds = Instant.ofEpochMilli( instant.toEpochMilli() );
String fodderForCassandra = instantTruncatedToMilliseconds.toString(); // Example: 2015-08-18T06:36:40.321Z
Or according to this Cassandra Java driver doc, you can pass a java.util.Date
instance (not to be confused with java.sqlDate
). So you could make a j.u.Date from that instantTruncatedToMilliseconds
in the code above.
java.util.Date dateForCassandra = java.util.Date.from( instantTruncatedToMilliseconds );
If doing this often, you could make a one-liner.
java.util.Date dateForCassandra = java.util.Date.from( zdt.toInstant() );
But it would be neater to create a little utility method.
static public java.util.Date toJavaUtilDateFromZonedDateTime ( ZonedDateTime zdt ) {
Instant instant = zdt.toInstant();
// Data-loss, going from nanosecond resolution to milliseconds.
java.util.Date utilDate = java.util.Date.from( instant ) ;
return utilDate;
}
Notice the difference in all this code than in the Question. The Question’s code was trying to adjust the time zone of the ZonedDateTime instance to UTC. But that is not necessary. Conceptually:
ZonedDateTime = Instant + ZoneId
We just extract the Instant part, which is already in UTC (basically in UTC, read the class doc for precise details).
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date
, Calendar
, & SimpleDateFormat
.
The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.*
classes.
Where to obtain the java.time classes?
The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval
, YearWeek
, YearQuarter
, and more.
Go to taskhistory.bin
in .gradle
folder of your project search password scroll down till you find the password
MSDN has an article Working With Large Value Types, which tries to explain how the import parts work, but it can get a bit confusing since it does 2 things simultaneously.
Here I am providing a simplified version, broken into 2 parts. Assume the following simple table:
CREATE TABLE [Thumbnail](
[Id] [int] IDENTITY(1,1) NOT NULL,
[Data] [varbinary](max) NULL
CONSTRAINT [PK_Thumbnail] PRIMARY KEY CLUSTERED
(
[Id] ASC
) ) ON [PRIMARY]
If you run (in SSMS):
SELECT * FROM OPENROWSET (BULK 'C:\Test\TestPic1.jpg', SINGLE_BLOB) AS X
it will show, that the result looks like a table with one column named BulkColumn
. That's why you can use it in INSERT like:
INSERT [Thumbnail] ( Data )
SELECT * FROM OPENROWSET (BULK 'C:\Test\TestPic1.jpg', SINGLE_BLOB) AS X
The rest is just fitting it into an insert with more columns, which your table may or may not have. If you name the result of that select FOO
then you can use SELECT Foo.BulkColumn
and as
after that constants for other fields in your table.
The part that can get more tricky is how to export that data back into a file so you can check that it's still OK. If you run it on cmd line:
bcp "select Data from B2B.dbo.Thumbnail where Id=1"
queryout D:\T\TestImage1_out2.dds -T -L 1
It's going to start whining for 4 additional "params" and will give misleading defaults (which will result in a changed file). You can accept the first one, set the 2nd to 0 and then assept 3rd and 4th, or to be explicit:
Enter the file storage type of field Data [varbinary(max)]:
Enter prefix-length of field Data [8]: 0
Enter length of field Data [0]:
Enter field terminator [none]:
Then it will ask:
Do you want to save this format information in a file? [Y/n] y
Host filename [bcp.fmt]: C:\Test\bcp_2.fmt
Next time you have to run it add -f C:\Test\bcp_2.fmt
and it will stop whining :-)
Saves a lot of time and grief.
Based on Xavier's answer, I wrote a Google chrome extension NuTake to add links to the Nuget.org package pages.
You should include "bPaginate": false,
into the configuration object you pass to your constructor parameters. As seen here: http://datatables.net/release-datatables/examples/basic_init/filter_only.html
Share the lines of code executed when you make this request. There might be an error in your code.
Also, you can change the memory limit in your php.ini file via the memory_limit
setting. Try doubling your memory to 64M. If this doesn't work you can try doubling it again, but I'd bet the problem is in your code.
ini_set('memory_limit', '64M');
Bootstrap sets the height of the navbar automatically to 50px. The padding above and below links is set to 15px. I think that bootstrap is adding padding to your logo.
You can either remove some of the padding above and below your logo or you can add more padding above and below links.
Adding more padding should look something like this:
nav.navbar-inverse>li>a {
padding-top: 25px;
padding-bottom: 25px;
}
There could be an error earlier in the CSS file that is causing your (correct) CSS to not work.
I had the same problem, with version 3.4.2
to run it (if you installed it with homebrew) run the process like this:
$ mongod --dbpath /usr/local/var/mongodb
Debian based distros:
sudo apt-get install python3-tk
RPM based distros:
sudo yum install python3-tkinter
For Windows, I think the problem is you didn't install complete Python package. Since Tkinter should be shipped with Python out of box. See: http://www.tkdocs.com/tutorial/install.html . Good python distributions for Windows can be found by the companies Anaconda or ActiveState.
python -c "import tkinter"
p.s. I suggest installing ipython, which provides powerful shell and necessary packages as well.
If you're going to do PHP in the command line, I recommend you install phpsh, a decent PHP shell. It's a lot more fun.
Anyway, the php
command offers two switches to execute code from the command line:
-r <code> Run PHP <code> without using script tags <?..?>
-R <code> Run PHP <code> for every input line
You can use php
's -r switch as such:
php -r 'echo function_exists("foo") ? "yes" : "no";'
The above PHP command above should output no
and returns 0
as you can see:
>>> php -r 'echo function_exists("foo") ? "yes" : "no";'
no
>>> echo $? # print the return value of the previous command
0
Another funny switch is php -a:
-a Run as interactive shell
It's sort of lame compared to phpsh, but if you don't want to install the awesome interactive shell for PHP made by Facebook to get tab completion, history, and so on, then use -a as such:
>>> php -a
Interactive shell
php > echo function_exists("foo") ? "yes" : "no";
no
php >
If it doesn't work on your box like on my boxes (tested on Ubuntu and Arch Linux), then probably your PHP setup is fuzzy or broken. If you run this command:
php -i | grep 'API'
You should see:
Server API => Command Line Interface
If you don't, this means that maybe another command will provides the CLI SAPI. Try php-cli; maybe it's a package or a command available in your OS.
If you do see that your php
command uses the CLI (command-line interface) SAPI (Server API), then run php -h | grep code
to find out which crazy switch - as this hasn't changed for year- allows to run code in your version/setup.
Another couple of examples, just to make sure it works on my boxes:
>>> php -r 'echo function_exists("sg_load") ? "yes" : "no";'
no
>>> php -r 'echo function_exists("print_r") ? "yes" : "no";'
yes
Also, note that it is possible that an extension is loaded in the CLI and not in the CGI or Apache SAPI. It is likely that several PHP SAPIs use different php.ini files, e.g., /etc/php/cli/php.ini
vs. /etc/php/cgi/php.ini
vs. /etc/php/apache/php.ini
on a Gentoo Linux box. Find out which ini file is used with php -i | grep ini
.
I know this thread is old, but...
If you're using html encoding (like AntiXSS), the previous answers will not work. The break tags will be rendered as text, rather than applying a carriage return. You can wrap your asp label in a pre tag, and it will display with whatever line breaks are set from the code behind.
Example:
<pre style="width:600px;white-space:pre-wrap;"><asp:Label ID="lblMessage" Runat="server" visible ="true"/></pre>
I came here from golang, where it's common to see something like
if (err := doSomething(); err != nil) {
return nil, err
}
In which err
is scoped to that if
block only. As such, here's what I'm doing in es6, which seems pretty ugly, but doesn't make my rather strict eslint rules whinge, and achieves the same.
{
const err = doSomething()
if (err != null) {
return (null, err)
}
}
The extra braces define a new, uh, "lexical scope"? Which means I can use const
, and err
isn't available to the outer block.
you are looking for this:
a:visited{
color:blue;
}
Links have several states you can alter... the way I remember them is LVHFA (Lord Vader's Handle Formerly Anakin)
Each letter stands for a pseudo class: (Link,Visited,Hover,Focus,Active)
a:link{
color:blue;
}
a:visited{
color:purple;
}
a:hover{
color:orange;
}
a:focus{
color:green;
}
a:active{
color:red;
}
If you want the links to always be blue, just change all of them to blue. I would note though on a usability level, it would be nice if the mouse click caused the color to change a little bit (even if just a lighter/darker blue) to help indicate that the link was actually clicked (this is especially important in a touchscreen interface where you're not always sure the click was actually registered)
If you have different types of links that you want to all have the same color when clicked, add a class to the links.
a.foo, a.foo:link, a.foo:visited, a.foo:hover, a.foo:focus, a.foo:active{
color:green;
}
a.bar, a.bar:link, a.bar:visited, a.bar:hover, a.bar:focus, a.bar:active{
color:orange;
}
It should be noted that not all browsers respect each of these options ;-)
In the year 2020 / 2021 it is even easier with Array.from
to 'convert' from a array-like nodes to an actual array, and then using .map
to loop through the resulting array.
The code is as simple as the follows:
Array.from(tableFields.children).map((child)=>console.log(child))
You can also use MethodBase.GetCurrentMethod()
which will inhibit the JIT compiler from inlining the method where it's used.
Update:
This method contains a special enumeration StackCrawlMark
that from my understanding will specify to the JIT compiler that the current method should not be inlined.
This is my interpretation of the comment associated to that enumeration present in SSCLI. The comment follows:
// declaring a local var of this enum type and passing it by ref into a function
// that needs to do a stack crawl will both prevent inlining of the calle and
// pass an ESP point to stack crawl to
//
// Declaring these in EH clauses is illegal;
// they must declared in the main method body
Sonatype Nexus and Apache Maven are two pieces of software that often work together but they do very different parts of the job. Nexus provides a repository while Maven uses a repository to build software.
Here's a quote from "What is Nexus?":
Nexus manages software "artifacts" required for development. If you develop software, your builds can download dependencies from Nexus and can publish artifacts to Nexus creating a new way to share artifacts within an organization. While Central repository has always served as a great convenience for developers you shouldn't be hitting it directly. You should be proxying Central with Nexus and maintaining your own repositories to ensure stability within your organization. With Nexus you can completely control access to, and deployment of, every artifact in your organization from a single location.
And here is a quote from "Maven and Nexus Pro, Made for Each Other" explaining how Maven uses repositories:
Maven leverages the concept of a repository by retrieving the artifacts necessary to build an application and deploying the result of the build process into a repository. Maven uses the concept of structured repositories so components can be retrieved to support the build. These components or dependencies include libraries, frameworks, containers, etc. Maven can identify components in repositories, understand their dependencies, retrieve all that are needed for a successful build, and deploy its output back to repositories when the build is complete.
So, when you want to use both you will have a repository managed by Nexus and Maven will access this repository.
See CNCopyCurrentNetworkInfo in CaptiveNetwork: http://developer.apple.com/library/ios/#documentation/SystemConfiguration/Reference/CaptiveNetworkRef/Reference/reference.html.
UPDATE
T1
SET
T1.Inci = T2.Inci
FROM
T1
INNER JOIN
T2
ON
T1.Brands = T2.Brands
AND
T1.Category= T2.Category
AND
T1.Date = T2.Date
Personally, I like this much better (which, granted, is just a different way of writing the currently selected "best answer"):
money = float(1234.5)
print('$' + format(money, ',.2f'))
Or, if you REALLY don't like "adding" multiple strings to combine them, you could do this instead:
money = float(1234.5)
print('${0}'.format(format(money, ',.2f')))
I just think both of these styles are a bit easier to read. :-)
(of course, you can still incorporate an If-Else to handle negative values as Eric suggests too)
Unfortunately, the best thing I have seen is the jquery.combobox, but it doesn't really look like something I'd really want to use in my web applications. I think there are some usability issues with this control, but as a user I don't think I'd know to start typing for the dropdownlist to turn into a textbox.
I much prefer the Combo Dropdown Box, but it still has some features that I'd want and it's still in alpha. The only think I don't like about this other than its being alpha... is that once I type in the combobox, the original dropdownlist items disappear. However, maybe there is a setting for this... or maybe it could be added fairly easily.
Those are the only two options that I know of. Good luck in your search. I'd love to hear if you find one or if the second option works out for you.
preg_match('/(?:http[s]*\:\/\/)*(.*?)\.(?=[^\/]*\..{2,5})/i', $url, $match);
Just read $match[1]
It works perfectly with this list of urls
$url = array(
'http://www.domain.com', // www
'http://domain.com', // --nothing--
'https://domain.com', // --nothing--
'www.domain.com', // www
'domain.com', // --nothing--
'www.domain.com/some/path', // www
'http://sub.domain.com/domain.com', // sub
'???????????????.????????.ua', // ??????????????? ;)
'????????.ua', // --nothing--
'http://sub-domain.domain.net/domain.net', // sub-domain
'sub-domain.third-Level_DomaIN.domain.uk.co/domain.net' // sub-domain
);
foreach ($url as $u) {
preg_match('/(?:http[s]*\:\/\/)*(.*?)\.(?=[^\/]*\..{2,5})/i', $u, $match);
var_dump($match);
}
Run your Visual Studio as Administrator
I just fixed this problem by adding the following code in header:
<meta http-equiv="Content-Security-Policy" content="upgrade-insecure-requests">
First of all, yes, a part of my answer definitely is helpful to solve the error that is posted by OP. Secondly, after trying the below step, I faced a couple of other errors, and so, have written the solution of those too.
(Psst! I am not sure if I've successfully helped in solving the above error, or if I've broken some rule or format of answering, but I faced the above error and some others and it took much time for me to find the proper solutions for those errors. I'm writing the complete solution because in case, if someone else also faces these errors, then he'll hopefully get a solution here.)
So adding to, and elaborating the answer provided by PrashanthiDevi, and also adding my personal experience, here it is:
I am new to the whole e2e and unit tests part. I started looking into this part from Protractor. Now I already had the files in which tests were written, but I had to run the tests.
I had already installed all the required softwares and tools, but when I initially ran the code for running the tests, gulp itest
, I got this 'Cannot find module' Error. After going through many different questions on SO, I found one answer that I thought could help getting a solution.
The person had suggested to run the command npm install
in my project folder.
The reason for doing this was to update the node-modules folder, inside our project folder, with all the required and necessary files and dependencies.
(The below part maybe irrelevant with this question, but might be helpful if anyone came across the same situation that I faced.)
The above step surely solved my previous error, but threw a new one! This time the error being Could not find chromedriver at '..\node_modules\protractor\selenium\chromedriver'
.
However, the solution of this error was pretty silly (and funny) to me. I already had the chromedriver file in my selenium folder. But, turns out that the above error was coming because my chromedriver files were inside selenium folder and not inside chromedriver folder. So, creating a chromedriver folder and copying the chromedriver files there solved my problem!
Also, for the error: Timed out waiting for the WebDriver Server, you could add this line of code to conf.js file inside exports.config{}
:
seleniumAddress: 'http://localhost:8080/'
Hope this helps!
Go to this link
Download version tar.gz for windows and just extract files to the folder by your needs. On the left pane, you can select which version of openjdk to download
Tutorial: unzip as expected. You need to set system variable PATH to include your directory with openjdk so you can type java -version in console.
Here I found this article which is send post request using JsonConvert.SerializeObject()
& StringContent()
to HttpClient.PostAsync
data
static async Task Main(string[] args)
{
var person = new Person();
person.Name = "John Doe";
person.Occupation = "gardener";
var json = Newtonsoft.Json.JsonConvert.SerializeObject(person);
var data = new System.Net.Http.StringContent(json, Encoding.UTF8, "application/json");
var url = "https://httpbin.org/post";
using var client = new HttpClient();
var response = await client.PostAsync(url, data);
string result = response.Content.ReadAsStringAsync().Result;
Console.WriteLine(result);
}
i changed default password from " " with space to blank
Not beautiful, but a solution nonetheless:
StringWriter writer = new StringWriter();
PrintWriter printWriter = new PrintWriter( writer );
exception.printStackTrace( printWriter );
printWriter.flush();
String stackTrace = writer.toString();
I imagine that there are not many browsers supporting extension. Indeed, I have been interested in this question for the last year and I only found Dolphin supporting add-ons and other cool features announced few days ago. I want to test it soon.
The purpose of interfaces is abstraction, or decoupling from implementation.
If you introduce an abstraction in your program, you don't care about the possible implementations. You are interested in what it can do and not how, and you use an interface
to express this in Java.
In the my.ini file in C:\xampp\mysql\bin, add the following line after the [mysqld]
command under #Mysql Server
:
skip-grant-tables
This should remove the error 1045.
The following does not return a response:
You must return anything like return afunction()
or return 'a string'
.
This can solve the issue
You have installed the library in a non-standard location ($HOME/zlib/
). That means the compiler will not know where your header files are and you need to tell the compiler that.
You can add a path to the list that the compiler uses to search for header files by using the -I
(upper-case i) option.
Also note that the LD_LIBRARY_PATH
is for the run-time linker and loader, and is searched for dynamic libraries when attempting to run an application. To add a path for the build-time linker use the -L
option.
All-together the command line should look like
$ c++ -I$HOME/zlib/include some_file.cpp -L$HOME/zlib/lib -lz
Strings are immutable types. You cannot modify them, only return new string instances.
Because of that, formatting with an instance method makes little sense, as it would have to be called like:
String formatted = "%s: %s".format(key, value);
The original Java authors (and .NET authors) decided that a static method made more sense in this situation, as you are not modifying the target, but instead calling a format method and passing in an input string.
Here is an example of why format()
would be dumb as an instance method. In .NET (and probably in Java), Replace()
is an instance method.
You can do this:
"I Like Wine".Replace("Wine","Beer");
However, nothing happens, because strings are immutable. Replace()
tries to return a new string, but it is assigned to nothing.
This causes lots of common rookie mistakes like:
inputText.Replace(" ", "%20");
Again, nothing happens, instead you have to do:
inputText = inputText.Replace(" ","%20");
Now, if you understand that strings are immutable, that makes perfect sense. If you don't, then you are just confused. The proper place for Replace()
would be where format()
is, as a static method of String
:
inputText = String.Replace(inputText, " ", "%20");
Now there is no question as to what's going on.
The real question is, why did the authors of these frameworks decide that one should be an instance method, and the other static? In my opinion, both are more elegantly expressed as static methods.
Regardless of your opinion, the truth is that you are less prone to make a mistake using the static version, and the code is easier to understand (No Hidden Gotchas).
Of course there are some methods that are perfect as instance methods, take String.Length()
int length = "123".Length();
In this situation, it's obvious we are not trying to modify "123", we are just inspecting it, and returning its length. This is a perfect candidate for an instance method.
My simple rules for Instance Methods on Immutable Objects:
On my machine:
C:\Program Files\PostgreSQL\8.4\data\postgresql.conf
I believe, 3 important aspects govern objects and their usage:
1. Instantiation (of a class together with initialisation if any).
2. Injection (of the instance so created) where it's required.
3. Life cycle management (of the instance so created).
Using Factory pattern, the first aspect (instantiation) is achieved but the remaining two is questionable. The class that uses other instances must hardcode the factories (instead of instances being created) which hinders loose coupling abilities. Moreover, life cycle management of instances becomes a challenge in a large application where a factory is used in multiple places (particularly, if the factory doesn't manage the life cycle of the instance it returns, it gets ugly).
Using a DI (of IoC pattern) on the other hand, all the 3 are abstracted outside the code (to the DI container) and the managed bean needs nothing about this complexity. Loose Coupling, a very important architectural goal can be achieved quiet comfortably. Another important architectural goal, the separation of concerns can be achieved much better than factories.
Whereas the Factories may be suitable for small applications, large ones would be better to chose DI over factories.
setTimeout() function it's use to delay a process in JavaScript.
w3schools has an easy tutorial about this function.
Another suggestion. One directive with selector.
HTML:
<button type="button" scroll-to="#catalogSection">Scroll To</button>
Angular:
app.directive('scrollTo', function () {
return {
restrict: 'A',
link: function (scope, element, attrs) {
element.on('click', function () {
var target = $(attrs.scrollTo);
if (target.length > 0) {
$('html, body').animate({
scrollTop: target.offset().top
});
}
});
}
}
});
Also notice $anchorScroll
As of Helios Service Release 2, there is no longer support for JAR files.You can add them, but Eclipse will not recognize them as libraries, therefore you can only "import" but can never use.
With the positive lookbehind technique:
(?<=\?).*
(We're searching for a text preceded by a question mark here)
Input: derpderp?mystring blahbeh
Output: mystring blahbeh
Basically the ?<=
is a group construct, that requires the escaped question-mark, before any match can be made.
They perform really well, but not all implementations support them.
It means the class is not yet added to the repository.
If your project was checked-out (most probably a CVS project) and you added a new class file, it will have the ? icon.
For other CVS Label Decorations, check http://help.eclipse.org/help33/index.jsp?topic=/org.eclipse.platform.doc.user/reference/ref-cvs-decorations.htm
I used a similar way to solve this problem using the animescm sugestion, indeed we can obtain the specific cells values from a group of selected cells using an auxiliar list:
private void dataGridCase_SelectionChanged(object sender, SelectedCellsChangedEventArgs e)
{
foreach (var item in e.AddedCells)
{
var col = item.Column as DataGridColumn;
var fc = col.GetCellContent(item.Item);
lstTxns.Items.Add((fc as TextBlock).Text);
}
}
It seems to me, that it is by design that this file is empty.
A similar question has been asked here: https://stackoverflow.com/questions/2567432/ubuntu-apache-httpd-conf-or-apache2-conf
So, you should have a look for /etc/apache2/apache2.conf
Navigate to http://www.oracle.com/technetwork/java/javase/downloads/index.html
Under Addition Resources and Under Java SE 8 Documentation
Click Download button
Under Java SE Development Kit 8 Documentation > Java SE Development Kit 8u77 Documentation
Accept the License Agreement and click on the download zip file
Unzip the downloaded file Start the API docs from jdk-8u77-docs-all\docs\api\index.html
Navigate to http://docs.oracle.com/javase/
From Release dropdown select either of Java SE 7/6/5
In corresponding JAVA SE page and under Downloads left side menu Click JDK 7/6/5 Documentation or Java SE Documentation
Now in next page select the appropriate Java SE Development Kit 7uXX Documentation.
Accept License Agreement and click on Download zip file
Unzip the file and Start the API docs from
jdk-7uXX-docs-all\docs\api\index.html
Here is another solution:
SELECT Isnull(Nullif(listing.offertext, ''), company.offertext) AS offer_text,
FROM tbl_directorylisting listing
INNER JOIN tbl_companymaster company
ON listing.company_id = company.company_id
Just supply the IP / hostname of the remote machine in your database connection string, instead of localhost
. For example:
jdbc:mysql://192.168.15.25:3306/yourdatabase
Make sure there is no firewall blocking the access to port 3306
Also, make sure the user you are connecting with is allowed to connect from this particular hostname. For development environments it is safe to do this by 'username'@'%'
. Check the user creation manual and the GRANT
manual.
Most likely the reason your push did not work is order of execution.
use
is a compile time directive. You push
is done at execution time:
push ( @INC,"directory_path/more_path");
use Foo.pm; # In directory path/more_path
You can use a BEGIN block to get around this problem:
BEGIN {
push ( @INC,"directory_path/more_path");
}
use Foo.pm; # In directory path/more_path
IMO, it's clearest, and therefore best to use lib
:
use lib "directory_path/more_path";
use Foo.pm; # In directory path/more_path
See perlmod for information about BEGIN and other special blocks and when they execute.
Edit
For loading code relative to your script/library, I strongly endorse File::FindLib
You can say use File::FindLib 'my/test/libs';
to look for a library directory anywhere above your script in the path.
Say your work is structured like this:
/home/me/projects/
|- shared/
| |- bin/
| `- lib/
`- ossum-thing/
`- scripts
|- bin/
`- lib/
Inside a script in ossum-thing/scripts/bin
:
use File::FindLib 'lib/';
use File::FindLib 'shared/lib/';
Will find your library directories and add them to your @INC
.
It's also useful to create a module that contains all the environment set-up needed to run your suite of tools and just load it in all the executables in your project.
use File::FindLib 'lib/MyEnvironment.pm'
You need to put it in the join
clause, not the where
:
SELECT *
FROM categories
LEFT JOIN user_category_subscriptions ON
user_category_subscriptions.category_id = categories.category_id
and user_category_subscriptions.user_id =1
See, with an inner join
, putting a clause in the join
or the where
is equivalent. However, with an outer join
, they are vastly different.
As a join
condition, you specify the rowset that you will be joining to the table. This means that it evaluates user_id = 1
first, and takes the subset of user_category_subscriptions
with a user_id
of 1
to join to all of the rows in categories
. This will give you all of the rows in categories
, while only the categories
that this particular user has subscribed to will have any information in the user_category_subscriptions
columns. Of course, all other categories
will be populated with null
in the user_category_subscriptions
columns.
Conversely, a where
clause does the join, and then reduces the rowset. So, this does all of the joins and then eliminates all rows where user_id
doesn't equal 1
. You're left with an inefficient way to get an inner join
.
Hopefully this helps!
Annotating all model classes looks to me as an overkill and Kenny's answer didn't work for me https://stackoverflow.com/a/43271115/4437153. The result of serialization was still camel case.
I realised that there is a problem with my spring configuration, so I had to tackle that problem from another side. Hopefully someone finds it useful, but if I'm doing something against springs' rules then please let me know.
Solution for Spring MVC 5.2.5 and Jackson 2.11.2
@Configuration
@EnableWebMvc
public class WebConfig implements WebMvcConfigurer {
@Override
public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
ObjectMapper objectMapper = new ObjectMapper();
objectMapper.setPropertyNamingStrategy(PropertyNamingStrategy.SNAKE_CASE);
MappingJackson2HttpMessageConverter converter = new MappingJackson2HttpMessageConverter();
converter.setObjectMapper(objectMapper);
converters.add(converter);
}
}
char *line = strdup("user name"); // don't do char *line = "user name"; see Note
char *first_part = strtok(line, " "); //first_part points to "user"
char *sec_part = strtok(NULL, " "); //sec_part points to "name"
Note: strtok
modifies the string, so don't hand it a pointer to string literal.
Update your working copy to the selected revision. Useful if you want to have your working copy reflect a time in the past, or if there have been further commits to the repository and you want to update your working copy one step at a time. It is best to update a whole directory in your working copy, not just one file, otherwise your working copy could be inconsistent. This is used to test a specific rev purpose, if your test has done, you can use this command to test another rev or use SVN Update to get HEAD
If you want to undo an earlier change permanently, use Revert to this revision instead.
-- from TSVN help doc
If you Update your working copy to an earlier rev, this is only affect your own working copy, after you do some change, and want to commit, you will fail,TSVN will alert you to update your WC to latest revision first If you Revert to a rev, you can commit to repository.everyone will back to the rev after they do an update.
keep this into your web config file then rename the add value="yourwebformname.aspx"
<system.webServer>
<defaultDocument>
<files>
<add value="insertion.aspx" />
</files>
</defaultDocument>
<directoryBrowse enabled="false" />
</system.webServer>
else
<system.webServer>
<directoryBrowse enabled="true" />
</system.webServer>
There is also:
try:
del mydict[key]
except KeyError:
pass
This only does 1 lookup instead of 2. However, except
clauses are expensive, so if you end up hitting the except clause frequently, this will probably be less efficient than what you already have.
In some cases it's very useful to change font-size with relative font sizing units. For example:
.btn {font-size: 3vw;}
Demo: http://www.bootply.com/7VN5OCVhhF
1vw is 1% of the viewport width. More info: http://www.sitepoint.com/new-css3-relative-font-size/
WAMP uses different php.ini files in the CLI and for Apache. when you enable php_openssl through the WAMP UI, you enable it for Apache, not for the CLI. You need to modify C:\wamp\bin\php\php-5.4.3\php.ini to enable it for the CLI.
Use a document.ready()
event around your call.
$(document).ready(function () {
$('#memberModal').modal('show');
});
jsFiddle updated - http://jsfiddle.net/uvnggL8w/1/
RFC3966 defines the IETF standard URI for telephone numbers, that is the 'tel:' URI. That's the standard. There's no similar standard that specifies 'callto:', that's a particular convention for Skype on platforms where is allows registering a URI handler to support it.
Kotlin code is a lot simpler:
if(isVisable) {
clearButton.visibility = View.INVISIBLE
}
else {
clearButton.visibility = View.VISIBLE
}
I found a shortcut: File - Project Structure - Tab:Dependencies Click on the green + sign, select support-v4 (or any other you need), click OK.
now go to your gradle file and see that is been added
Using the ternary :?
operator [spec].
var hasName = (name === 'true') ? 'Y' :'N';
The ternary operator lets us write shorthand if..else
statements exactly like you want.
It looks like:
(name === 'true')
- our condition
?
- the ternary operator itself
'Y'
- the result if the condition evaluates to true
'N'
- the result if the condition evaluates to false
So in short (question)?(result if true):(result is false)
, as you can see - it returns the value of the expression so we can simply assign it to a variable just like in the example above.
=IF(COUNTIF(A1:D1,FALSE)>0,FALSE,TRUE)
(or you can specify any other range to look in)
Try this code
HashMap<String, String> map = new HashMap<String, String>();
map.put("EmpID", EmpID);
map.put("UnChecked", "1");
This error is due to
.dx
format cannot be parsed.Solution:
That div.cell
solution didn't actually work on my IPython, however luckily someone suggested a working solution for new IPythons:
Create a file ~/.ipython/profile_default/static/custom/custom.css
(iPython) or ~/.jupyter/custom/custom.css
(Jupyter) with content
.container { width:100% !important; }
Then restart iPython/Jupyter notebooks. Note that this will affect all notebooks.
@echo off
(echo this is in the first line) > xy.txt
(echo this is in the second line) >> xy.txt
exit
The two >>
means that the second line will be appended to the file (i.e. second line will start after the last line of xy.txt).
this is how the xy.txt
looks like:
this is in the first line
this is in the second line
You can try following code:
foreach ($arry as $key => $value)
{
echo $key;
foreach ($value as $val)
{
echo $val;
}
}
You can use an inflater with TableRow:
for (int i = 0; i < months; i++) {
View view = getLayoutInflater ().inflate (R.layout.list_month_data, null, false);
TextView textView = view.findViewById (R.id.title);
textView.setText ("Text");
tableLayout.addView (view);
}
Layout:
<TableRow
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:layout_centerInParent="true"
android:gravity="center_horizontal"
android:paddingTop="15dp"
android:paddingRight="15dp"
android:paddingLeft="15dp"
android:paddingBottom="10dp"
>
<TextView
android:id="@+id/title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="18sp"
android:gravity="center"
/>
</TableRow>
Also, in the above case there should be only one
implicit function whose type is double => Int
. Otherwise, the compiler gets confused and won't compile properly.
//this won't compile
implicit def doubleToInt(d: Double) = d.toInt
implicit def doubleToIntSecond(d: Double) = d.toInt
val x: Int = 42.0
Doing it in one bulk read:
import re
textfile = open(filename, 'r')
filetext = textfile.read()
textfile.close()
matches = re.findall("(<(\d{4,5})>)?", filetext)
Line by line:
import re
textfile = open(filename, 'r')
matches = []
reg = re.compile("(<(\d{4,5})>)?")
for line in textfile:
matches += reg.findall(line)
textfile.close()
But again, the matches that returns will not be useful for anything except counting unless you added an offset counter:
import re
textfile = open(filename, 'r')
matches = []
offset = 0
reg = re.compile("(<(\d{4,5})>)?")
for line in textfile:
matches += [(reg.findall(line),offset)]
offset += len(line)
textfile.close()
But it still just makes more sense to read the whole file in at once.
No, it's simply a typo, the "list" at the end must be capitalized. You can nest loops over the same variable just fine (although there's rarely a good reason to).
However, there are other problems with the code. For starters, you're iterating through lists, so i
and j
will be items not indices. Furthermore, you can't change a collection while iterating over it (well, you "can" in that it runs, but madness lies that way - for instance, you'll propably skip over items). And then there's the complexity problem, your code is O(n^2). Either convert the list into a set
and back into a list
(simple, but shuffles the remaining list items) or do something like this:
seen = set()
new_x = []
for x in xs:
if x in seen:
continue
seen.add(x)
new_xs.append(x)
Both solutions require the items to be hashable. If that's not possible, you'll probably have to stick with your current approach sans the mentioned problems.
You can use NGBindHTML or NGbindHtmlUnsafe this will not escape the html
content of your model.
<div ng-app ng-controller="MyCtrl">
<ul>
<li ng-repeat=" opt in opts" ng-bind-html-unsafe="opt.text">
{{ opt.text }}
</li>
</ul>
<p>{{opt}}</p>
</div>
This works, anyway you should be very careful when using unsanitized
html
content, you should really trust the source of the content.
The easiest method you can use is this:
System.IO.File.Replace(string sourceFileName, string destinationFileName, string destinationBackupFileName);
This will take care of everything you requested.
If you need only make and friends. Try installing the command-line-tools provided by Apple. (Assuming you are not doing any iOS development.)
Receive POST and GET request in nodejs :
1).Server
var http = require('http');
var server = http.createServer ( function(request,response){
response.writeHead(200,{"Content-Type":"text\plain"});
if(request.method == "GET")
{
response.end("received GET request.")
}
else if(request.method == "POST")
{
response.end("received POST request.");
}
else
{
response.end("Undefined request .");
}
});
server.listen(8000);
console.log("Server running on port 8000");
2). Client :
var http = require('http');
var option = {
hostname : "localhost" ,
port : 8000 ,
method : "POST",
path : "/"
}
var request = http.request(option , function(resp){
resp.on("data",function(chunck){
console.log(chunck.toString());
})
})
request.end();
Add your <script>
to the bottom of your <body>
, or add an event listener for DOMContentLoaded
following this StackOverflow question.
If that script executes in the <head>
section of the code, document.getElementsByClassName(...)
will return an empty array because the DOM is not loaded yet.
You're getting the Type Error
because you're referencing search_span[0]
, but search_span[0]
is undefined
.
This works when you execute it in Dev Tools because the DOM is already loaded.
You can try this
markers[markers.length-1].setMap(null);
Hope it works.
Don't type python test.py
from inside the Python interpreter. Type it at the command prompt, like so:
Change the Encoding of the stream writer. It's a property.
http://msdn.microsoft.com/en-us/library/system.io.streamwriter.encoding.aspx
So:
sw.Encoding = Encoding.GetEncoding(28591);
Prior to writing to the stream.
So after looking (and using) of the other answers, seems they all handling ColorDrawable
and PaintDrawable
badly. (Especially on lollipop) seemed that Shader
s were tweaked so solid blocks of colors were not handled correctly.
I am using the following code now:
public static Bitmap drawableToBitmap(Drawable drawable) {
if (drawable instanceof BitmapDrawable) {
return ((BitmapDrawable) drawable).getBitmap();
}
// We ask for the bounds if they have been set as they would be most
// correct, then we check we are > 0
final int width = !drawable.getBounds().isEmpty() ?
drawable.getBounds().width() : drawable.getIntrinsicWidth();
final int height = !drawable.getBounds().isEmpty() ?
drawable.getBounds().height() : drawable.getIntrinsicHeight();
// Now we check we are > 0
final Bitmap bitmap = Bitmap.createBitmap(width <= 0 ? 1 : width, height <= 0 ? 1 : height,
Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(bitmap);
drawable.setBounds(0, 0, canvas.getWidth(), canvas.getHeight());
drawable.draw(canvas);
return bitmap;
}
Unlike the others, if you call setBounds
on the Drawable
before asking to turn it into a bitmap, it will draw the bitmap at the correct size!
Note that each line executed by a make file is run in its own shell anyway. If you change directory, it won't affect subsequent lines. So you probably have little use for pushd and popd, your problem is more the opposite, that of getting the directory to stay changed for as long as you need it!
In case you do not want to use Asset Catalog, you can add an iOS 7 icon for an old app by creating a 120x120 .png image. Name it Icon-120.png
and drag in to the project.
Under TARGET > Your App > Info > Icon files, add one more entry in the Target Properties:
I tested on Xcode 5 and an app was submitted without the missing retina icon warning.
You can try it, use this method to make it easy
/**
* array insert element on position
*
* @link https://vector.cool
*
* @since 1.01.38
*
* @param array $original
* @param mixed $inserted
* @param int $position
* @return array
*/
function array_insert(&$original, $inserted, int $position): array
{
array_splice($original, $position, 0, array($inserted));
return $original;
}
$columns = [
['name' => '????', 'column' => 'item_name'],
['name' => '????', 'column' => 'start_time'],
['name' => '????', 'column' => 'full_name'],
['name' => '????', 'column' => 'phone'],
['name' => '????', 'column' => 'create_time']
];
$col = ['name' => '????', 'column' => 'user_id'];
$columns = array_insert($columns, $col, 3);
print_r($columns);
Print out:
Array
(
[0] => Array
(
[name] => ????
[column] => item_name
)
[1] => Array
(
[name] => ????
[column] => start_time
)
[2] => Array
(
[name] => ????
[column] => full_name
)
[3] => Array
(
[name] => ????1
[column] => num_of_people
)
[4] => Array
(
[name] => ????
[column] => phone
)
[5] => Array
(
[name] => ????
[column] => user_id
)
[6] => Array
(
[name] => ????
[column] => create_time
)
)
Both Date
and moment
will parse the input string in the local time zone of the browser by default. However Date
is sometimes inconsistent with this regard. If the string is specifically YYYY-MM-DD
, using hyphens, or if it is YYYY-MM-DD HH:mm:ss
, it will interpret it as local time. Unlike Date
, moment
will always be consistent about how it parses.
The correct way to parse an input moment as UTC in the format you provided would be like this:
moment.utc('07-18-2013', 'MM-DD-YYYY')
Refer to this documentation.
If you want to then format it differently for output, you would do this:
moment.utc('07-18-2013', 'MM-DD-YYYY').format('YYYY-MM-DD')
You do not need to call toString
explicitly.
Note that it is very important to provide the input format. Without it, a date like 01-04-2013
might get processed as either Jan 4th or Apr 1st, depending on the culture settings of the browser.
Use otool:
otool -TV your.dylib
OR
nm -g your.dylib
Two one liners - I suspect the first one is faster but second one is prettier and unlike end()
and array_pop()
, you can pass the result of a function directly to current()
without generating any notice or warning since it doesn't move the pointer or alter the array.
$var = 'http://www.vimeo.com/1234567';
// VERSION 1 - one liner simmilar to DisgruntledGoat's answer above
echo substr($a,(strrpos($var,'/') !== false ? strrpos($var,'/') + 1 : 0));
// VERSION 2 - explode, reverse the array, get the first index.
echo current(array_reverse(explode('/',$var)));
Change const
to static readonly
and initialise it like this
static readonly MyStruct[] MyArray = new[] {
new MyStruct { label = "a", id = 1 },
new MyStruct { label = "b", id = 5 },
new MyStruct { label = "q", id = 29 }
};
Array notation and pointer arithmetic can be used interchangeably in C/C++ (this is not true for ALL the cases but by the time you get there, you will find the cases yourself). So although str
is a pointer, you can use it as if it were an array like so:
char char_E = str[1];
char char_L1 = str[2];
char char_O = str[4];
...and so on. What you could also do is "add" 1 to the value of the pointer to a character str
which will then point to the second character in the string. Then you can simply do:
str = str + 1; // makes it point to 'E' now
char myChar = *str;
I hope this helps.
image
has a shape of (64,64,3)
.
Your input placeholder _x
have a shape of (?, 64,64,3)
.
The problem is that you're feeding the placeholder with a value of a different shape.
You have to feed it with a value of (1, 64, 64, 3)
= a batch of 1 image.
Just reshape your image
value to a batch with size one.
image = array(img).reshape(1, 64,64,3)
P.S: the fact that the input placeholder accepts a batch of images, means that you can run predicions for a batch of images in parallel.
You can try to read more than 1 image (N images) and than build a batch of N image, using a tensor with shape (N, 64,64,3)
When you reference Range like that it's called an unqualified reference because you don't specifically say which sheet the range is on. Unqualified references are handled by the "_Global" object that determines which object you're referring to and that depends on where your code is.
If you're in a standard module, unqualified Range will refer to Activesheet. If you're in a sheet's class module, unqualified Range will refer to that sheet.
inputTemplateContent is a variable that contains a reference to a range, probably a named range. If you look at the RefersTo property of that named range, it likely points to a sheet other than the Activesheet at the time the code executes.
The best way to fix this is to avoid unqualified Range references by specifying the sheet. Like
With ThisWorkbook.Worksheets("Template")
.Range(inputTemplateHeader).Value = NO_ENTRY
.Range(inputTemplateContent).Value = NO_ENTRY
End With
Adjust the workbook and worksheet references to fit your particular situation.
$myarray = array(
'test1' => 'foo',
'test2' => 'bar',
'test3' => 'baz',
'test4' => 'waldo'
);
$myarray2 = array(
'foo',
'bar',
'baz',
'waldo'
);
// Get the last array_key
$last = array_pop(array_keys($myarray));
foreach($myarray as $key => $value) {
if($key != $last) {
echo "$key -> $value\n";
}
}
// Get the last array_key
$last = array_pop(array_keys($myarray2));
foreach($myarray2 as $key => $value) {
if($key != $last) {
echo "$key -> $value\n";
}
}
Since array_pop
works on the temporary array created by array_keys
it doesn't modify the original array at all.
$ php test.php
test1 -> foo
test2 -> bar
test3 -> baz
0 -> foo
1 -> bar
2 -> baz
I recently ran into this as well and this was a helpful post. I took the above Topera a step further and this works for me in both chrome and firefox:
var temp = new Date( Date("2010-08-17 12:09:36") );
alert(temp);
the internal call to Date()
returns a string that new Date()
can parse.
You can use ReactDOMServer to render your component to HTML and then use this on jsPDF.
First do the imports:
import React from "react";
import ReactDOMServer from "react-dom/server";
import jsPDF from 'jspdf';
then:
var doc = new jsPDF();
doc.fromHTML(ReactDOMServer.renderToStaticMarkup(this.render()));
doc.save("myDocument.pdf");
Prefer to use:
renderToStaticMarkup
instead of:
renderToString
As the former include HTML code that react relies on.
Assuming your "states" collection is like:
{"name" : "Spain", "cities" : [ { "name" : "Madrid" }, { "name" : null } ] }
{"name" : "France" }
The query to find states with null cities would be:
db.states.find({"cities.name" : {"$eq" : null, "$exists" : true}});
It is a common mistake to query for nulls as:
db.states.find({"cities.name" : null});
because this query will return all documents lacking the key (in our example it will return Spain and France). So, unless you are sure the key is always present you must check that the key exists as in the first query.
You just said javascript in your tags, so @Wampie Driessen post could helps you.
I want also to contribute, so you can use the following when using jQuery if you need it.
//Firefox
$('#elem').bind('DOMMouseScroll', function(e){
if(e.detail > 0) {
//scroll down
console.log('Down');
}else {
//scroll up
console.log('Up');
}
//prevent page fom scrolling
return false;
});
//IE, Opera, Safari
$('#elem').bind('mousewheel', function(e){
if(e.wheelDelta< 0) {
//scroll down
console.log('Down');
}else {
//scroll up
console.log('Up');
}
//prevent page fom scrolling
return false;
});
Another example:
$(function(){
var _top = $(window).scrollTop();
var _direction;
$(window).scroll(function(){
var _cur_top = $(window).scrollTop();
if(_top < _cur_top)
{
_direction = 'down';
}
else
{
_direction = 'up';
}
_top = _cur_top;
console.log(_direction);
});
});?
Is your employer aware that he can "steal" back any ideas that other people get from your code? I mean, if they can read your work, so can you theirs. Maybe looking at how you can benefit from the situation would yield a better return of your investment than fearing how much you could lose.
[EDIT] Answer to Nick's comment:
Nothing gained and nothing lost. The customer has what he wants (and paid for it since he did the change himself). Since he doesn't release the change, it's as if it didn't happen for everyone else.
Now if the customer sells the software, they have to change the copyright notice (which is illegal, so you can sue and will win -> simple case).
If they don't change the copyright notice, the 2nd level customers will notice that the software comes from you original and wonder what is going on. Chances are that they will contact you and so you will learn about the reselling of your work.
Again we have two cases: The original customer sold only a few copies. That means they didn't make much money anyway, so why bother. Or they sold in volume. That means better chances for you to learn about what they do and do something about it.
But in the end, most companies try to comply to the law (once their reputation is ruined, it's much harder to do business). So they will not steal your work but work with you to improve it. So if you include the source (with a license that protects you from simple reselling), chances are that they will simply push back changes they made since that will make sure the change is in the next version and they don't have to maintain it. That's win-win: You get changes and they can make the change themselves if they really, desperately need it even if you're unwilling to include it in the official release.
As commented by David Thomas, descendants of those child elements will (likely) inherit most of the styles assigned to those child elements.
You need to wrap your .myTestClass
inside an element and apply the styles to descendants by adding .wrapper *
descendant selector. Then, add .myTestClass > *
child selector to apply the style to the elements children, not its grand children. For example like this:
JSFiddle - DEMO
.wrapper * {_x000D_
color: blue;_x000D_
margin: 0 100px; /* Only for demo */_x000D_
}_x000D_
.myTestClass > * {_x000D_
color:red;_x000D_
margin: 0 20px;_x000D_
}
_x000D_
<div class="wrapper">_x000D_
<div class="myTestClass">Text 0_x000D_
<div>Text 1</div>_x000D_
<span>Text 1</span>_x000D_
<div>Text 1_x000D_
<p>Text 2</p>_x000D_
<div>Text 2</div>_x000D_
</div>_x000D_
<p>Text 1</p>_x000D_
</div>_x000D_
<div>Text 0</div>_x000D_
</div>
_x000D_
class Test extends Thread
{
public void run(){
try{
Thread.sleep(10000);
}catch(InterruptedException e){
System.out.println("test1");
throw new RuntimeException("Thread interrupted..."+e);
}
}
public static void main(String args[]){
Test t1=new Test1();
t1.start();
try{
t1.interrupt();
}catch(Exception e){
System.out.println("test2");
System.out.println("Exception handled "+e);
}
}
}
Its output doesn't contain test2 , so its not handling runtime exception. @jon skeet, @Jan Zyka
According to the specifications of the World Wide Web Consortium (w3C), there are 5 characters that must not appear in their literal form in an XML document, except when used as markup delimiters or within a comment, a processing instruction, or a CDATA section. In all the other cases, these characters must be replaced either using the corresponding entity or the numeric reference according to the following table:
Original CharacterXML entity replacementXML numeric replacement
< < <
> > >
" " "
& & &
' ' '
Notice that the aforementioned entities can be used also in HTML, with the exception of ', that was introduced with XHTML 1.0 and is not declared in HTML 4. For this reason, and to ensure retro-compatibility, the XHTML specification recommends the use of ' instead.
Reduce makes this fairly easy:
merged.data.frame = Reduce(function(...) merge(..., all=T), list.of.data.frames)
Here's a fully example using some mock data:
set.seed(1)
list.of.data.frames = list(data.frame(x=1:10, a=1:10), data.frame(x=5:14, b=11:20), data.frame(x=sample(20, 10), y=runif(10)))
merged.data.frame = Reduce(function(...) merge(..., all=T), list.of.data.frames)
tail(merged.data.frame)
# x a b y
#12 12 NA 18 NA
#13 13 NA 19 NA
#14 14 NA 20 0.4976992
#15 15 NA NA 0.7176185
#16 16 NA NA 0.3841037
#17 19 NA NA 0.3800352
And here's an example using these data to replicate my.list
:
merged.data.frame = Reduce(function(...) merge(..., by=match.by, all=T), my.list)
merged.data.frame[, 1:12]
# matchname party st district chamber senate1993 name.x v2.x v3.x v4.x senate1994 name.y
#1 ALGIERE 200 RI 026 S NA <NA> NA NA NA NA <NA>
#2 ALVES 100 RI 019 S NA <NA> NA NA NA NA <NA>
#3 BADEAU 100 RI 032 S NA <NA> NA NA NA NA <NA>
Note: It looks like this is arguably a bug in merge
. The problem is there is no check that adding the suffixes (to handle overlapping non-matching names) actually makes them unique. At a certain point it uses [.data.frame
which does make.unique
the names, causing the rbind
to fail.
# first merge will end up with 'name.x' & 'name.y'
merge(my.list[[1]], my.list[[2]], by=match.by, all=T)
# [1] matchname party st district chamber senate1993 name.x
# [8] votes.year.x senate1994 name.y votes.year.y
#<0 rows> (or 0-length row.names)
# as there is no clash, we retain 'name.x' & 'name.y' and get 'name' again
merge(merge(my.list[[1]], my.list[[2]], by=match.by, all=T), my.list[[3]], by=match.by, all=T)
# [1] matchname party st district chamber senate1993 name.x
# [8] votes.year.x senate1994 name.y votes.year.y senate1995 name votes.year
#<0 rows> (or 0-length row.names)
# the next merge will fail as 'name' will get renamed to a pre-existing field.
Easiest way to fix is to not leave the field renaming for duplicates fields (of which there are many here) up to merge
. Eg:
my.list2 = Map(function(x, i) setNames(x, ifelse(names(x) %in% match.by,
names(x), sprintf('%s.%d', names(x), i))), my.list, seq_along(my.list))
The merge
/Reduce
will then work fine.
Let's look at static variables and static methods first.
Class.variable
Class.methodName()
this
or super
keywords in anyway.Java also has "static nested classes". A static nested class is just one which doesn't implicitly have a reference to an instance of the outer class.
Static nested classes can have instance methods and static methods.
There's no such thing as a top-level static class in Java.
main method is
static
since it must be be accessible for an application to run before any instantiation takes place.
final
keyword is used in several different contexts to define an entity which cannot later be changed.A final
class cannot be subclassed. This is done for reasons of security and efficiency. Accordingly, many of the Java standard library classes are final
, for example java.lang.System
and java.lang.String
. All methods in a final
class are implicitly final
.
A final
method can't be overridden by subclasses. This is used to prevent unexpected behavior from a subclass altering a method that may be crucial to the function or consistency of the class.
A final
variable can only be initialized once, either via an initializer or an assignment statement. It does not need to be initialized at the point of declaration: this is called a blank final
variable. A blank final instance variable of a class must be definitely assigned at the end of every constructor of the class in which it is declared; similarly, a blank final static variable must be definitely assigned in a static initializer of the class in which it is declared; otherwise, a compile-time error occurs in both cases.
When an anonymous inner class is defined within the body of a method, all variables declared final
in the scope of that method are accessible from within the inner class. Once it has been assigned, the value of the final variable cannot change.
You may also find this command useful:
mkdir dirname && cd $_
where dirname is the name of the directory you want to create
If you mark your entity with @DynamicInsert
e.g.
@Entity
@DynamicInsert
@Table(name = "TABLE_NAME")
public class ClassName implements Serializable {
Hibernate will generate SQL without null
values. Then the database will insert its own default value. This does have performance implications See [Dynamic Insert][1].
You may use simplehtmldom. Most of the jQuery selectors are supported in simplehtmldom. An example is given below
// Create DOM from URL or file
$html = file_get_html('http://www.google.com/');
// Find all images
foreach($html->find('img') as $element)
echo $element->src . '<br>';
// Find all links
foreach($html->find('a') as $element)
echo $element->href . '<br>';
Try this that works for me:
$('#bar').mousedown();
Actually we get this error also when we create canvas in javascript as below.
document.createElement('canvas');
Here point to be noted we have to provide argument name correctly as 'canvas' not anything else.
Thanks
With Spring you can also just write the following using AnnotationUtils class. i.e.:
Class<?> clazz = AnnotationUtils.findAnnotationDeclaringClass(Target.class, null);
For more details and all different methods check official docs: https://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/core/annotation/AnnotationUtils.html
$str = '<img border="0" src=\'/images/image.jpg\' alt="Image" width="100" height="100"/>';
preg_match('/(src=["\'](.*?)["\'])/', $str, $match); //find src="X" or src='X'
$split = preg_split('/["\']/', $match[0]); // split by quotes
$src = $split[1]; // X between quotes
echo $src;
Other regexp's can be used to determine if the pulled src tag is a picture like so:
if(preg_match('/([jpg]{3}$)|([gif]{3}$)|([jpeg]{3}$)|([bmp]{3}$)|([png]{3}$)/', $src) == 1) {
//its an image
}
Emmanuel,
I think the extra info should be put before starting the activity otherwise the data won't be available yet if you're accessing it in the onCreate method of NextActivity.
Intent myIntent = new Intent(CurrentActivity.this, NextActivity.class);
myIntent.putExtra("key", value);
CurrentActivity.this.startActivity(myIntent);
Probably not the dictionary definition, but a callback usually refers to a function, which is external to a particular object, being stored and then called upon a specific event.
An example might be when a UI button is created, it stores a reference to a function which performs an action. The action is handled by a different part of the code but when the button is pressed, the callback is called and this invokes the action to perform.
C#, rather than use the term 'callback' uses 'events' and 'delegates' and you can find out more about delegates here.
For HTTP things, the current choice should be: Requests- HTTP for Humans
You can trigger a file input element by sending it a Javascript click event, e.g.
<input type="file" ... id="file-input">
$("#file-input").click();
You could put this in a click event handler for the image, for instance, then hide the file input with CSS. It'll still work even if it's invisible.
Once you've got that part working, you can set a change
event handler on the input element to see when the user puts a file into it. This event handler can create a temporary "blob" URL for the image by using window.URL.createObjectURL
, e.g.:
var file = document.getElementById("file-input").files[0];
var blob_url = window.URL.createObjectURL(file);
That URL can be set as the src
for an image on the page. (It only works on that page, though. Don't try to save it anywhere.)
Note that not all browsers currently support camera capture. (In fact, most desktop browsers don't.) Make sure your interface still makes sense if the user gets asked to pick a file.
It is very straight forward
HTML
<input type="text" placeholder="some text" />
<input type="button" value="button" class="button"/>
<button class="button">Another button</button>
jQuery
$(document).ready(function(){
$('.button').css( 'cursor', 'pointer' );
// for old IE browsers
$('.button').css( 'cursor', 'hand' );
});
One more solution able to control the how many decimal digits to print out based on needs (if you don't want to print redundant zero(s))
For example, if you have a vector as elements
and would like to get sum
of it
elements <- c(-1e-05, -2e-04, -3e-03, -4e-02, -5e-01, -6e+00, -7e+01, -8e+02)
sum(elements)
## -876.5432
Apparently, the last digital as 1
been truncated, the ideal result should be -876.54321
, but if set as fixed printing decimal option, e.g sprintf("%.10f", sum(elements))
, redundant zero(s) generate as -876.5432100000
Following the tutorial here: printing decimal numbers, if able to identify how many decimal digits in the certain numeric number, like here in -876.54321
, there are 5 decimal digits need to print, then we can set up a parameter for format
function as below:
decimal_length <- 5
formatC(sum(elements), format = "f", digits = decimal_length)
## -876.54321
We can change the decimal_length
based on each time query, so it can satisfy different decimal printing requirement.
Use the border-spacing
property on the table
element to set the spacing between cells.
Make sure border-collapse
is set to separate
(or there will be a single border between each cell instead of a separate border around each one that can have spacing between them).
Integer.parseInt(str) throws NumberFormatException
if the string does not contain a parsable integer. You can hadle the same as below.
int a;
String str = "N/A";
try {
a = Integer.parseInt(str);
} catch (NumberFormatException nfe) {
// Handle the condition when str is not a number.
}
I think your problem is that the match method is returning an array. The 0th item in the array is the original string, the 1st thru nth items correspond to the 1st through nth matched parenthesised items. Your "alert()" call is showing the entire array.
It may also be worth mentioning, on OSX using Vim, you can select text with the mouse, Cmd-C to copy to OSX system clipboard, and the copied text will be available in the clipboard outside of Vim.
In other words, OSX treats it like it were a regular window, and this is where the much-maligned Apple "Command" button comes in handy.
B-30
Here is a version that is copy-pastable directly into code:
import java.io.StringWriter;
import java.io.PrintWriter;
//Two lines of code to get the exception into a StringWriter
StringWriter sw = new StringWriter();
new Throwable().printStackTrace(new PrintWriter(sw));
//And to actually print it
logger.info("Current stack trace is:\n" + sw.toString());
Or, in a catch block
} catch (Throwable t) {
StringWriter sw = new StringWriter();
t.printStackTrace(new PrintWriter(sw));
logger.info("Current stack trace is:\n" + sw.toString());
}
I wrote some simple thing:
When you initialize icheck
as:
$('input').iCheck({
checkboxClass: 'icheckbox_square-blue',
radioClass: 'iradio_square-blue',
increaseArea: '20%' // optional
});
Add this code under it:
$('input').on('ifChecked', function (event){
$(this).closest("input").attr('checked', true);
});
$('input').on('ifUnchecked', function (event) {
$(this).closest("input").attr('checked', false);
});
After this you can easily find your original checkbox's state.
I wrote this code for using icheck
in gridView
and accessed its state from server side by C#.
Simply find your checkBox from its id.
Both of these are primary from the old printing days.
Carriage return is from the days of the teletype printers/old typewriters, where literally the carriage would return to the next line, and push the paper up. This is what we now call \r
.
Line feed LF
signals the end of the line, it signals that the line has ended - but doesn't move the cursor to the next line. In other words, it doesn't "return" the cursor/printer head to the next line.
For more sundry details, the mighty wikipedia to the rescue.
First, you need to create selfsigned.key and selfsigned.crt files. Go to Create a Self-Signed SSL Certificate Or do following steps.
Go to the terminal and run the following command.
sudo openssl req -x509 -nodes -days 365 -newkey rsa:2048 -keyout ./selfsigned.key -out selfsigned.crt
After creation adds key & cert file in your code, and pass the options to the server.
const express = require('express');
const https = require('https');
const fs = require('fs');
const port = 3000;
var key = fs.readFileSync(__dirname + '/../certs/selfsigned.key');
var cert = fs.readFileSync(__dirname + '/../certs/selfsigned.crt');
var options = {
key: key,
cert: cert
};
app = express()
app.get('/', (req, res) => {
res.send('Now using https..');
});
var server = https.createServer(options, app);
server.listen(port, () => {
console.log("server starting on port : " + port)
});
More information https://github.com/sagardere/set-up-SSL-in-nodejs
Though this doesnt answer to the shortening problem, but this helped me to organize the messages, I created a structure for error messages like below
struct Constants {
// Error Messages
struct ErrorMessages {
static let unKnownError = NSLocalizedString("Unknown Error", comment: "Unknown Error Occured")
static let downloadError = NSLocalizedString("Error in Download", comment: "Error in Download")
}
}
let error = Constants.ErrorMessages.unKnownError
This way you can organize the messages and make genstrings work.
And this is the genstrings command used
find ./ -name \*.swift -print0 | xargs -0 genstrings -o .en.lproj
If you're using .NET 4.5 and want to use async then you can use HttpClient
in System.Net.Http
:
using (var httpClient = new HttpClient())
{
var json = await httpClient.GetStringAsync("url");
// Now parse with JSON.Net
}
After wading through all the other answers, to keep the Java 7 Date type but be more precise/standard with the Java 8 diff approach,
public static long daysBetweenDates(Date d1, Date d2) {
Instant instant1 = d1.toInstant();
Instant instant2 = d2.toInstant();
long diff = ChronoUnit.DAYS.between(instant1, instant2);
return diff;
}
What worked for me on Windows was (I had cloned code from a repo 1st):
eval $(ssh-agent)
ssh-add
git pull
at which time it asked me one last time for my passphrase
Credits: the solution was taken from https://unix.stackexchange.com/questions/12195/how-to-avoid-being-asked-passphrase-each-time-i-push-to-bitbucket
UPDATE TABLE <tablename>
SET <COLUMN=VALUE>
WHERE <CONDITION>
Example:
UPDATE TABLE teacher SET teacher_name='NSP' WHERE teacher_id='1'
It also occurs when you try to load()
an rds object instead of using
object <- readRDS("object.rds")
The simplest technique:
If your form action attribute is omitted, you can send a form to the same HTML file without actually using a GET HTTP access, just by using onClick on the button used for submitting the form. Then the form fields are in the elements array document.FormName.elements . Each element in that array has a value attribute containing the string the user provided (For INPUT elements). It also has id and name attributes, containing the id and/or name provided in the form child elements.
If you just want to calculate the schema size without tablespace free space and indexes :
select
sum(bytes)/1024/1024 as size_in_mega,
segment_type
from
dba_segments
where
owner='<schema's owner>'
group by
segment_type;
For all schemas
select
sum(bytes)/1024/1024 as size_in_mega, owner
from
dba_segments
group by
owner;
Better and clean example using JS only
Reference: TheDeveloperBlog.com
Step 1 - Create your java script and place it in your HTML page.
<script type="text/javascript">
function ShowLoading(e) {
var div = document.createElement('div');
var img = document.createElement('img');
img.src = 'loading_bar.GIF';
div.innerHTML = "Loading...<br />";
div.style.cssText = 'position: fixed; top: 5%; left: 40%; z-index: 5000; width: 422px; text-align: center; background: #EDDBB0; border: 1px solid #000';
div.appendChild(img);
document.body.appendChild(div);
return true;
// These 2 lines cancel form submission, so only use if needed.
//window.event.cancelBubble = true;
//e.stopPropagation();
}
</script>
in your form call the java script function on submit event.
<form runat="server" onsubmit="ShowLoading()">
</form>
Soon after you submit the form, it will show you the loading image.
You'll want to check HTML5 Differences from HTML4: W3C Working Group Note 9 December 2014 for the complete differences. There are many new elements and element attributes. Some elements were removed and others have different semantic value than before.
There are also APIs defined, such as the use of canvas, to help build the next generation of web apps and make sure implementations are standardized.
Even if I want to return a business logic error as HTTP code there is no such acceptable HTTP error code for that errors rather than using HTTP 200 because it will misrepresent the actual error.
So, HTTP 200 will be good for business logic errors. But all errors which are covered by HTTP error codes should use them.
Basically HTTP 200 means what server correctly processes user request (in case of there is no seats on the plane it is no matter because user request was correctly processed, it can even return just a number of seats available on the plane, so there will be no business logic errors at all or that business logic can be on client side. Business logic error is an abstract meaning, but HTTP error is more definite).
For Android Studio 1.3 : (Method 1)
Step 1 : Open gradle.properties file in your Android Studio project.
Step 2 : Add this line at the end of the file
org.gradle.jvmargs=-XX\:MaxHeapSize\=256m -Xmx256m
Above methods seems to work but if in case it won't then do this (Method 2)
Step 1 : Start Android studio and close any open project (File > Close Project).
Step 2 : On Welcome window, Go to Configure > Settings.
Step 3 : Go to Build, Execution, Deployment > Compiler
Step 4 : Change Build process heap size (Mbytes) to 1024 and Additional build process to VM Options to -Xmx512m.
Step 5 : Close or Restart Android Studio.
One way that I've found really useful in situations like this is to go old-school and use the Jet OLEDB provider, together with a schema.ini file to read large tab-delimited files in using ADO.Net. Obviously, this method is really only useful if you know the format of the file to be imported.
public void ImportCsvFile(string filename)
{
FileInfo file = new FileInfo(filename);
using (OleDbConnection con =
new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=\"" +
file.DirectoryName + "\";
Extended Properties='text;HDR=Yes;FMT=TabDelimited';"))
{
using (OleDbCommand cmd = new OleDbCommand(string.Format
("SELECT * FROM [{0}]", file.Name), con))
{
con.Open();
// Using a DataReader to process the data
using (OleDbDataReader reader = cmd.ExecuteReader())
{
while (reader.Read())
{
// Process the current reader entry...
}
}
// Using a DataTable to process the data
using (OleDbDataAdapter adp = new OleDbDataAdapter(cmd))
{
DataTable tbl = new DataTable("MyTable");
adp.Fill(tbl);
foreach (DataRow row in tbl.Rows)
{
// Process the current row...
}
}
}
}
}
Once you have the data in a nice format like a datatable, filtering out the data you need becomes pretty trivial.
If there's a chance that you will reuse this code, then I would probably make the effort to go with an object-oriented perspective. Using the global namespace can be dangerous -- you run the risk of hard to find bugs due to variable names that get reused. Typically I start by using an object-oriented approach for anything more than a simple callback so that I don't have to do the re-write thing. Any time that you have a group of related functions in javascript, I think, it's a candidate for an object-oriented approach.
There are in fact 3 questions in your question :
What JB King has described is correct, but it is a particular, simple version, where in fact he mapped front, middle and bacn to an MVC layer. He mapped M to the back, V to the front, and C to the middle.
For many people, it is just fine, since they come from the ugly world where even MVC was not applied, and you could have direct DB calls in a view.
However in real, complex web applications, you indeed have two or three different layers, called front, middle and back. Each of them may have an associated database and a controller.
The front-end will be visible by the end-user. It should not be confused with the front-office, which is the UI for parameters and administration of the front. The front-end will usually be some kind of CMS or e-commerce Platform (Magento, etc.)
The middle-end is not compulsory and is where the business logics is. It will be based on a PIM, a MDM tool, or some kind of custom database where you enrich your produts or your articles (for CMS). It'll also be the place where you code business functions that need to be shared between differents frontends (for instance between the PC frontend and the API-based mobile application). Sometimes, an ESB or tool like ActiveMQ will be your middle-end
The back-end will be a 3rd layer, surrouding your source database or your ERP. It may be jsut the API wrting to and reading from your ERP. It may be your supplier DB, if you are doing e-commerce. In fact, it really depends on web projects, but it is always a central repository. It'll be accessed either through a DB call, through an API, or an Hibernate layer, or a full-featured back-end application
This description means that answering the other 2 questions is not possible in this thread, as bottlenecks really depend on what your 3 ends contain : what JB King wrote remains true for simple MVC architectures
at the time the question was asked (5 years ago), maybe the MVC pattern was not yet so widely adopted. Now, there is absolutely no reason why the MVC pattern would not be followed and a view would be tied to DB calls. If you read the question "Are there cases where they MUST overlap, and frontend/backend cannot be separated?" in a broader sense, with 3 different components, then there times when the 3 layers architecture is useless of course. Think of a simple personal blog, you'll not need to pull external data or poll RabbitMQ queues.
For symfony 2.6 and above we can use
{{ app.user.getFirstname() }}
as app.security global variable for Twig template has been deprecated and will be removed from 3.0
more info:
http://symfony.com/blog/new-in-symfony-2-6-security-component-improvements
and see the global variables in
http://symfony.com/doc/current/reference/twig_reference.html
If you are using a more modern version of Rails and it uses Puma as the web server, you can run the following command to find the stuck Puma process:
ps aux | grep puma
It will result in output similar to this:
85923 100.0 0.8 2682420 131324 s004 R+ 2:54pm 3:27.92 puma 3.12.0 (tcp://0.0.0.0:3010) [my-app]
92463 0.0 0.0 2458404 1976 s008 S+ 3:09pm 0:00.00 grep puma
You want the process that is not referring to grep
. In this case, the process ID is 85923.
I can then run the following command to kill that process:
kill -9 85923
You want to read raw lines to avoid problems with backslashes in the input (use -r
):
while read -r line; do
printf "<%s>\n" "$line"
done < file.txt
This will keep whitespace within the line, but removes leading and trailing whitespace. To keep those as well, set the IFS empty, as in
while IFS= read -r line; do
printf "%s\n" "$line"
done < file.txt
This now is an equivalent of cat < file.txt
as long as file.txt
ends with a newline.
Note that you must double quote "$line"
in order to keep word splitting from splitting the line into separate words--thus losing multiple whitespace sequences.
Thing
is an inner class with an automatic connection to an instance of Hello
. You get a compile error because there is no instance of Hello
for it to attach to. You can fix it most easily by changing it to a static nested class which has no connection:
static class Thing
Another option would be to use Angular's built-in pub-sub architecture in order to notify your directive to focus. Similar to the other approaches, but it's then not directly tied to a property, and is instead listening in on it's scope for a particular key.
Directive:
angular.module("app").directive("focusOn", function($timeout) {
return {
restrict: "A",
link: function(scope, element, attrs) {
scope.$on(attrs.focusOn, function(e) {
$timeout((function() {
element[0].focus();
}), 10);
});
}
};
});
HTML:
<input type="text" name="text_input" ng-model="ctrl.model" focus-on="focusTextInput" />
Controller:
//Assume this is within your controller
//And you've hit the point where you want to focus the input:
$scope.$broadcast("focusTextInput");
Regarding seek()
there's not too much to worry about.
First of all, it is useful when operating over an open file.
It's important to note that its syntax is as follows:
fp.seek(offset, from_what)
where fp
is the file pointer you're working with; offset
means how many positions you will move; from_what
defines your point of reference:
if omitted, from_what
defaults to 0.
Never forget that when managing files, there'll always be a position inside that file where you are currently working on. When just open, that position is the beginning of the file, but as you work with it, you may advance.
seek
will be useful to you when you need to walk
along that open file, just as a path you are traveling into.
No, it sets all members/elements that haven't been explicitly set to their default-initialisation value, which is zero for numeric types.
We can merge/join all data inside only one collection with a easy function in few lines using the mongodb client console, and now we could be able of perform the desired query. Below a complete example,
.- Authors:
db.authors.insert([
{
_id: 'a1',
name: { first: 'orlando', last: 'becerra' },
age: 27
},
{
_id: 'a2',
name: { first: 'mayra', last: 'sanchez' },
age: 21
}
]);
.- Categories:
db.categories.insert([
{
_id: 'c1',
name: 'sci-fi'
},
{
_id: 'c2',
name: 'romance'
}
]);
.- Books
db.books.insert([
{
_id: 'b1',
name: 'Groovy Book',
category: 'c1',
authors: ['a1']
},
{
_id: 'b2',
name: 'Java Book',
category: 'c2',
authors: ['a1','a2']
},
]);
.- Book lending
db.lendings.insert([
{
_id: 'l1',
book: 'b1',
date: new Date('01/01/11'),
lendingBy: 'jose'
},
{
_id: 'l2',
book: 'b1',
date: new Date('02/02/12'),
lendingBy: 'maria'
}
]);
.- The magic:
db.books.find().forEach(
function (newBook) {
newBook.category = db.categories.findOne( { "_id": newBook.category } );
newBook.lendings = db.lendings.find( { "book": newBook._id } ).toArray();
newBook.authors = db.authors.find( { "_id": { $in: newBook.authors } } ).toArray();
db.booksReloaded.insert(newBook);
}
);
.- Get the new collection data:
db.booksReloaded.find().pretty()
.- Response :)
{
"_id" : "b1",
"name" : "Groovy Book",
"category" : {
"_id" : "c1",
"name" : "sci-fi"
},
"authors" : [
{
"_id" : "a1",
"name" : {
"first" : "orlando",
"last" : "becerra"
},
"age" : 27
}
],
"lendings" : [
{
"_id" : "l1",
"book" : "b1",
"date" : ISODate("2011-01-01T00:00:00Z"),
"lendingBy" : "jose"
},
{
"_id" : "l2",
"book" : "b1",
"date" : ISODate("2012-02-02T00:00:00Z"),
"lendingBy" : "maria"
}
]
}
{
"_id" : "b2",
"name" : "Java Book",
"category" : {
"_id" : "c2",
"name" : "romance"
},
"authors" : [
{
"_id" : "a1",
"name" : {
"first" : "orlando",
"last" : "becerra"
},
"age" : 27
},
{
"_id" : "a2",
"name" : {
"first" : "mayra",
"last" : "sanchez"
},
"age" : 21
}
],
"lendings" : [ ]
}
I hope this lines can help you.
I finally was able to insert a row, on the condition that it didn't already exist, using the following model:
INSERT INTO table ( column1, column2, column3 )
(
SELECT $column1, $column2, $column3
WHERE NOT EXISTS (
SELECT 1
FROM table
WHERE column1 = $column1
AND column2 = $column2
AND column3 = $column3
)
)
which I found at:
I had this issue too, after following this guide, it was simply 1 additional patch that was required to get past the
Rule "Prior Visual Studio 2010 instances requiring update." failed.
Was to locate this file, and patch my machine
VS10sp1-KB983509.msp
Simply do a file search on the installation media for SQL Server 2012, in my case it was in \redist\VisualStudioShell (whereas in the guide it's listed as being in a different location).
Then hit 're-run'.
Dim psValue As String = "1,5,12,34,123,12"
psValue = psValue.Substring(0, psValue.LastIndexOf(","))
output:
1,5,12,34,123
Note that in an attribute selector (e.g., [attr~=value]
), the tilde
Represents an element with an attribute name of attr whose value is a whitespace-separated list of words, one of which is exactly value.
https://developer.mozilla.org/en-US/docs/Web/CSS/Attribute_selectors
To put a require rule on a select list you just need an option with an empty value
<option value="">Year</option>
then just applying required on its own is enough
<script>
$(function () {
$("form").validate();
});
</script>
with form
<form>
<select name="year" id="year" class="required">
<option value="">Year</option>
<option value="1">1919</option>
<option value="2">1920</option>
<option value="3">1921</option>
<option value="4">1922</option>
</select>
<input type="submit" />
</form>
In Kotlin we can do in one line
TEXT_VIEW_ID.typeface = Typeface.defaultFromStyle(Typeface.BOLD)
Ultimately, I want to be able to echo out a signle field like so:
$row['option_value']
So why don't you? It should work.
Use replace method of string like the following way:
String x="\"abcd";
String z=x.replace("\"", "");
System.out.println(z);
Output:
abcd
my problem was to copy the whole source files contains .idea directory and my webstorm terminal commands were run on the original directory of the source
I delete the .idea directory and it worked fine
Check this answer: Set CORS header in Tomcat
Note that you need Tomcat 7.0.41 or higher.
To know where the current instance of Tomcat is located try this:
System.out.println(System.getProperty("catalina.base"));
You'll see the path in the console view.
Then look for /conf/web.xml on that folder, open it and add the lines of the above link.
This may help you.
--go-to-home
or it will continue to start in the directory specified in your HOME variableThats it.
You don't need to use regex, LIKE
is sufficient:
WHERE my_field LIKE '[a-zA-Z][a-zA-Z]%'
Assuming that by "alphabetical" you mean only latin characters, not anything classified as alphabetical in Unicode.
Note - if your collation is case sensitive, it's important to specify the range as [a-zA-Z]
. [a-z]
may exclude A
or Z
. [A-Z]
may exclude a
or z
.
Use this jQuery extension by James Padoley
I was having this problem due to the dates not being in a format Excel recognised. I manually converted them to DD/mm/yy using the find and replace tool. Excel was still not recognising the entries as dates. Turns out there was a space in the cell before the date. I deleted the spaces using find and replace and it solved the problem.
After searching a lot I find out that it is possible to create a new folder from the web interface, but it would require you to have at least one file within the folder when creating it.
When using the normal way of creating new files through the web interface, you can type in the folder into the file name to create the file within that new directory.
For example, if I would like to create the file filename.md
in a series of sub-folders, I can do this (taken from the GitHub blog):
Pull "pulls" the div towards the left of the browser and and Push "pushes" the div away from left of browser.
Like:
So basically in a 3 column layout of any web page the "Main Body" appears at the "Center" and in "Mobile" view the "Main Body" appears at the "Top" of the page. This is mostly desired by everyone with 3 column layout.
<div class="container">
<div class="row">
<div id="content" class="col-lg-4 col-lg-push-4 col-sm-12">
<h2>This is Content</h2>
<p>orem Ipsum ...</p>
</div>
<div id="sidebar-left" class="col-lg-4 col-sm-6 col-lg-pull-4">
<h2>This is Left Sidebar</h2>
<p>orem Ipsum...</p>
</div>
<div id="sidebar-right" class="col-lg-4 col-sm-6">
<h2>This is Right Sidebar</h2>
<p>orem Ipsum.... </p>
</div>
</div>
</div>
You can view it here: http://jsfiddle.net/DrGeneral/BxaNN/1/
Hope it helps
In htop
, you can simply search with
/process-name
To set https
globally instead of git://
:
git config --global url.https://github.com/.insteadOf git://github.com/
In TortoiseSVN you can configure the proxy server under Settings=> Network
Just a minor point; put the following in the header
using namespace std;
then
std::cout << std::fixed << std::setprecision(2) << d;
becomes simplified to
cout << fixed << setprecision(2) << d;
I also got this error .I was using Text inside body after changing to XML(text/xml) , got result as expected.
If your request is XML Request use XML(text/xml).
If your request is JSON Request use JSON(application/json)
You can also use a dict comprehension like:
with open("infile.txt") as f:
d = {int(k): v for line in f for (k, v) in [line.strip().split(None, 1)]}
If you are working on PC of a company that uses a proxy you must turn on your VPN
The $push operator appends a specified value to an array.
{ $push: { <field1>: <value1>, ... } }
$push adds the array field with the value as its element.
Above answer fulfils all the requirements, but I got it working by doing the following
var objFriends = { fname:"fname",lname:"lname",surname:"surname" };
Friend.findOneAndUpdate(
{ _id: req.body.id },
{ $push: { friends: objFriends } },
function (error, success) {
if (error) {
console.log(error);
} else {
console.log(success);
}
});
)
Use this:
<asp:CustomValidator runat="server" id="vld" ValidateEmptyText="true"/>
To validate an empty field.
You don't need to add 2 validators !
It's a reserved keyword (like return, filter, function, break).
Also, as per Section 7.6.4 of Bruce Payette's Powershell in Action:
But what happens when you want a script to exit from within a function defined in that script? ... To make this easier, Powershell has the exit keyword.
Of course, as other have pointed out, it's not hard to do what you want by wrapping exit in a function:
PS C:\> function ex{exit}
PS C:\> new-alias ^D ex
public static WindowManager.LayoutParams setDialogLayoutParams(Activity activity, Dialog dialog)
{
try
{
Display display = activity.getWindowManager().getDefaultDisplay();
Point screenSize = new Point();
display.getSize(screenSize);
int width = screenSize.x;
WindowManager.LayoutParams layoutParams = new WindowManager.LayoutParams();
layoutParams.copyFrom(dialog.getWindow().getAttributes());
layoutParams.width = (int) (width - (width * 0.07) );
layoutParams.height = WindowManager.LayoutParams.WRAP_CONTENT;
return layoutParams;
}
catch (Exception e)
{
e.printStackTrace();
return null;
}
}
ephemeral is just another name of root volume when you launch Instance from AMI backed from Amazon EC2 instance store
So Everything will be stored on ephemeral.
if you have launched your instance from AMI backed by EBS volume then your instance does not have ephemeral.
Just add this line before opening the document (must be before):
document.Header = new HeaderFooter(new Phrase("Header Text"), false);
document.Open();
.Cells(.Rows.Count,"A").End(xlUp).row
I think the first dot in the parenthesis should not be there, I mean, you should write it in this way:
.Cells(Rows.Count,"A").End(xlUp).row
Before the Cells, you can write your worksheet name, for example:
Worksheets("sheet1").Cells(Rows.Count, 2).End(xlUp).row
The worksheet name is not necessary when you operate on the same worksheet.
If you want to create a new Thread
...you can do something like this...
Thread t = new Thread(new Runnable() { public void run() {
// your code goes here...
}});
The source of this message was unrelated to the solution in my case.
My ip address of my server changed and i didn't change the <VirtualHost>
directive in my httpd.conf of the apache server.
Once i changed it to the correct ip address the message disappeared and Wordpress is working again.