I saw in getwindowtext (user32) on pinvoke.net that you can place a MarshalAs
statement to state that the StringBuffer is equivalent to LPSTR.
<DllImport("user32.dll", SetLastError:=True, CharSet:=CharSet.Ansi)> _
Public Function GetWindowText(hwnd As IntPtr, <MarshalAs(UnManagedType.LPStr)>lpString As System.Text.StringBuilder, cch As Integer) As Integer
End Function
At the time of writing, none of the other solutions are very self-contained. They depend either on an environment variable or the position of the module in the package structure. The top answer with the ‘Django’ solution falls victim to the latter by requiring a relative import. It also has the disadvantage of having to modify a module at the top level.
This should be the correct approach for finding the directory path of the top-level package:
import sys
import os
root_name, _, _ = __name__.partition('.')
root_module = sys.modules[root_name]
root_dir = os.path.dirname(root_module.__file__)
config_path = os.path.join(root_dir, 'configuration.conf')
It works by taking the first component in the dotted string contained in __name__
and using it as a key in sys.modules
which returns the module object of the top-level package. Its __file__
attribute contains the path we want after trimming off /__init__.py
using os.path.dirname()
.
This solution is self-contained. It works anywhere in any module of the package, including in the top-level __init__.py
file.
The tikz package seems to have what you want.
\documentclass{article}
\usepackage{tikz}
\usetikzlibrary{snakes}
\begin{document}
\begin{tikzpicture}[snake=zigzag, line before snake = 5mm, line after snake = 5mm]
% draw horizontal line
\draw (0,0) -- (2,0);
\draw[snake] (2,0) -- (4,0);
\draw (4,0) -- (5,0);
\draw[snake] (5,0) -- (7,0);
% draw vertical lines
\foreach \x in {0,1,2,4,5,7}
\draw (\x cm,3pt) -- (\x cm,-3pt);
% draw nodes
\draw (0,0) node[below=3pt] {$ 0 $} node[above=3pt] {$ $};
\draw (1,0) node[below=3pt] {$ 1 $} node[above=3pt] {$ 10 $};
\draw (2,0) node[below=3pt] {$ 2 $} node[above=3pt] {$ 20 $};
\draw (3,0) node[below=3pt] {$ $} node[above=3pt] {$ $};
\draw (4,0) node[below=3pt] {$ 5 $} node[above=3pt] {$ 50 $};
\draw (5,0) node[below=3pt] {$ 6 $} node[above=3pt] {$ 60 $};
\draw (6,0) node[below=3pt] {$ $} node[above=3pt] {$ $};
\draw (7,0) node[below=3pt] {$ n $} node[above=3pt] {$ 10n $};
\end{tikzpicture}
\end{document}
I'm not too expert with tikz, but this does give a good timeline, which looks like:
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)
please chceck the type of file growth of the database, if its restricted make it unrestricted
package com.programmingfree.springshop.controller;
import java.util.List;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import com.programmingfree.springshop.dao.UserShop;
import com.programmingfree.springshop.domain.User;
@RestController
@RequestMapping("/shop/user")
public class SpringShopController {
UserShop userShop=new UserShop();
@RequestMapping(value = "/{id}", method = RequestMethod.GET,headers="Accept=application/json")
public User getUser(@PathVariable int id) {
User user=userShop.getUserById(id);
return user;
}
@RequestMapping(method = RequestMethod.GET,headers="Accept=application/json")
public List<User> getAllUsers() {
List<User> users=userShop.getAllUsers();
return users;
}
}
In the above example they going to display all user and particular id details now I want to use both id and name,
1) localhost:8093/plejson/shop/user <---this link will display all user details
2) localhost:8093/plejson/shop/user/11 <----if i use 11 in link means, it will display particular user 11 details
now I want to use both id and name
localhost:8093/plejson/shop/user/11/raju <-----------------like this it means we can use any one in this please help me out.....
It seems your question is very much older. But I just saw it. I searched(not in google) and found My Answer.
So I am writing its solution so that others may get help from it.
Here is my solution.
Unlike the other answers, you don't need to setup environments.
all you need is just to write php index.php
if index.php
is your file name.
then you will see that, the file compiled and showing it's desired output.
Using white-space: pre-line
allows you to input the text directly in the HTML with line breaks without having to use \n
If you use the innerText
property of the element via JavaScript on a non-pre element e.g. a <div>
, the \n
values will be replaced with <br>
in the DOM by default
innerText
: replaces \n
with <br>
innerHTML
, textContent
: require the use of styling white-space
It depends on how your applying the text, but there are a number of options
const node = document.createElement('div');
node.innerText = '\n Test \n One '
Make a new-directory and then use the git clone url
Try margin-top:
<header style="margin-top: -20px;">
...
Edit:
Now I found relative position probably a better choice:
<header style="position: relative; top: -20px;">
...
Here is a Python 3, POSIX solution (not Windows!) that uses mmap
to map the object into memory.
import hashlib
import mmap
def sha256sum(filename):
h = hashlib.sha256()
with open(filename, 'rb') as f:
with mmap.mmap(f.fileno(), 0, prot=mmap.PROT_READ) as mm:
h.update(mm)
return h.hexdigest()
I had the same problem, and because of the "Home" button added automatically in the toolbar, my text was not exactly entered.
I fixed it the dirty way but it works well in my case. I simply added a margin to the right of my TextView to compensate for the home button on the left. Here's my toolbar layout :
<android.support.v7.widget.Toolbar
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:elevation="1dp"
android:id="@+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
app:layout_collapseMode="pin"
android:gravity="center"
android:background="@color/mainBackgroundColor"
android:fitsSystemWindows="true" >
<com.lunabee.common.utils.LunabeeShadowTextView
android:id="@+id/title"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginRight="?attr/actionBarSize"
android:gravity="center"
style="@style/navigation.toolbar.title" />
</android.support.v7.widget.Toolbar>
I was struggling to find a solution for arbitrary length byte sequences that would work under Python 2.x. Finally I wrote this one, it's a bit hacky because it performs a string conversion, but it works.
def signedbytes(data):
"""Convert a bytearray into an integer, considering the first bit as
sign. The data must be big-endian."""
negative = data[0] & 0x80 > 0
if negative:
inverted = bytearray(~d % 256 for d in data)
return -signedbytes(inverted) - 1
encoded = str(data).encode('hex')
return int(encoded, 16)
This function has two requirements:
The input data
needs to be a bytearray
. You may call the function like this:
s = 'y\xcc\xa6\xbb'
n = signedbytes(s)
The data needs to be big-endian. In case you have a little-endian value, you should reverse it first:
n = signedbytes(s[::-1])
Of course, this should be used only if arbitrary length is needed. Otherwise, stick with more standard ways (e.g. struct
).
It's mainly so you can make start and end statements clearer when creating HTML in loops:
<table>
<? while ($record = mysql_fetch_assoc($rs)): ?>
<? if (!$record['deleted']): ?>
<tr>
<? foreach ($display_fields as $field): ?>
<td><?= $record[$field] ?></td>
<? endforeach; ?>
<td>
<select name="action" onChange="submit">
<? foreach ($actions as $action): ?>
<option value="<?= $action ?>"><?= $action ?>
<? endforeach; ?>
</td>
</tr>
<? else: ?>
<tr><td colspan="<?= array_count($display_fields) ?>"><i>record <?= $record['id'] ?> has been deleted</i></td></tr>
<? endif; ?>
<? endwhile; ?>
</table>
versus
<table>
<? while ($record = mysql_fetch_assoc($rs)) { ?>
<? if (!$record['deleted']) { ?>
<tr>
<? foreach ($display_fields as $field) { ?>
<td><?= $record[$field] ?></td>
<? } ?>
<td>
<select name="action" onChange="submit">
<? foreach ($actions as $action) { ?>
<option value="<?= $action ?>"><?= action ?>
<? } ?>
</td>
</tr>
<? } else { ?>
<tr><td colspan="<?= array_count($display_fields) ?>"><i>record <?= $record['id'] ?> has been deleted</i></td></tr>
<? } ?>
<? } ?>
</table>
Hopefully my example is sufficient to demonstrate that once you have several layers of nested loops, and the indenting is thrown off by all the PHP open/close tags and the contained HTML (and maybe you have to indent the HTML a certain way to get your page the way you want), the alternate syntax (endforeach
) form can make things easier for your brain to parse. With the normal style, the closing }
can be left on their own and make it hard to tell what they're actually closing.
In a specific case where your epoch seconds timestamp comes from SQL or is related to SQL somehow, you can obtain it like this:
long startDateLong = <...>
LocalDate theDate = new java.sql.Date(startDateLong).toLocalDate();
First you need to set your device to debugging mode. On Android 4.X that means as described in another answer in another question:
Open up your device’s “Settings”. This can be done by pressing the Menu button while on your home screen and tapping “System settings”
Now scroll to the bottom and tap “About phone” or “About tablet”.
At the “About” screen, scroll to the bottom and tap on “Build number” seven times. [Note this is no joke]
Make sure you tap seven times. If you see a “Not need, you are already a developer!” message pop up, then you know you have done it correctly.
Done! By tapping on “Build number” seven times, you have unlocked USB debugging mode on Android 4.2 and higher. You can now enable/disable it whenever you desire by going to “Settings” -> “Developer Options” -> “Debugging” ->” USB debugging”.
The next step is to connect your device to your computer via the USB cable.
The next step is to install a USB driver for it. On the official website you find a list with sources for drivers for phones from various different companies.
Eclipse now should give you the phone as a choice when you click on Run and it presents you possible device to launch.
In some case Eclpise will tell you Target Unknown which prevents you from using the device. If that's the case you might have to restart the phone. You might also have to check and recheckUSB debugging, till the phone asks you to allow your particular computer to do usb debugging.
You can check wether an arrow key is pressed by:
$(document).keydown(function(e){
if (e.keyCode > 36 && e.keyCode < 41)
alert( "arrowkey pressed" );
});
Try starting the project using the python_boilerplate template. It largely follows the best practices (e.g. those here), but is better suited in case you find yourself willing to split your project into more than one egg at some point (and believe me, with anything but the simplest projects, you will. One common situation is where you have to use a locally-modified version of someone else's library).
Where do you put the source?
PROJECT_ROOT/src/<egg_name>
.Where do you put application startup scripts?
entry_point
in one of the eggs.Where do you put the IDE project cruft?
PROJECT_ROOT/.<something>
in the root of the project, and this is fine.Where do you put the unit/acceptance tests?
PROJECT_ROOT/src/<egg_name>/tests
directory. I personally prefer to use py.test
to run them.Where do you put non-Python data such as config files?
pkg_resources
package from setuptools
, or since Python 3.7 via the importlib.resources
module from the standard library.PROJECT_ROOT/config
. For deployment there can be various options. On Windows one can use %APP_DATA%/<app-name>/config
, on Linux, /etc/<app-name>
or /opt/<app-name>/config
.PROJECT_ROOT/var
during development, and under /var
during Linux deployment.PROJECT_ROOT/src/<egg_name>/native
Documentation would typically go into PROJECT_ROOT/doc
or PROJECT_ROOT/src/<egg_name>/doc
(this depends on whether you regard some of the eggs to be a separate large projects). Some additional configuration will be in files like PROJECT_ROOT/buildout.cfg
and PROJECT_ROOT/setup.cfg
.
var date = new Date();
console.log(date.toJSON().slice(0,10).replace(new RegExp("-", 'g'),"/" ).split("/").reverse().join("/")+" "+date.toJSON().slice(11,19));
// output : 01/09/2016 18:30:00
If you're using rails you can also use in_groups_of:
foo.in_groups_of(3)
This error is caused by binary data being inserted into a buffer. To solve this problem, you should insert one statement in your code.
This statement is:
obj_FileStream.Read(Img, 0, Convert.ToInt32(obj_FileStream.Length));
Example:
FileStream obj_FileStream = new FileStream(str_ImagePath, FileMode.OpenOrCreate, FileAccess.Read);
Byte[] Img = new Byte[obj_FileStream.Length];
obj_FileStream.Read(Img, 0, Convert.ToInt32(obj_FileStream.Length));
dt_NewsFeedByRow.Rows[0][6] = Img;
You have a few choices:
typeof(IMyInterface).IsAssignableFrom(typeof(MyType))
typeof(MyType).GetInterfaces().Contains(typeof(IMyInterface))
For a generic interface, it’s a bit different.
typeof(MyType).GetInterfaces().Any(i => i.IsGenericType && i.GetGenericTypeDefinition() == typeof(IMyInterface<>))
I don't know of a way to force Chrome to not clear the Network debugger, but this might accomplish what you're looking for:
window.addEventListener("beforeunload", function() { debugger; }, false)
This will pause chrome before loading the new page by hitting a breakpoint.
I would strongly suspect this is not possible, because it would be an incredible security problem if it were. For example, I could make a page which looked like a bank login page, and make the URL in the address bar look just like the real bank!
Perhaps if you explain why you want to do this, folks might be able to suggest alternative approaches...
[Edit in 2011: Since I wrote this answer in 2008, more info has come to light regarding an HTML5 technique that allows the URL to be modified as long as it is from the same origin]
use css property word-wrap: break-word;
see example here: http://jsfiddle.net/emgRF/
border:0;
outline:none;
box-shadow:none;
This should do the trick.
For the MVC Controller method, use a nullable boolean type:
public ActionResult Index( string responsables, bool? checkResp) { etc. }
Then if the check box is checked, checkResp will be true. If not, it will be null.
There isn't a magic bullet solution for what you're looking for, unfortunately. Here's what you can do:
create an Interface class using this command in the Visual Studio Command Prompt window:
wsdl.exe yourFile.wsdl /l:CS /serverInterface
Use VB or CS for your language of choice. This will create a new .cs
or .vb
file.
Create a new .NET Web Service project. Import Existing File into your project - the file that was created in the step above.
In your .asmx.cs
file in Code-View, modify your class as such:
public class MyWebService : System.Web.Services.WebService, IMyWsdlInterface
{
[WebMethod]
public string GetSomeString()
{
//you'll have to write your own business logic
return "Hello SOAP World";
}
}
One option, if you need it done in a pinch, and if your initial column was created with a default, is to create the new column you want, copy the contents over to it, and basically "abandon" the old column (it stays present, but you just don't use/update it, etc.)
ex:
alter table TABLE_NAME ADD COLUMN new_column_name TYPE NOT NULL DEFAULT '';
update TABLE_NAME set new_column_name = old_column_name;
update TABLE_NAME set old_column_name = ''; -- abandon old column, basically
This leaves behind a column (and if it was created with NOT NULL but without a default, then future inserts that ignore it might fail), but if it's just a throwaway table, the tradeoffs might be acceptable. Otherwise use one of the other answers mentioned here, or a different database that allows columns to be renamed.
Create a stored procedure that does something like the following:
declare @startDate date;
declare @endDate date;
select @startDate = '20150528';
select @endDate = '20150531';
with dateRange as
(
select dt = dateadd(dd, 1, @startDate)
where dateadd(dd, 1, @startDate) < @endDate
union all
select dateadd(dd, 1, dt)
from dateRange
where dateadd(dd, 1, dt) < @endDate
)
select *
from dateRange
Or better still create a calendar table and just select from that.
This is borderline programming, but look into using tr:
$ echo "this is just a test" | tr -s ' ' | tr ' ' '_'
Should do it. The first invocation squeezes the spaces down, the second replaces with underscore. You probably need to add TABs and other whitespace characters, this is for spaces only.
In jQuery event.target
always refers to the element that triggered the event, where event
is the parameter passed to the function. http://api.jquery.com/category/events/event-object/
$(document).ready(function() {
$("a").click(function(event) {
alert(event.target.id);
});
});
Note also that this
will also work, but that it is not a jQuery object, so if you wish to use a jQuery function on it then you must refer to it as $(this)
, e.g.:
$(document).ready(function() {
$("a").click(function(event) {
// this.append wouldn't work
$(this).append(" Clicked");
});
});
Possible solutions for code that deal with RTTI and non-RTTI libraries:
a) Recompile everything with either -frtti or -fno-rtti
b) If a) is not possible for you, try the following:
Assume libfoo is built without RTTI. Your code uses libfoo and compiles with RTTI. If you use a class (Foo) in libfoo that has virtuals, you're likely to run into a link-time error that says: missing typeinfo for class Foo.
Define another class (e.g. FooAdapter) that has no virtual and will forward calls to Foo that you use.
Compile FooAdapter in a small static library that doesn't use RTTI and only depends on libfoo symbols. Provide a header for it and use that instead in your code (which uses RTTI). Since FooAdapter has no virtual function it won't have any typeinfo and you'll be able to link your binary. If you use a lot of different classes from libfoo, this solution may not be convenient, but it's a start.
HTML:
<input type="checkbox" onchange="handleChange(event)">
JS:
function handleChange(e) {
const {checked} = e.target;
}
CSS only
line-height: 1.5;
white-space: normal;
overflow: hidden;
text-overflow: ellipsis;
display: -webkit-box;
-webkit-line-clamp: 2;
-webkit-box-orient: vertical;
I guess this one is a good method, suggested by Hardik4560 ,
No because this fundamentally means that you will not be grouping anything. If you group by all columns (and have a properly defined table w/ a unique index) then SELECT * FROM table
is essentially the same thing as SELECT * FROM table GROUP BY *
.
Better to use arc4random_uniform
. However, this isn't available below iOS 4.3. Luckily iOS will bind this symbol at runtime, not at compile time (so don't use the #if preprocessor directive to check if it's available).
The best way to determine if arc4random_uniform
is available is to do something like this:
#include <stdlib.h>
int r = 0;
if (arc4random_uniform != NULL)
r = arc4random_uniform (74);
else
r = (arc4random() % 74);
Not the most readable solution, but you can mix the result from a value-of with plain text:
<a>
<xsl:attribute name="href">
Text<xsl:value-of select="/*/properties/property[@name='report']/@value"/>Text
</xsl:attribute>
</a>
It is a shorthand for Nullable<int>
. Nullable<T>
is used to allow a value type to be set to null
. Value types usually cannot be null.
You can also try using multiprocessing.Process
with daemon=True
; the process.start()
method does not block and you can return a response/status immediately to the caller while your expensive function executes in the background.
I experienced similar problem while working with falcon framework and using daemon
process helped.
You'd need to do the following:
from multiprocessing import Process
@app.route('/render/<id>', methods=['POST'])
def render_script(id=None):
...
heavy_process = Process( # Create a daemonic process with heavy "my_func"
target=my_func,
daemon=True
)
heavy_process.start()
return Response(
mimetype='application/json',
status=200
)
# Define some heavy function
def my_func():
time.sleep(10)
print("Process finished")
You should get a response immediately and, after 10s you should see a printed message in the console.
NOTE: Keep in mind that daemonic
processes are not allowed to spawn any child processes.
This Code works for Swift 4 if you want to change the image of Tab Bar Item
when pressed.
Copy and paste in the first viewDidLoad
method that is hit in the project
let arrayOfImageNameForSelectedState:[String] = ["Image1Color", "Image2Color","Image3Color"]
let arrayOfImageNameForUnselectedState: [String] = ["Image1NoColor","Image2NoColor","Image3NoColor"]
print(self.tabBarController?.tabBar.items?.count)
if let count = self.tabBarController?.tabBar.items?.count {
for i in 0...(count-1) {
let imageNameForSelectedState = arrayOfImageNameForSelectedState[i]
print(imageNameForSelectedState)
let imageNameForUnselectedState = arrayOfImageNameForUnselectedState[i]
print(imageNameForUnselectedState)
self.tabBarController?.tabBar.items?[i].selectedImage = UIImage(named: imageNameForSelectedState)?.withRenderingMode(.alwaysOriginal)
self.tabBarController?.tabBar.items?[i].image = UIImage(named: imageNameForUnselectedState)?.withRenderingMode(.alwaysOriginal)
}
}
In v5.x, you might still face the problem. So, try to delete related table manually first using
php artisan tinker
Then
Schema::drop('books')
(and exit with q
)
Now, you can successfully php artisan migrate:rollback
and php artisan migrate
.
If this happens repeatedly you should check that the down()
method in your migration is showing the right table name. (Can be a gotcha if you've changed your table names.)
If I understand you correctly, you want a list of all pictures with the same name (and their different ids) such that their name occurs more than once in the table. I think this will do the trick:
SELECT U.NAME, P.PIC_ID
FROM USERS U, PICTURES P, POSTINGS P1
WHERE U.EMAIL_ID = P1.EMAIL_ID AND P1.PIC_ID = P.PIC_ID AND U.Name IN (
SELECT U.Name
FROM USERS U, PICTURES P, POSTINGS P1
WHERE U.EMAIL_ID = P1.EMAIL_ID AND P1.PIC_ID = P.PIC_ID AND P.CAPTION LIKE '%car%';
GROUP BY U.Name HAVING COUNT(U.Name) > 1)
I haven't executed it, so there may be a syntax error or two there.
Most databases have a native UUID type these days to make working with them easier. If yours doesn't, they're just 128-bit numbers, so you can use BINARY(16), and if you need the text format frequently, e.g. for troubleshooting, then add a calculated column to generate it automatically from the binary column. There is no good reason to store the (much larger) text form.
append
appends a single element. extend
appends a list of elements.
Note that if you pass a list to append, it still adds one element:
>>> a = [1, 2, 3]
>>> a.append([4, 5, 6])
>>> a
[1, 2, 3, [4, 5, 6]]
It's worth investigating the Pipeline plugin. With the plugin you can checkout multiple VCS projects into relative directory paths. Beforehand creating a directory per VCS checkout. Then issue commands to the newly checked out VCS workspace. In my case I am using git. But you should get the idea.
node{
def exists = fileExists 'foo'
if (!exists){
new File('foo').mkdir()
}
dir ('foo') {
git branch: "<ref spec>", changelog: false, poll: false, url: '<clone url>'
......
}
def exists = fileExists 'bar'
if (!exists){
new File('bar').mkdir()
}
dir ('bar') {
git branch: "<ref spec>", changelog: false, poll: false, url: '<clone url>'
......
}
def exists = fileExists 'baz'
if (!exists){
new File('baz').mkdir()
}
dir ('baz') {
git branch: "<ref spec>", changelog: false, poll: false, url: '<clone url>'
......
}
}
ORA-03113: end-of-file on communication channel
Is the database letting you know that the network connection is no more. This could be because:
For 1) (firewall) search tahiti.oracle.com for SQLNET.EXPIRE_TIME
. This is a sqlnet.ora parameter that will regularly send a network packet at a configurable interval ie: setting this will make the firewall believe that the connection is live.
For 1) (network) speak to your network admin (connection could be unreliable)
For 2) Check the alert.log
for errors. If the server process failed there will be an error message. Also a trace file will have been written to enable support to identify the issue. The error message will reference the trace file.
Support issues can be raised at metalink.oracle.com with a suitable Customer Service Identifier (CSI)
This may have been answered before: Python URLLib / URLLib2 POST.
Your server is likely performing a 302 redirect from http://myserver/post_service
to http://myserver/post_service/
. When the 302 redirect is performed, the request changes from POST to GET (see Issue 1401). Try changing url
to http://myserver/post_service/
.
You can modify the id
without having to use getElementById
Example:
<div id = 'One' onclick = "One.id = 'Two'; return false;">One</div>
You can see it here: http://jsbin.com/elikaj/1/
Tested with Mozilla Firefox 22 and Google Chrome 60.0
If you know the location of installed jboss folder then simply open it and look for version.txt
file.
One of the variables has not been given any value, thus it is a NoneType. You'll have to look into why this is, it's probably a simple logic error on your part.
Throwing code should make clear whether the error message is appropriate for display to end users or is only intended for developer debugging. To indicate a description is displayable to the user, I use a struct DisplayableError
that implements the LocalizedError
protocol.
struct DisplayableError: Error, LocalizedError {
let errorDescription: String?
init(_ description: String) {
errorDescription = description
}
}
Usage for throwing:
throw DisplayableError("Out of pixie dust.")
Usage for display:
let messageToDisplay = error.localizedDescription
In Windows 10 PC, it is saved at:
C:\Users\<user>\.gradle\caches\modules-2\files-2.1\
Something like this?
public static T ConvertValue<T>(string value)
{
return (T)Convert.ChangeType(value, typeof(T));
}
You can then use it like this:
int val = ConvertValue<int>("42");
Edit:
You can even do this more generic and not rely on a string
parameter provided the type U
implements IConvertible
- this means you have to specify two type parameters though:
public static T ConvertValue<T,U>(U value) where U : IConvertible
{
return (T)Convert.ChangeType(value, typeof(T));
}
I considered catching the InvalidCastException
exception that might be raised by Convert.ChangeType()
- but what would you return in this case? default(T)
? It seems more appropriate having the caller deal with the exception.
Not knowing exactly what you're trying to achieve, I would suggest looking into the possibility of redesigning you application to use composition rather than inheritance in this case.
This is what works for me:
if (typeof myVar === 'string' || myVar instanceof String)
// it's a string
else
// it's something else
It might be possible to delete the Zone Record entirely, then recreate it exactly as you want it. Perhaps this will force a full propagation. If I'm wrong, somebody tell me and I'll delete this suggestion. Also, I don't know how to save a Zone Record and recreate it using WHM or any other tool.
I do know that when I deleted a hosting account today and recreated it, the original Zone Record seemed to be propagated instantly to a DNS resolver up the line from my computer. That is good evidence it works.
If it's an object method, you need to pass the object to CallObjectMethod
:
jobject result = env->CallObjectMethod(obj, messageMe, jstr);
What you were doing was the equivalent of jstr.messageMe()
.
Since your is a void method, you should call:
env->CallVoidMethod(obj, messageMe, jstr);
If you want to return a result, you need to change your JNI signature (the ()V
means a method of void
return type) and also the return type in your Java code.
If you're trying to load a DataTable
, then leverage the SqlDataAdapter
instead:
DataTable dt = new DataTable();
using (SqlConnection c = new SqlConnection(cString))
using (SqlDataAdapter sda = new SqlDataAdapter(sql, c))
{
sda.SelectCommand.CommandType = CommandType.StoredProcedure;
sda.SelectCommand.Parameters.AddWithValue("@parm1", val1);
...
sda.Fill(dt);
}
You don't even need to define the columns. Just create the DataTable
and Fill
it.
Here, cString
is your connection string and sql
is the stored procedure command.
git checkout -b <branch-name> <origin/branch_name>
for example in my case:
git branch -a
* master
origin/HEAD
origin/enum-account-number
origin/master
origin/rel_table_play
origin/sugarfield_customer_number_show_c
So to create a new branch based on my enum-account-number branch I do:
git checkout -b enum-account-number origin/enum-account-number
After you hit return the following happens:
Branch enum-account-number set up to track remote branch refs/remotes/origin/enum-account-number.
Switched to a new branch "enum-account-number"
if($('#leftmenu').val() == "") {
// statement
}
In the browser, use document.querySelect('[attribute-name]')
.
But if you're unit testing and your mocked dom has a flakey querySelector implementation, this will do the trick.
This is @kevinfahy's answer, just trimmed down to be a bit with ES6 fat arrow functions and by converting the HtmlCollection into an array at the cost of readability perhaps.
So it'll only work with an ES6 transpiler. Also, I'm not sure how performant it'll be with a lot of elements.
function getElementsWithAttribute(attribute) {
return [].slice.call(document.getElementsByTagName('*'))
.filter(elem => elem.getAttribute(attribute) !== null);
}
And here's a variant that will get an attribute with a specific value
function getElementsWithAttributeValue(attribute, value) {
return [].slice.call(document.getElementsByTagName('*'))
.filter(elem => elem.getAttribute(attribute) === value);
}
I've had this sort of problem.....
The solve: cmd
/ powershell
run as ADMINISTRATOR! I always forget.
Notice: In powershell
, you need to put .\
for example:
.\httpd -k shutdown .\httpd -k stop .\httpd -k uninstall
Result: Removing the apache2.4
service The Apache2.4
service has been removed successfully.
There's some sort of security restriction in place in Chrome for using geolocation from a file:///
URI, though unfortunately it doesn't seem to record any errors to indicate that. It will work from a local web server. If you have python installed try opening a command prompt in the directory where your test files are and issuing the command:
python -m SimpleHTTPServer
It should start up a web server on port 8000 (might be something else, but it'll tell you in the console what port it's listening on), then browse to http://localhost:8000/mytestpage.html
If you don't have python there are equivalent modules in Ruby, or Visual Web Developer Express comes with a built in local web server.
As of Git v2.23.0 (August 2019), git switch
is preferred over git checkout
when you’re simply switching branches/tags. I’m guessing they did this since git checkout
had two functions: for switching branches and for restoring files. So in v2.23.0, they added two new commands, git switch
, and git restore
, to separate those concerns. I would predict at some point in the future, git checkout
will be deprecated.
To switch to a normal branch, use git switch <branch-name>
. To switch to a commit-like object, including single commits and tags, use git switch --detach <commitish>
, where <commitish>
is the tag name or commit number.
The --detach
option forces you to recognize that you’re in a mode of “inspection and discardable experiments”. To create a new branch from the commitish you’re switching to, use git switch -c <new-branch> <start-point>
.
When you insert ANY variable into HTML, unless you want the browser to interpret the variable itself as HTML, it's best to use htmlspecialchars()
on it. Among other things, it prevents hackers from inserting arbitrary HTML in your page.
The value of $_SERVER['PHP_SELF']
is taken directly from the URL entered in the browser. Therefore if you use it without htmlspecialchars()
, you're allowing hackers to directly manipulate the output of your code.
For example, if I e-mail you a link to http://example.com/"><script>malicious_code_here()</script><span class="
and you have <form action="<?php echo $_SERVER['PHP_SELF'] ?>">
, the output will be:
<form action="http://example.com/"><script>malicious_code_here()</script><span class="">
My script will run, and you will be none the wiser. If you were logged in, I may have stolen your cookies, or scraped confidential info from your page.
However, if you used <form action="<?php echo htmlspecialchars($_SERVER['PHP_SELF']) ?>">
, the output would be:
<form action="http://example.com/"><script>cookie_stealing_code()</script><span class="">
When you submitted the form, you'd have a weird URL, but at least my evil script did not run.
On the other hand, if you used <form action="">
, then the output would be the same no matter what I added to my link. This is the option I would recommend.
dev.off() is the best function, but it clears also all plots. If you want to keep plots in your window, at the beginning save default par settings:
def.par = par()
Then when you use your par functions you still have a backup of default par settings. Later on, after generating plots, finish with:
par(def.par) #go back to default par settings
With this, you keep generated plots and reset par settings.
Difference between "querySelector" and "querySelectorAll"
//querySelector returns single element_x000D_
let listsingle = document.querySelector('li');_x000D_
console.log(listsingle);_x000D_
_x000D_
_x000D_
//querySelectorAll returns lit/array of elements_x000D_
let list = document.querySelectorAll('li');_x000D_
console.log(list);_x000D_
_x000D_
_x000D_
//Note : output will be visible in Console
_x000D_
<ul>_x000D_
<li class="test">ffff</li>_x000D_
<li class="test">vvvv</li>_x000D_
<li>dddd</li>_x000D_
<li class="test">ddff</li>_x000D_
</ul>
_x000D_
Try this:
UPDATE data_table t, (SELECT DISTINCT ID, NAME, VALUE
FROM data_table
WHERE VALUE IS NOT NULL AND VALUE != '') t1
SET t.VALUE = t1.VALUE
WHERE t.ID = t1.ID
AND t.NAME = t1.NAME
Use the collapse
argument to paste
:
paste(a,collapse=" ")
[1] "aa bb cc"
Getting right memory usage is trickier than one may think. The best way I could find is:
echo 0 $(awk '/TYPE/ {print "+", $2}' /proc/`pidof PROCESS`/smaps) | bc
Where "PROCESS" is the name of the process you want to inspect and "TYPE" is one of:
Rss
: resident memory usage, all memory the process uses, including all memory this process shares with other processes. It does not include swap;Shared
: memory that this process shares with other processes;Private
: private memory used by this process, you can look for memory leaks here;Swap
: swap memory used by the process;Pss
: Proportional Set Size, a good overall memory indicator. It is the Rss adjusted for sharing: if a process has 1MiB private and 20MiB shared between other 10 processes, Pss is 1 + 20/10 = 3MiBOther valid values are Size
(i.e. virtual size, which is almost meaningless) and Referenced
(the amount of memory currently marked as referenced or accessed).
You can use watch
or some other bash-script-fu to keep an eye on those values for processes that you want to monitor.
For more informations about smaps
: http://www.kernel.org/doc/Documentation/filesystems/proc.txt.
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.Map;
import java.util.Scanner;
import java.util.TreeMap;
public class CharCountFromAllFilesInFolder {
public static void main(String[] args)throws IOException {
try{
//C:\Users\MD\Desktop\Test1
System.out.println("Enter Your FilePath:");
Scanner sc = new Scanner(System.in);
Map<Character,Integer> hm = new TreeMap<Character, Integer>();
String s1 = sc.nextLine();
File file = new File(s1);
File[] filearr = file.listFiles();
for (File file2 : filearr) {
System.out.println(file2.getName());
FileReader fr = new FileReader(file2);
BufferedReader br = new BufferedReader(fr);
String s2 = br.readLine();
for (int i = 0; i < s2.length(); i++) {
if(!hm.containsKey(s2.charAt(i))){
hm.put(s2.charAt(i), 1);
}//if
else{
hm.put(s2.charAt(i), hm.get(s2.charAt(i))+1);
}//else
}//for2
System.out.println("The Char Count: "+hm);
}//for1
}//try
catch(Exception e){
System.out.println("Please Give Correct File Path:");
}//catch
}
}
Yes. add a linked server entry, and use select into using the four part db object naming convention.
Example:
SELECT * INTO targetTable
FROM [sourceserver].[sourcedatabase].[dbo].[sourceTable]
Most of the time you get such a error, problem is in code. I am not trying to say that you are writing code that is bad, I am trying to say that you need to carefully observe what's there in that is using this much amount of memory.
Always remember "Garbage collection in PHP is pretty bad", it's not like Java, any other such language. there is a way to enforce garbage collection through gc_collect_cycle, but, in my personal opinion, that won't solve your problem. PHP free all memory used for executing a page, once request-response cycle is complete, so you may run into memory issues, if your script is long running, like a background script(Gearman etc), because, memory isn't freed till script is running.
If above is not the case with your scr,pt, and as you said there is no code that requires such a huge amount of memory, then problem is most definitely in code it self, and upgrading to any version of PHP won't solve the problem. I was facing with one of my Gearman scripts once, and there was a problem with one of my loop where I was appending one variable to one of my array, the variable itself was very heavy (approx 110KB of data). So I would suggest, do a careful inspection of your code.
Ravish
Push only single file
git commit -m "Message goes here" filename
Push only two files.
git commit -m "Message goes here" file1 file2
On Ubuntu/Debian, you can install it with apt-get install python-simplejson
Its worked for me. I think, it work's also in your PC.
In short, there is no simpler way. You need to make another server request to show PDF file. Al though, there are few alternatives but they are not perfect and won't work on all browsers:
Here's a cleaner, more "plug-and-play", version of @Nagasaki45's answer. Unlike many other answers here, it works properly with strings of different lengths. It achieves this by clearing the line with just as many spaces as the length of the last line printed print. Will also work on Windows.
def print_statusline(msg: str):
last_msg_length = len(print_statusline.last_msg) if hasattr(print_statusline, 'last_msg') else 0
print(' ' * last_msg_length, end='\r')
print(msg, end='\r')
sys.stdout.flush() # Some say they needed this, I didn't.
print_statusline.last_msg = msg
Simply use it like this:
for msg in ["Initializing...", "Initialization successful!"]:
print_statusline(msg)
time.sleep(1)
This small test shows that lines get cleared properly, even for different lengths:
for i in range(9, 0, -1):
print_statusline("{}".format(i) * i)
time.sleep(0.5)
max-device-width is the device rendering width
@media all and (max-device-width: 400px) {
/* styles for devices with a maximum width of 400px and less
Changes only on device orientation */
}
@media all and (max-width: 400px) {
/* styles for target area with a maximum width of 400px and less
Changes on device orientation , browser resize */
}
The max-width is the width of the target display area means the current size of browser.
When you create an implicit intent, the Android system finds the appropriate component to start by comparing the contents of the intent to the intent filters declared in the manifest file of other apps on the device. If the intent matches an intent filter, the system starts that component and delivers it the Intent object. If multiple intent filters are compatible, the system displays a dialog so the user can pick which app to use.
An intent filter is an expression in an app's manifest file that specifies the type of intents that the component would like to receive. For instance, by declaring an intent filter for an activity, you make it possible for other apps to directly start your activity with a certain kind of intent. Likewise, if you do not declare any intent filters for an activity, then it can be started only with an explicit intent.
According: Intents and Intent Filters
Taking Milad's suggestion a bit further, you can break your document source down and then do another find, continuing until you find the unmatched culprit.
When you are working with many modules (using a CMS), or don't have access to the W3C tool (because you are working locally), this approach is really helpful.
Upcoming pandas 0.13 version will allow to add rows through loc
on non existing index data. However, be aware that under the hood, this creates a copy of the entire DataFrame so it is not an efficient operation.
Description is here and this new feature is called Setting With Enlargement.
First, is 40 collisions for 130 words hashed to 0..99 bad? You can't expect perfect hashing if you are not taking steps specifically for it to happen. An ordinary hash function won't have fewer collisions than a random generator most of the time.
A hash function with a good reputation is MurmurHash3.
Finally, regarding the size of the hash table, it really depends what kind of hash table you have in mind, especially, whether buckets are extensible or one-slot. If buckets are extensible, again there is a choice: you choose the average bucket length for the memory/speed constraints that you have.
Here's a simple trap that prints the last argument of whatever failed to STDERR, reports the line it failed on, and exits the script with the line number as the exit code. Note these are not always great ideas, but this demonstrates some creative application you could build on.
trap 'echo >&2 "$_ at $LINENO"; exit $LINENO;' ERR
I put that in a script with a loop to test it. I just check for a hit on some random numbers; you might use actual tests. If I need to bail, I call false (which triggers the trap) with the message I want to throw.
For elaborated functionality, have the trap call a processing function. You can always use a case statement on your arg ($_) if you need to do more cleanup, etc. Assign to a var for a little syntactic sugar -
trap 'echo >&2 "$_ at $LINENO"; exit $LINENO;' ERR
throw=false
raise=false
while :
do x=$(( $RANDOM % 10 ))
case "$x" in
0) $throw "DIVISION BY ZERO" ;;
3) $raise "MAGIC NUMBER" ;;
*) echo got $x ;;
esac
done
Sample output:
# bash tst
got 2
got 8
DIVISION BY ZERO at 6
# echo $?
6
Obviously, you could
runTest1 "Test1 fails" # message not used if it succeeds
Lots of room for design improvement.
The draw backs include the fact that false
isn't pretty (thus the sugar), and other things tripping the trap might look a little stupid. Still, I like this method.
You can use the wmic command:
wmic path CIM_LogicalDevice where "Description like 'USB%'" get /value
In addition to registering a ByteArrayHttpMessageConverter
, you may want to use a ResponseEntity
instead of @ResponseBody
. The following code works for me :
@RequestMapping("/photo2")
public ResponseEntity<byte[]> testphoto() throws IOException {
InputStream in = servletContext.getResourceAsStream("/images/no_image.jpg");
final HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.IMAGE_PNG);
return new ResponseEntity<byte[]>(IOUtils.toByteArray(in), headers, HttpStatus.CREATED);
}
You should know about the three A's. Authentication, Authorization, Audit. Classical mistake is to authenticate a user, while not checking if user is authorized to perform some action, so a user may look at other users private photos, the mistake Diaspora did. Many, many more people forget about Audit, you need, in a secure system, to be able to tell who did what and when.
Scripts are usually loaded in the end of the html page, and MVC recommends the using of bundles, just saying. So my best bet is that your jquery.validate
files got altered in some way or are not updated to the latest version, since they do validate e-mail inputs.
So you could either update/refresh your nuget package or write your own function, really.
Here's an example which you would add in an extra file after jquery.validate.unobtrusive
:
$.validator.addMethod(
"email",
function (value, element) {
return this.optional( element ) || /^[a-zA-Z0-9.!#$%&'*+\/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/.test( value );
},
"This e-mail is not valid"
);
This is just a copy and paste of the current jquery.validate
Regex, but this way you could set your custom error message/add extra methods to fields you might want to validate in the near future.
I solved it by using the default password for cacerts keystore : 'changeit'
I get exactly the same errors as kryshah with su - postgres
and sudo -u postgres psql
.
DanielM's answer gives also errors.
Answer however from przbabu's comment.
masi$ psql
psql: FATAL: database "masi" does not exist
masi$ psql -U postgres
psql: FATAL: role "postgres" does not exist
masi$ psql postgres
psql (9.4.1)
Type "help" for help.
I think the some part of this problem may be in owner settings in OSX
masi$ ls -al /Users/
total 0
drwxr-xr-x 7 root admin 238 Jul 3 09:50 .
drwxr-xr-x 37 root wheel 1326 Jul 2 19:02 ..
-rw-r--r-- 1 root wheel 0 Sep 10 2014 .localized
drwxrwxrwt 7 root wheel 238 Apr 9 19:49 Shared
drwxr-xr-x 2 root admin 68 Jul 3 09:50 postgres
drwxr-xr-x+ 71 masi staff 2414 Jul 3 09:50 masi
but doing sudo chown -R postgres:staff /Users/postgres
gives chown: invalid user: ‘postgres:staff’
.
In short, this is not the solution the problem. Use the tools provided by the postgres installation to create a user and database.
There are specific commands after postgres installation to add a new user to the database system. After initdb, run the following as described here
createuser --pwprompt postgres
createdb -Opostgres -Eutf8 masi_development
psql -U postgres -W masi_development
To avoid the password request all the time, you have three choices as described here.
set TEXT_T="myfile.txt"
set /a c=1
FOR /F "tokens=1 usebackq" %%i in (%TEXT_T%) do (
set /a c+=1
set OUTPUT_FILE_NAME=output_%c%.txt
echo Output file is %OUTPUT_FILE_NAME%
echo %%i, %c%
)
You (or Joomla) is likely including this file multiple times. Enclose your function in a conditional block:
if (!function_exists('parseDate')) {
// ... proceed to declare your function
}
I would also trim the input field, cause a space could make it look like filled
if ($.trim($('#person_data[document_type]').val()) != '')
{
}
Your current code:
ggplot(histogram, aes(f0, fill = utt)) + geom_histogram(alpha = 0.2)
is telling ggplot
to construct one histogram using all the values in f0
and then color the bars of this single histogram according to the variable utt
.
What you want instead is to create three separate histograms, with alpha blending so that they are visible through each other. So you probably want to use three separate calls to geom_histogram
, where each one gets it's own data frame and fill:
ggplot(histogram, aes(f0)) +
geom_histogram(data = lowf0, fill = "red", alpha = 0.2) +
geom_histogram(data = mediumf0, fill = "blue", alpha = 0.2) +
geom_histogram(data = highf0, fill = "green", alpha = 0.2) +
Here's a concrete example with some output:
dat <- data.frame(xx = c(runif(100,20,50),runif(100,40,80),runif(100,0,30)),yy = rep(letters[1:3],each = 100))
ggplot(dat,aes(x=xx)) +
geom_histogram(data=subset(dat,yy == 'a'),fill = "red", alpha = 0.2) +
geom_histogram(data=subset(dat,yy == 'b'),fill = "blue", alpha = 0.2) +
geom_histogram(data=subset(dat,yy == 'c'),fill = "green", alpha = 0.2)
which produces something like this:
Edited to fix typos; you wanted fill, not colour.
You want to add libraries to your project and in doing so you have two options as you yourself identified:
Compile-time libraries are libraries which is needed to compile your application. They are not included when your application is assembled (e.g., into a war-file). Libraries of this kind must be provided by the container running your project.
This is useful in situation when you want to vary API and implementation, or when the library is supplied by the container (which is typically the case with javax.servlet which is required to compile but provided by the application server, e.g., Apache Tomcat).
Run-time libraries are libraries which is needed both for compilation and when running your project. This is probably what you want in most cases. If for instance your project is packaged into a war/ear, then these libraries will be included in the package.
As for the other alernatives you have either global libraries using Library Manager
or jdk libraries. The latter is simply your regular java libraries, while the former is just a way for your to store a set of libraries under a common name. For all your future projects, instead of manually assigning the libraries you can simply select to import them from your Library Manager
.
l = list(...)
if item in l:
l.remove(item) # checks if the item to be moved is present in the list
l.insert(new_index,item)
Since Gradle 4.9, the command line arguments can be passed with --args. For example, if you want to launch the application with command line arguments foo --bar
, you can use
gradle run --args='foo --bar'
The script to autoincrement the build number in the answer above didn't work for me if the build number is a floating point value, so I modified it a little:
#!/bin/bash
buildNumber=$(/usr/libexec/PlistBuddy -c "Print CFBundleVersion" "$INFOPLIST_FILE")
buildNumber=`echo $buildNumber +1|bc`
/usr/libexec/PlistBuddy -c "Set :CFBundleVersion $buildNumber" "$INFOPLIST_FILE"
In Sailsjs there are two ways to configure all the stuff, first is to configure in config folder with each one has their separate files (like database connection regarding settings lies within connections.js ). And second is configure on environment base file structure, each environment files presents in config/env
folder and each file contains settings for particular env.
Sails first looks in config/env folder and then look forward to config/ *.js
Now lets setup ssl in config/local.js
.
var local = {
port: process.env.PORT || 1337,
environment: process.env.NODE_ENV || 'development'
};
if (process.env.NODE_ENV == 'production') {
local.ssl = {
secureProtocol: 'SSLv23_method',
secureOptions: require('constants').SSL_OP_NO_SSLv3,
ca: require('fs').readFileSync(__dirname + '/path/to/ca.crt','ascii'),
key: require('fs').readFileSync(__dirname + '/path/to/jsbot.key','ascii'),
cert: require('fs').readFileSync(__dirname + '/path/to/jsbot.crt','ascii')
};
local.port = 443; // This port should be different than your default port
}
module.exports = local;
Alternative you can add this in config/env/production.js too. (This snippet also show how to handle multiple CARoot certi)
Or in production.js
module.exports = {
port: 443,
ssl: {
secureProtocol: 'SSLv23_method',
secureOptions: require('constants').SSL_OP_NO_SSLv3,
ca: [
require('fs').readFileSync(__dirname + '/path/to/AddTrustExternalCARoot.crt', 'ascii'),
require('fs').readFileSync(__dirname + '/path/to/COMODORSAAddTrustCA.crt', 'ascii'),
require('fs').readFileSync(__dirname + '/path/to/COMODORSADomainValidationSecureServerCA.crt', 'ascii')
],
key: require('fs').readFileSync(__dirname + '/path/to/jsbot.key', 'ascii'),
cert: require('fs').readFileSync(__dirname + '/path/to/jsbot.crt', 'ascii')
}
};
Here ws is Web Socket and wss represent Secure Web Socket, as we set up ssl then now http and ws both requests become secure and transform to https and wss respectively.
There are many source from our app will receive request like any blog post, social media post but our server runs only on https so when any request come from http it gives “This site can’t be reached” error in client browser. And we loss our website traffic. So we must redirect http request to https, same rules allow for websocket otherwise socket will fails.
So we need to run same server on port 80 (http), and divert all request to port 443(https). Sails first compile config/bootstrap.js file before lifting server. Here we can start our express server on port 80.
In config/bootstrap.js (Create http server and redirect all request to https)
module.exports.bootstrap = function(cb) {
var express = require("express"),
app = express();
app.get('*', function(req, res) {
if (req.isSocket)
return res.redirect('wss://' + req.headers.host + req.url)
return res.redirect('https://' + req.headers.host + req.url)
}).listen(80);
cb();
};
Now you can visit http://www.yourdomain.com, it will redirect to https://www.yourdomain.com
Please make sure that your applicationContext.xml file is loaded by specifying it in your web.xml file:
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/applicationContext.xml</param-value>
</context-param>
Try this. Here is the code to get the sheet names in order.
private Dictionary<int, string> GetExcelSheetNames(string fileName)
{
Excel.Application _excel = null;
Excel.Workbook _workBook = null;
Dictionary<int, string> excelSheets = new Dictionary<int, string>();
try
{
object missing = Type.Missing;
object readOnly = true;
Excel.XlFileFormat.xlWorkbookNormal
_excel = new Excel.ApplicationClass();
_excel.Visible = false;
_workBook = _excel.Workbooks.Open(fileName, 0, readOnly, 5, missing,
missing, true, Excel.XlPlatform.xlWindows, "\\t", false, false, 0, true, true, missing);
if (_workBook != null)
{
int index = 0;
foreach (Excel.Worksheet sheet in _workBook.Sheets)
{
// Can get sheet names in order they are in workbook
excelSheets.Add(++index, sheet.Name);
}
}
}
catch (Exception e)
{
return null;
}
finally
{
if (_excel != null)
{
if (_workBook != null)
_workBook.Close(false, Type.Missing, Type.Missing);
_excel.Application.Quit();
}
_excel = null;
_workBook = null;
}
return excelSheets;
}
You can use
../
to mean up one level. If you have a page called page2.html in the same folder as page.html then the relative path is:
page2.html.
If you have page2.html at the same level with folder then the path is:
../page2.html
Linux Mint 19.3
I installed Java Oracle manually, like this:
$ sudo ln -s /usr/lib/jvm/java-1.8.0_211/bin/javac /usr/bin/javac
For what it worth, if anyone has this problem only in VSCode, just restart VSCode and it should fix it. Sometimes, Intellisense seems to mess up with imports or types.
Related to Typescript: Argument of type 'RegExpMatchArray' is not assignable to parameter of type 'string'
I use undefsafe religiously. It tests each level down into your object until it either gets the value you asked for, or it returns "undefined". But never errors.
on 2.7, is this too non-pythonic?
if raw_input('your prompt').lower()[0]=='y':
your code here
else:
alternate code here
it captures any variation of Yes at least.
You can use 100vw / 100vh
. CSS3 gives us viewport-relative units. 100vw means 100% of the viewport width. 100vh; 100% of the height.
<div style="display:flex; justify-content: space-between;background-color: lightyellow; width:100%; height:85vh">
<div style="width:70%; height: 100%; border: 2px dashed red"></div>
<div style="width:30%; height: 100%; border: 2px dashed red"></div>
</div>
You can install multiple Java runtimes under Windows (including Windows 7) as long as each is in their own directory.
For example, if you are running Win 7 64-bit, or Win Server 2008 R2, you may install 32-bit JRE in "C:\Program Files (x86)\Java\jre6" and 64-bit JRE in "C:\Program Files\Java\jre6", and perhaps IBM Java 6 in "C:\Program Files (x86)\IBM\Java60\jre".
The Java Control Panel app theoretically has the ability to manage multiple runtimes: Java tab >> View... button
There are tabs for User and System settings. You can add additional runtimes with Add or Find, but once you have finished adding runtimes and hit OK, you have to hit Apply in the main Java tab frame, which is not as obvious as it could be - otherwise your changes will be lost.
If you have multiple versions installed, only the main version will auto-update. I have not found a solution to this apart from the weak workaround of manually updating whenever I see an auto-update, so I'd love to know if anyone has a fix for that.
Most Java IDEs allow you to select any Java runtime on your machine to build against, but if not using an IDE, you can easily manage this using environment variables in a cmd window. Your PATH and the JAVA_HOME variable determine which runtime is used by tools run from the shell. Set the JAVA_HOME to the jre directory you want and put the bin directory into your path (and remove references to other runtimes) - with IBM you may need to add multiple bin directories. This is pretty much all the set up that the default system Java does. You can also set CLASSPATH, ANT_HOME, MAVEN_HOME, etc. to unique values to match your runtime.
i got the same problem after clicking update plugins, i tried all the suggestions above and failed , the only thing that worked for my is reinstalling android studio..
DataTable dtAll = new DataTable();
DataTable dt= new DataTable();
foreach (int id in lst)
{
dt.Merge(GetDataTableByID(id)); // Get Data Methode return DataTable
}
dtAll = dt;
You can provide a file-like object to the stdin
argument of subprocess.call()
.
The documentation for the Popen
object applies here.
To capture the output, you should instead use subprocess.check_output()
, which takes similar arguments. From the documentation:
>>> subprocess.check_output(
... "ls non_existent_file; exit 0",
... stderr=subprocess.STDOUT,
... shell=True)
'ls: non_existent_file: No such file or directory\n'
I had this problem with Django and it was because I had forgotten to start the virtual environment on the backend.
There is another way of doing this with just JavaScript. All you have to do is toggle the visibility based on the current state of the DIV's visibility in CSS.
Example:
function toggleVideo() {
var e = document.getElementById('video-over');
if(e.style.visibility == 'visible') {
e.style.visibility = 'hidden';
} else if(e.style.visibility == 'hidden') {
e.style.visibility = 'visible';
}
}
@EvilDr You can create an IUSR_[identifier] account within your AD environment and let the particular application pool run under that IUSR_[identifier] account:
"Application pool" > "Advanced Settings" > "Identity" > "Custom account"
Set your website to "Applicaton user (pass-through authentication)" and not "Specific user", in the Advanced Settings.
Now give that IUSR_[identifier] the appropriate NTFS permissions on files and folders, for example: modify on companydata.
Here's the one that may be little easier to read. Hope this is helpful.
from PIL import Image
from PIL import ExifTags
exifData = {}
img = Image.open(picture.jpg)
exifDataRaw = img._getexif()
for tag, value in exifDataRaw.items():
decodedTag = ExifTags.TAGS.get(tag, tag)
exifData[decodedTag] = value
I had a similar problem:
module cv2 has no attribute "cv2.TrackerCSRT_create"
My Python version is 3.8.0 under Windows 10. The problem was the opencv version installation.
So I fixed this way (cmd prompt with administrator privileges):
pip uninstall opencv-python
pip install opencv-contrib-python
Anyway you can read the following guide:
Clean Build folder + Build
will clear any error you may have even after fixing your code.
ConcurrentHashMap
is thread safe without synchronizing the whole map. Reads can happen very fast while write is done with a lock.
I also meet a similar error message
"Command 'python setup.py egg_info' failed with error code 1"
when I want to install cairosvg with command pip install cairosvg
in a virtual environment.
Then I have tried both pip install --upgrade pip
and pip install --upgrade setuptools
before running pip3 install cairosvg
, but I still get this error.
I can get rid of this error with sudo in front of the installation command : sudo pip install cairosvg
.
But note that the command with sudo will install the package for the system python rather than the virtual environment.
So, I further check the error message and find that I get the error while installing the cairocffi. Then I install a certain version of cairocffi (refer to this answer) before install cairosvg. That is how I solve my problem.
I fixed this issue by adding following code in my file.
@Component
@Scope(value = "session", proxyMode = ScopedProxyMode.TARGET_CLASS)
XML configuration -
<listener>
<listener-class>
org.springframework.web.context.request.RequestContextListener
</listener-class>
</listener>
Above we can do using Java configuration -
@Configuration
@WebListener
public class MyRequestContextListener extends RequestContextListener {
}
How to add a RequestContextListener with no-xml configuration?
I am using spring version 5.1.4.RELEASE and no need to add below changes in pom.
<dependency>
<groupId>cglib</groupId>
<artifactId>cglib</artifactId>
<version>3.2.10</version>
</dependency>
This happens because in r6 it shows an error when you try to extend private styles.
Refer to this link
"boilerplate code" is any seemingly repetitive code that shows up again and again in order to get some result that seems like it ought to be much simpler.
It's a subjective definition.
The term comes from "boilerplate" in the newspaper industry: wiki
try this,
String dateStr = "17-April-2011 19:20:23.707000000 ";
Date dateForm = new SimpleDateFormat("dd-MMMM-yyyy HH:mm:ss").parse(dateStr);
SimpleDateFormat format = new SimpleDateFormat("dd-MM-yyyy");
String newDate = format.format(dateForm);
Calendar today = Calendar.getInstance();
Date fromDate = format.parse(newDate);
today.setTime(fromDate);
today.add(Calendar.DAY_OF_YEAR, 1);
Date toDate= new SimpleDateFormat("dd-MM-yyyy").parse(format.format(today.getTime()));
Criteria crit = sessionFactory.getCurrentSession().createCriteria(Model.class);
crit.add(Restrictions.ge("dateFieldName", fromDate));
crit.add(Restrictions.le("dateFieldName", toDate));
return crit.list();
If you already have the figure object use:
f.set_figheight(15)
f.set_figwidth(15)
But if you use the .subplots() command (as in the examples you're showing) to create a new figure you can also use:
f, axs = plt.subplots(2,2,figsize=(15,15))
For me : Build->Clean Project solved this question
#!/bin/ksh
variable1=$(
echo "set feed off
set pages 0
select count(*) from table;
exit
" | sqlplus -s username/password@oracle_instance
)
echo "found count = $variable1"
Make sure that you have the correct layout, and that the RecyclerView id is inside the layout. Otherwise, you will be getting this error. I had the same problem, then I noticed the layout was wrong.
public class ColorsFragment extends Fragment {
public ColorsFragment() {}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
==> make sure you are getting the correct layout here. R.layout...
View rootView = inflater.inflate(R.layout.fragment_colors, container, false);
I was having issues wtih installing phonegap. The issues were fixed when i run cmd as Administrator and then run command
npm install -g phonegap
and it is installed successfully.
Then in the directory where it is installed i opened cmd, and run command phonegap and it was working fine. Now going to play with it more :)
Thanks buddies for all this help.
Another way to do this:
first_value = df['Btime'].values[0]
This way seems to be faster than using .iloc
:
In [1]: %timeit -n 1000 df['Btime'].values[20]
5.82 µs ± 142 ns per loop (mean ± std. dev. of 7 runs, 1000 loops each)
In [2]: %timeit -n 1000 df['Btime'].iloc[20]
29.2 µs ± 1.28 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)
up=`fping -r 1 $1 `
if [ -z "${up}" ]; then
printf "Host $1 not responding to ping \n"
else
printf "Host $1 responding to ping \n"
fi
private void textBox1_TextChanged(object sender, EventArgs e)
{
try
{
textBox1.AutoCompleteMode = AutoCompleteMode.Suggest;
textBox1.AutoCompleteSource = AutoCompleteSource.CustomSource;
AutoCompleteStringCollection col = new AutoCompleteStringCollection();
con.Open();
sql = "select *from Table_Name;
cmd = new SqlCommand(sql, con);
SqlDataReader sdr = null;
sdr = cmd.ExecuteReader();
while (sdr.Read())
{
col.Add(sdr["Column_Name"].ToString());
}
sdr.Close();
textBox1.AutoCompleteCustomSource = col;
con.Close();
}
catch
{
}
}
If you are using ASP.NET Core with the Startup.cs
convention, you can access and set the query command timeout option like this:
public void ConfigureServices(IServiceCollection services)
{
services.AddDbContextPool<MyDbContext>(_ =>
{
_.UseSqlServer(Configuration.GetConnectionString("MyConnectionString"), options =>
{
options.CommandTimeout(180); // 3 minutes
});
});
}
100% working in iOS Swift 4 by: Parmar Sajjad
Step 1: Goto GoogleDeveloper Api Console And create your ApiKey
Step 2: Goto Project install Cocoapods GoogleMaps pod
step 3: Goto AppDelegate.swift import GoogleMaps and
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
GMSServices.provideAPIKey("ApiKey")
return true
}
step 4: import UIKit import GoogleMaps class ViewController: UIViewController, CLLocationManagerDelegate {
@IBOutlet weak var mapview: UIView!
let locationManager = CLLocationManager()
override func viewDidLoad() {
super.viewDidLoad()
locationManagerSetting()
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func locationManagerSetting() {
self.locationManager.delegate = self
self.locationManager.desiredAccuracy = kCLLocationAccuracyNearestTenMeters
self.locationManager.requestWhenInUseAuthorization()
self.locationManager.startUpdatingLocation()
}
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
self.showCurrentLocationonMap()
self.locationManager.stopUpdatingLocation()
}
func showCurrentLocationonMap() {
let
cameraposition = GMSCameraPosition.camera(withLatitude: (self.locationManager.location?.coordinate.latitude)! , longitude: (self.locationManager.location?.coordinate.longitude)!, zoom: 18)
let mapviewposition = GMSMapView.map(withFrame: CGRect(x: 0, y: 0, width: self.mapview.frame.size.width, height: self.mapview.frame.size.height), camera: cameraposition)
mapviewposition.settings.myLocationButton = true
mapviewposition.isMyLocationEnabled = true
let marker = GMSMarker()
marker.position = cameraposition.target
marker.snippet = "Macczeb Technologies"
marker.appearAnimation = GMSMarkerAnimation.pop
marker.map = mapviewposition
self.mapview.addSubview(mapviewposition)
}
}
step 5: open info.plist file and Add below Privacy - Location When In Use Usage Description ...... below a Main storyboard file base name
step 6: run
In case we want to dump the in memory file to disk. This code can be used
if isinstanceof(obj,SpooledTemporaryFile):
obj.rollover()
The intended use for App_Data is to store database related file. Usually SQL Server Express .mdf files.
This works for me
hdmi_group=2
hdmi_mode=1
hdmi_mode=87
hdmi_cvt 800 480 60 6 0 0 0
max_usb_current=1
There is no semantic difference in the generic constraint language between whether a class 'implements' or 'extends'. The constraint possibilities are 'extends' and 'super' - that is, is this class to operate with assignable to that other one (extends), or is this class assignable from that one (super).
Starting with Android 11, you can directly bring up the app-specific settings page for the location permission only using code like this: requestPermissions(arrayOf(Manifest.permission.ACCESS_BACKGROUND_LOCATION), PERMISSION_REQUEST_BACKGROUND_LOCATION)
However, the above will only work one time. If the user denies the permission or even accidentally dismisses the screen, the app can never trigger this to come up again.
Other than the above, the answer remains the same as prior to Android 11 -- the best you can do is bring up the app-specific settings page and ask the user to drill down two levels manually to enable the proper permission.
val intent = Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS)
val uri: Uri = Uri.fromParts("package", packageName, null)
intent.data = uri
// This will take the user to a page where they have to click twice to drill down to grant the permission
startActivity(intent)
See my related question here: Android 11 users can’t grant background location permission?
{{ Form::open(array('action' => "WelcomeController@log_in")) }}
...
{{ Form::close() }}
This might be helpful
from bs4 import UnicodeDammit
with open('automate_data/billboard.csv', 'rb') as file:
content = file.read()
suggestion = UnicodeDammit(content)
suggestion.original_encoding
#'iso-8859-1'
Give this link a try --> https://pypi.python.org/pypi/setuptools
I'm assuming you're on Windows (could be wrong) but if you click the green Downloads button, it should take you to a table where you can choose to download a .exe version of setuptools appropriate for your version of Python. All that eggsetup stuff should be taken care of in the executable file.
Let me know if you need more help.
you can set the PictureBox
BackColor
proprty to Transparent
From the Sonatype doc:
The answer to this question depends on your own perspective. The great majority of Maven users are going to call Maven a “build tool”: a tool used to build deployable artifacts from source code. Build engineers and project managers might refer to Maven as something more comprehensive: a project management tool. What is the difference? A build tool such as Ant is focused solely on preprocessing, compilation, packaging, testing, and distribution. A project management tool such as Maven provides a superset of features found in a build tool. In addition to providing build capabilities, Maven can also run reports, generate a web site, and facilitate communication among members of a working team.
I'd strongly recommend looking at the Sonatype doc and spending some time looking at the available plugins to understand the power of Maven.
Very briefly, it operates at a higher conceptual level than (say) Ant. With Ant, you'd specify the set of files and resources that you want to build, then specify how you want them jarred together, and specify the order that should occur in (clean/compile/jar). With Maven this is all implicit. Maven expects to find your files in particular places, and will work automatically with that. Consequently setting up a project with Maven can be a lot simpler, but you have to play by Maven's rules!
Default values are only used if the arguments are not specified. In your case you did specify the arguments - both were supplied, with a value of NULL. (Yes, in this case NULL is considered a real value :-). Try:
EXEC TEST()
Share and enjoy.
Addendum: The default values for procedure parameters are certainly buried in a system table somewhere (see the SYS.ALL_ARGUMENTS
view), but getting the default value out of the view involves extracting text from a LONG field, and is probably going to prove to be more painful than it's worth. The easy way is to add some code to the procedure:
CREATE OR REPLACE PROCEDURE TEST(X IN VARCHAR2 DEFAULT 'P',
Y IN NUMBER DEFAULT 1)
AS
varX VARCHAR2(32767) := NVL(X, 'P');
varY NUMBER := NVL(Y, 1);
BEGIN
DBMS_OUTPUT.PUT_LINE('X=' || varX || ' -- ' || 'Y=' || varY);
END TEST;
print("imageURLString = " + imageURLString!)
just use !
RUn the following query to find if you are running spfile or not:
SELECT DECODE(value, NULL, 'PFILE', 'SPFILE') "Init File Type"
FROM sys.v_$parameter WHERE name = 'spfile';
If the result is "SPFILE", then use the following command:
alter system set open_cursors = 4000 scope=both; --4000 is the number of open cursor
if the result is "PFILE", then use the following command:
alter system set open_cursors = 1000 ;
You can read about SPFILE vs PFILE here,
from bs4 import BeautifulSoup
from requests_html import HTMLSession
url = 'your_url'
session = HTMLSession()
resp = session.get(url)
# if element with id "articlebody" is dynamic, else need not to render
resp.html.render()
soup = bs(resp.html.html, "lxml")
soup.find("div", {"id": "articlebody"})
ClickOnce applications are stored under the user's profile at %LocalAppData%\Apps\2.0\
.
From there, use the search function to find your application.
The earth is an annoyingly irregular surface, so there is no simple formula to do this exactly. You have to live with an approximate model of the earth, and project your coordinates onto it. The model I typically see used for this is WGS 84. This is what GPS devices usually use to solve the exact same problem.
NOAA has some software you can download to help with this on their website.
Since youre using JSON, I would Base64 Encode it before sending it across the wire.
If the files are large, try to look at BSON, or some other format that is better with binary transfers.
You could also zip the files, if they compress well, before base64 encoding them.
Let's say you have a collection of Car
objects (database rows), and each Car
has a collection of Wheel
objects (also rows). In other words, Car
? Wheel
is a 1-to-many relationship.
Now, let's say you need to iterate through all the cars, and for each one, print out a list of the wheels. The naive O/R implementation would do the following:
SELECT * FROM Cars;
And then for each Car
:
SELECT * FROM Wheel WHERE CarId = ?
In other words, you have one select for the Cars, and then N additional selects, where N is the total number of cars.
Alternatively, one could get all wheels and perform the lookups in memory:
SELECT * FROM Wheel
This reduces the number of round-trips to the database from N+1 to 2. Most ORM tools give you several ways to prevent N+1 selects.
Reference: Java Persistence with Hibernate, chapter 13.
If you don't need a plot per say, and you're simply interested in adding color to represent the values in a table format, you can use the style.background_gradient()
method of the pandas data frame. This method colorizes the HTML table that is displayed when viewing pandas data frames in e.g. the JupyterLab Notebook and the result is similar to using "conditional formatting" in spreadsheet software:
import numpy as np
import pandas as pd
index= ['aaa', 'bbb', 'ccc', 'ddd', 'eee']
cols = ['A', 'B', 'C', 'D']
df = pd.DataFrame(abs(np.random.randn(5, 4)), index=index, columns=cols)
df.style.background_gradient(cmap='Blues')
For detailed usage, please see the more elaborate answer I provided on the same topic previously and the styling section of the pandas documentation.
You need to create new Book
objects then put those in a new List
:
List<Book> books_2 = books_1.Select(book => new Book(book.title)).ToList();
Update: Slightly simpler... List<T>
has a method called ConvertAll
that returns a new list:
List<Book> books_2 = books_1.ConvertAll(book => new Book(book.title));
Lot of concepts here which will be useful:
List<Object> list = new ArrayList<Object>(Arrays.asList(new String[]{"Java","is","cool"}));
String[] a = new String[list.size()];
list.toArray(a);
Tip to print array of Strings:
System.out.println(Arrays.toString(a));
This is a security and maintainability question.
Whenever possible, you should use 'safe' (unidirectional) methods such as GET and HEAD in order to limit potential vulnerability.
Whenever possible, you should use 'idempotent' methods such as GET, HEAD, PUT and DELETE, which can't have side effects and are therefore less error prone/easier to control.
You can get some help from AuthorityUtils class. Checking role as a one-liner:
if (AuthorityUtils.authorityListToSet(SecurityContextHolder.getContext().getAuthentication().getAuthorities()).contains("ROLE_MANAGER")) {
/* ... */
}
Caveat: This does not check role hierarchy, if such exists.
If your task is not to invent the line-by-line reading function, but just to read the file line-by-line, you may use a typical code snippet involving the getline()
function (see the manual page here):
#define _GNU_SOURCE
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
FILE * fp;
char * line = NULL;
size_t len = 0;
ssize_t read;
fp = fopen("/etc/motd", "r");
if (fp == NULL)
exit(EXIT_FAILURE);
while ((read = getline(&line, &len, fp)) != -1) {
printf("Retrieved line of length %zu:\n", read);
printf("%s", line);
}
fclose(fp);
if (line)
free(line);
exit(EXIT_SUCCESS);
}
In the documentaion http://contactform7.com/text-fields/#textarea
[textarea* message id:contact-message 10x2 placeholder "Your Message"]
The above will generate a textarea with cols="10" and rows="2"
<textarea name="message" cols="10" rows="2" class="wpcf7-form-control wpcf7-textarea wpcf7-validates-as-required" id="contact-message" aria-required="true" aria-invalid="false" placeholder="Your Message"></textarea>
To get the current working directory, you can use:
process.cwd()
However, be aware that some scripts, notably gulp, will change the current working directory with process.chdir()
.
You can get the path of the current module with:
__filename
__dirname
If you are running a script from the command line, and you want the original directory from which the script was run, regardless of what directory the script is currently operating in, you can use:
process.env.INIT_CWD
It's sometimes desirable to run an NPM script in the current directory, rather than the root of the project.
This variable is available inside npm package scripts as:
$INIT_CWD.
You must be running a recent version of NPM. If this variable is not available, make sure NPM is up to date.
This will allow you access the current path in your package.json, e.g.:
scripts: {
"customScript": "gulp customScript --path $INIT_CWD"
}
Have you tried this http://tools.android.com/preview-channel ? Download preview channel. After that, install ADT Preview.
It's shipped with Android Studio now. Just go to Build/Analyze APK... then select your APK :)
If you are using wampserver 3 (recommended, works with no configuration usually)
if this doesnt fix it, try:
right click wampserver icon > Tools > Check httpd.conf syntax (then fix the issue it identifies and restart all services, likely it's bad syntax in your virtual hosts file)
right click wampserver icon > Tools > test port 80 (you likely have skype turned on or something else, turn it off and restart all services)
If this doesnt fix it, maybe have a windows conflict:
If this doesnt fix it:
You can check it by two methods
A)By converting the array into string and then check the required string by .contains method
String a=Arrays.toString(VALUES);
System.out.println(a.contains("AB"));
System.out.println(a.contains("BC"));
System.out.println(a.contains("CD"));
System.out.println(a.contains("AE"));
B)this is a more efficent method
Scanner s=new Scanner(System.in);
String u=s.next();
boolean d=true;
for(int i=0;i<VAL.length;i++)
{
if(VAL[i].equals(u)==d)
System.out.println(VAL[i] +" "+u+VAL[i].equals(u));
}
I had this same issue, but I was connecting to a remote db using a static IP address. So none of the above solutions solved my issue.
I had failed to add the proper User Mapping for the security Login I was using, so the solution for me was simply to ensure the User Mapping setting was set to access my database.
How do I finish the merge after resolving my merge conflicts?
With Git 2.12 (Q1 2017), you will have the more natural command:
git merge --continue
See commit c7d227d (15 Dec 2016) by Jeff King (peff
).
See commit 042e290, commit c261a87, commit 367ff69 (14 Dec 2016) by Chris Packham (cpackham
).
(Merged by Junio C Hamano -- gitster
-- in commit 05f6e1b, 27 Dec 2016)
See 2.12 release notes.
merge
: add '--continue
' option as a synonym for 'git commit
'Teach '
git merge
' the--continue
option which allows 'continuing' a merge by completing it.
The traditional way of completing a merge after resolving conflicts is to use 'git commit
'.
Now with commands like 'git rebase
' and 'git cherry-pick
' having a '--continue
' option adding such an option to 'git merge
' presents a consistent UI.
This is how I did for setting token with every request.
import { RequestOptions, BaseRequestOptions, RequestOptionsArgs } from '@angular/http';
export class CustomRequestOptions extends BaseRequestOptions {
constructor() {
super();
this.headers.set('Content-Type', 'application/json');
}
merge(options?: RequestOptionsArgs): RequestOptions {
const token = localStorage.getItem('token');
const newOptions = super.merge(options);
if (token) {
newOptions.headers.set('Authorization', `Bearer ${token}`);
}
return newOptions;
}
}
And register in app.module.ts
@NgModule({
declarations: [
AppComponent
],
imports: [
BrowserModule
],
providers: [
{ provide: RequestOptions, useClass: CustomRequestOptions }
],
bootstrap: [AppComponent]
})
export class AppModule { }
Swift 5 Protocol Extension
Here is an approach using protocol extension so that you can easily inline an optional nil check:
import Foundation
public extension Optional {
var isNil: Bool {
guard case Optional.none = self else {
return false
}
return true
}
var isSome: Bool {
return !self.isNil
}
}
Usage
var myValue: String?
if myValue.isNil {
// do something
}
if myValue.isSome {
// do something
}
When the first characters in a script are #!
, that is called the shebang. If your file starts with
#!/path/to/something
the standard is to run something
and pass the rest of the file to that program as an input.
With that said, the difference between #!/bin/bash
, #!/bin/sh
, or even #!/bin/zsh
is whether the bash, sh, or zsh programs are used to interpret the rest of the file. bash
and sh
are just different programs, traditionally. On some Linux systems they are two copies of the same program. On other Linux systems, sh
is a link to dash
, and on traditional Unix systems (Solaris, Irix, etc) bash
is usually a completely different program from sh
.
Of course, the rest of the line doesn't have to end in sh. It could just as well be #!/usr/bin/python
, #!/usr/bin/perl
, or even #!/usr/local/bin/my_own_scripting_language
.
Given a root Vue instance is accessible by all descendants via this.$root
, a parent component can access child components via the this.$children
array, and a child component can access it's parent via this.$parent
, your first instinct might be to access these components directly.
The VueJS documentation warns against this specifically for two very good reasons:
The event interface implemented by Vue allows you to communicate up and down the component tree. Leveraging the custom event interface gives you access to four methods:
$on()
- allows you to declare a listener on your Vue instance with which to listen to events$emit()
- allows you to trigger events on the same instance (self)$on()
and $emit()
:const events = new Vue({}),_x000D_
parentComponent = new Vue({_x000D_
el: '#parent',_x000D_
ready() {_x000D_
events.$on('eventGreet', () => {_x000D_
this.parentMsg = `I heard the greeting event from Child component ${++this.counter} times..`;_x000D_
});_x000D_
},_x000D_
data: {_x000D_
parentMsg: 'I am listening for an event..',_x000D_
counter: 0_x000D_
}_x000D_
}),_x000D_
childComponent = new Vue({_x000D_
el: '#child',_x000D_
methods: {_x000D_
greet: function () {_x000D_
events.$emit('eventGreet');_x000D_
this.childMsg = `I am firing greeting event ${++this.counter} times..`;_x000D_
}_x000D_
},_x000D_
data: {_x000D_
childMsg: 'I am getting ready to fire an event.',_x000D_
counter: 0_x000D_
}_x000D_
});
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/1.0.28/vue.min.js"></script>_x000D_
_x000D_
<div id="parent">_x000D_
<h2>Parent Component</h2>_x000D_
<p>{{parentMsg}}</p>_x000D_
</div>_x000D_
_x000D_
<div id="child">_x000D_
<h2>Child Component</h2>_x000D_
<p>{{childMsg}}</p>_x000D_
<button v-on:click="greet">Greet</button>_x000D_
</div>
_x000D_
Answer taken from the original post: Communicating between components in VueJS
I usually prefer the key sampling method to troubleshoot such scenarios.
redis-cli -p 6379 -n db_number --bigkeys
Eg:-
redis-cli -p 6370 -n 0 --bigkeys
There is something wrong in your setDelimiter()
function. You don't want to double quote the delimiters, do you?
public void setDelimiter(String delimiter) {
char[] c = delimiter.toCharArray();
this.delimiter = "\\" + c[0] + "\\" + c[1];
System.out.println("Delimiter string is: " + this.delimiter);
}
However, as other users have said, it's better to use the Pattern.quote() method to escape your delimiter if your requirements permit.
This will ensure that the output is a 2-digit value...you can rearrange the output to your liking and test by un-commenting the diagnostics section. Enjoy!
(I borrowed a lot of this from other forums...)
:: ------------------ Date and Time Modifier ------------------------
@echo off
setlocal
:: THIS CODE WILL DISPLAY A 2-DIGIT TIMESTAMP FOR USE IN APPENDING FILENAMES
:: CREATE VARIABLE %TIMESTAMP%
for /f "tokens=1-8 delims=.:/-, " %%i in ('echo exit^|cmd /q /k"prompt $D $T"') do (
for /f "tokens=2-4 skip=1 delims=/-,()" %%a in ('echo.^|date') do (
set dow=%%i
set %%a=%%j
set %%b=%%k
set %%c=%%l
set hh=%%m
set min=%%n
set sec=%%o
set hsec=%%p
)
)
:: ensure that hour is always 2 digits
if %hh%==0 set hh=00
if %hh%==1 set hh=01
if %hh%==2 set hh=02
if %hh%==3 set hh=03
if %hh%==4 set hh=04
if %hh%==5 set hh=05
if %hh%==6 set hh=06
if %hh%==7 set hh=07
if %hh%==8 set hh=08
if %hh%==9 set hh=09
:: --------- TIME STAMP DIAGNOSTICS -------------------------
:: Un-comment these lines to test output
:: echo dayOfWeek = %dow%
:: echo year = %yy%
:: echo month = %mm%
:: echo day = %dd%
:: echo hour = %hh%
:: echo minute = %min%
:: echo second = %sec%
:: echo hundredthsSecond = %hsec%
:: echo.
:: echo Hello!
:: echo Today is %dow%, %mm%/%dd%.
:: echo.
:: echo.
:: echo.
:: echo.
:: pause
:: --------- END TIME STAMP DIAGNOSTICS ----------------------
:: assign timeStamp:
:: Add the date and time parameters as necessary - " yy-mm-dd-dow-min-sec-hsec "
endlocal & set timeStamp=%yy%%mm%%dd%_%hh%-%min%-%sec%
echo %timeStamp%
For future googlers: You can also use copy-webpack-plugin and add this to webpack's production config:
plugins: [
new CopyWebpackPlugin({
patterns: [
// relative path is from src
{ from: './static/favicon.ico' }, // <- your path to favicon
]
})
]
You can use .val() to select the value, like the following:
function select_option(i) {
$("#span_id select").val(i);
}
Here is a jsfiddle: https://jsfiddle.net/tweissin/uscq42xh/8/
This is a helpful website listing the mapping for the latest releases of Chrome -
There is always the old-fashioned way:
long startTime = System.nanoTime();
methodToTime();
long endTime = System.nanoTime();
long duration = (endTime - startTime); //divide by 1000000 to get milliseconds.
Yes, it is 128, except for temp tables, whose names can only be up to 116 character long. It is perfectly explained here.
And the verification can be easily made with the following script contained in the blog post before:
DECLARE @i NVARCHAR(800)
SELECT @i = REPLICATE('A', 116)
SELECT @i = 'CREATE TABLE #'+@i+'(i int)'
PRINT @i
EXEC(@i)
Method 1: Put maps in a List and then join
public class Test15 {
public static void main(String[] args) {
Map<String, List<String>> map1 = new HashMap<>();
map1.put("London", Arrays.asList("A", "B", "C"));
map1.put("Wales", Arrays.asList("P1", "P2", "P3"));
Map<String, List<String>> map2 = new HashMap<>();
map2.put("Calcutta", Arrays.asList("Protijayi", "Gina", "Gini"));
map2.put("London", Arrays.asList( "P4", "P5", "P6"));
map2.put("Wales", Arrays.asList( "P111", "P5555", "P677666"));
System.out.println(map1);System.out.println(map2);
// put the maps in an ArrayList
List<Map<String, List<String>>> maplist = new ArrayList<Map<String,List<String>>>();
maplist.add(map1);
maplist.add(map2);
/*
<T,K,U> Collector<T,?,Map<K,U>> toMap(
Function<? super T,? extends K> keyMapper,
Function<? super T,? extends U> valueMapper,
BinaryOperator<U> mergeFunction)
*/
Map<String, List<String>> collect = maplist.stream()
.flatMap(ch -> ch.entrySet().stream())
.collect(
Collectors.toMap(
//keyMapper,
Entry::getKey,
//valueMapper
Entry::getValue,
// mergeFunction
(list_a,list_b) -> Stream.concat(list_a.stream(), list_b.stream()).collect(Collectors.toList())
));
System.out.println("Final Result(Map after join) => " + collect);
/*
{Wales=[P1, P2, P3], London=[A, B, C]}
{Calcutta=[Protijayi, Gina, Gini], Wales=[P111, P5555, P677666], London=[P4, P5, P6]}
Final Result(Map after join) => {Calcutta=[Protijayi, Gina, Gini], Wales=[P1, P2, P3, P111, P5555, P677666], London=[A, B, C, P4, P5, P6]}
*/
}//main
}
Method 2 : Normal Map merge
public class Test15 {
public static void main(String[] args) {
Map<String, List<String>> map1 = new HashMap<>();
map1.put("London", Arrays.asList("A", "B", "C"));
map1.put("Wales", Arrays.asList("P1", "P2", "P3"));
Map<String, List<String>> map2 = new HashMap<>();
map2.put("Calcutta", Arrays.asList("Protijayi", "Gina", "Gini"));
map2.put("London", Arrays.asList( "P4", "P5", "P6"));
map2.put("Wales", Arrays.asList( "P111", "P5555", "P677666"));
System.out.println(map1);System.out.println(map2);
/*
<T,K,U> Collector<T,?,Map<K,U>> toMap(
Function<? super T,? extends K> keyMapper,
Function<? super T,? extends U> valueMapper,
BinaryOperator<U> mergeFunction)
*/
Map<String, List<String>> collect = Stream.of(map1,map2)
.flatMap(ch -> ch.entrySet().stream())
.collect(
Collectors.toMap(
//keyMapper,
Entry::getKey,
//valueMapper
Entry::getValue,
// mergeFunction
(list_a,list_b) -> Stream.concat(list_a.stream(), list_b.stream()).collect(Collectors.toList())
));
System.out.println("Final Result(Map after join) => " + collect);
/*
{Wales=[P1, P2, P3], London=[A, B, C]}
{Calcutta=[Protijayi, Gina, Gini], Wales=[P111, P5555, P677666], London=[P4, P5, P6]}
Final Result(Map after join) => {Calcutta=[Protijayi, Gina, Gini], Wales=[P1, P2, P3, P111, P5555, P677666], London=[A, B, C, P4, P5, P6]}
*/
}//main
}
In Python, HashMap is called Dictionary and we can merge them very easily.
x = {'Roopa': 1, 'Tabu': 2}
y = {'Roopi': 3, 'Soudipta': 4}
z = {**x,**y}
print(z)
{'Roopa': 1, 'Tabu': 2, 'Roopi': 3, 'Soudipta': 4}
Just to have a simple and complete example for Python 3, which most people seem to be using now.
class MySuper(object):
def __init__(self,a):
self.a = a
class MySub(MySuper):
def __init__(self,a,b):
self.b = b
super().__init__(a)
my_sub = MySub(42,'chickenman')
print(my_sub.a)
print(my_sub.b)
gives
42
chickenman
x and y
returns true if both x
and y
are true
.
x or y
returns if either one is true
.
From this we can conclude that or
contains and
within itself unless you mean xOR
(or except if and
is true)
Checking in from 2015: We now have native promises in most recent browser (Edge 12, Firefox 40, Chrome 43, Safari 8, Opera 32 and Android browser 4.4.4 and iOS Safari 8.4, but not Internet Explorer, Opera Mini and older versions of Android).
If we want to perform 10 async actions and get notified when they've all finished, we can use the native Promise.all
, without any external libraries:
function asyncAction(i) {
return new Promise(function(resolve, reject) {
var result = calculateResult();
if (result.hasError()) {
return reject(result.error);
}
return resolve(result);
});
}
var promises = [];
for (var i=0; i < 10; i++) {
promises.push(asyncAction(i));
}
Promise.all(promises).then(function AcceptHandler(results) {
handleResults(results),
}, function ErrorHandler(error) {
handleError(error);
});
When i posted this originally it wasnt possible so this is the workaround. Now I simply suggest using other answers.
There is no way to get the outline of the image exactly but you can fake it with a div behind the image in the center.
If my trick doesn't work then you have to cut up the image and do it for every single of the little images. (the more images the more accurate the shadow will look) but for most images it looks alright with just one img.
what you need to do is to put a wrap div around your img like so
<div id="imgWrap">
<img id="img" scr="imgLocation">
</div>
then you put an empty divider inside the wrap (this will serve as the shadow)
<div id="imgWrap">
<div id="shadow"> </div>
<img id="img" scr="imgLocation">
</div>
and then you have to make the shadow appear behind the img with CSS:
#img {
z-index: 1;
}
#shadow {
z-index: 0; /*make this value negative if doesnt work*/
box-shadow: 0 -130px 180px 150px rgba(255, 255, 0, 0.6);
width: 0;
height: 0;
}
now position the imgWrap to position the original img... to center the shadow of the img you can mess with the first two values of the box-shadow making them negative.... or you can position the img and the shadow divs absolutely making img top and left values = 0 and the shadow div values = half of img width and height respectively.
If this looks horrid cut your img up and try again.
(If you don't want the shadow behind the img just on the outline then you need to make your img opaque and make it act as if it was transparent which is not that hard and you can comment and I'll explain later)
Java rule : One public
class in one file.
This is the tutorial I used to get to darrinm's answer. It's updated for ios5/6 and really easy. When I'm popular enough I'll delete this and add it as a comment to his answer.
http://www.raywenderlich.com/5492/working-with-json-in-ios-5
http://www.touch-code-magazine.com/tutorial-fetch-and-parse-json-in-ios6/
An even simpler way to kill all child process of a bash script:
pkill -P $$
The -P
flag works the same way with pkill
and pgrep
- it gets child processes, only with pkill
the child processes get killed and with pgrep
child PIDs are printed to stdout.
You could use this PHP, hope it helps.
<?php if(basename($_SERVER['PHP_SELF'], '.php') == 'home' ) { ?> class="active" <?php } else { ?> <?php }?>
So a list would be like the below.
<ul>
<li <?php if( basename($_SERVER['PHP_SELF'], '.php') == 'home' ) { ?> class="active" <?php } else { ?> <?php }?>><a href="home"><i class="fa fa-dashboard"></i> <span>Home</span></a></li>
<li <?php if( basename($_SERVER['PHP_SELF'], '.php') == 'listings' ) { ?> class="active" <?php } else { ?> <?php }?>><a href="other"><i class="fa fa-th-list"></i> <span>Other</span></a></li>
</ul>
You must place the label after a caption in order to for label
to store the table's number, not the chapter's number.
\begin{table} \begin{tabular}{| p{5cm} | p{5cm} | p{5cm} |} -- cut -- \end{tabular} \caption{My table} \label{table:kysymys} \end{table} Table \ref{table:kysymys} on page \pageref{table:kysymys} refers to the ...
Just did the test and it works with toEqual
please find my test:
describe('toEqual', function() {
it('passes if arrays are equal', function() {
var arr = [1, 2, 3];
expect(arr).toEqual([1, 2, 3]);
});
});
Just for information:
toBe() versus toEqual(): toEqual() checks equivalence. toBe(), on the other hand, makes sure that they're the exact same object.
set datestr=%date%
set result=%datestr:/=-%
@echo %result%
pause
Maybe because its 2013-01-29 so +1 month would be 2013-02-29 which doesn't exist so it would be 2013-03-01
You could try
date('m/d/y h:i a',(strtotime('next month',strtotime(date('m/01/y')))));
from the comments on http://php.net/manual/en/function.strtotime.php
Answer above is missing an example which might not be obvious (it wasn't to me).
Url could be broken down into parts
https://github.com/liufa/Tuplinator/commit/f36e3c5b3aba23a6c9cf7c01e7485028a23c3811
\_____/\________/ \_______________________________________/
| | |
Account name | Hash of revision
Project name
Hash can be found here (you can click it and will get the url from browser).
Hope this saves you some time.
I have the same issue with Eclipse Helios and the m2eclipse plugin. They just can't seem to get this thing to work with WTP or WPT or whatever the blasted acronym is.
If I do a clean on the project and watch the Maven console then I can see the compilation issues in the console but eclipse won't touch it. It seems eclipse or WTP/WPT and m2eclipse are busy playing slap hands.
On my Mac that I'm sure I'm not going to allow java anyplace other than a specific site, I was able to use Preferences->Java to bring up the Java control panel and turned the checking off. If DLink ever fixes their certificate, I'll turn it back on.
This declaration:
double F[1000][1000000];
would occupy 8 * 1000 * 1000000 bytes on a typical x86 system. This is about 7.45 GB. Chances are your system is running out of memory when trying to execute your code, which results in a segmentation fault.
Java SE Development Kit 9 is not compatible with the Netbeans IDE 8.2.
My Solution:
Personally, I needed a little hand holding figuring out how to use this and it is really, awesome.
IF(OBJECT_ID('tempdb..#TEMP') IS NOT NULL) BEGIN DROP TABLE #TEMP END
SELECT *
INTO #TEMP
FROM (
The query you want to use many times
) AS X
SELECT * FROM #TEMP WHERE THIS = THAT
SELECT * FROM #TEMP WHERE THIS <> THAT
SELECT COL1,COL3 FROM #TEMP WHERE THIS > THAT
DROP TABLE #TEMP
You have the alias inside of the case, it needs to be outside of the END
:
Insert into TblStuff (FullName,Address,City,Zip)
Select
Case
When Middle is Null
Then Fname + LName
Else Fname +' ' + Middle + ' '+ Lname
End as FullName,
Case
When Address2 is Null Then Address1
else Address1 +', ' + Address2
End as Address,
City as City,
Zip as Zip
from tblImport