app-routing.module.ts
const routes: Routes = [
{ path: 'products', component: ProductsComponent },
{ path: 'product/:id', component: ProductDetailsComponent },
{ path: '', redirectTo: '/products', pathMatch: 'full' },
];
In controller you can navigate like this,
this.router.navigate(['/products', productId]);
It will land you to path like this: http://localhost:4200/products/product-id
To join all lines into a string and remove new lines, I normally use :
with open('t.txt') as f:
s = " ".join([l.rstrip() for l in f])
This is a optimized version of the function which removes dependency on BitConverter function and makes it compatible with NETMF (.NET Micro Framework)
public static DateTime GetNetworkTime()
{
const string ntpServer = "pool.ntp.org";
var ntpData = new byte[48];
ntpData[0] = 0x1B; //LeapIndicator = 0 (no warning), VersionNum = 3 (IPv4 only), Mode = 3 (Client Mode)
var addresses = Dns.GetHostEntry(ntpServer).AddressList;
var ipEndPoint = new IPEndPoint(addresses[0], 123);
var socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
socket.Connect(ipEndPoint);
socket.Send(ntpData);
socket.Receive(ntpData);
socket.Close();
ulong intPart = (ulong)ntpData[40] << 24 | (ulong)ntpData[41] << 16 | (ulong)ntpData[42] << 8 | (ulong)ntpData[43];
ulong fractPart = (ulong)ntpData[44] << 24 | (ulong)ntpData[45] << 16 | (ulong)ntpData[46] << 8 | (ulong)ntpData[47];
var milliseconds = (intPart * 1000) + ((fractPart * 1000) / 0x100000000L);
var networkDateTime = (new DateTime(1900, 1, 1)).AddMilliseconds((long)milliseconds);
return networkDateTime;
}
This can happen because java script allows white spaces sometimes if a string is concatenated with a number. try removing the spaces and create a string and then pass it into getElementById.
example:
var str = 'horseThumb_'+id;
str = str.replace(/^\s+|\s+$/g,"");
function AddBorder(id){
document.getElementById(str).className='hand positionLeft'
}
While iterating through the loop, you are trying to change the List value in the remove() operation. This will result in ConcurrentModificationException.
Follow the below code, which will achieve what you want and yet will not throw any exceptions
private String toString(List aDrugStrengthList) {
StringBuilder str = new StringBuilder();
List removalList = new ArrayList();
for (DrugStrength aDrugStrength : aDrugStrengthList) {
if (!aDrugStrength.isValidDrugDescription()) {
removalList.add(aDrugStrength);
}
}
aDrugStrengthList.removeAll(removalList);
str.append(aDrugStrengthList);
if (str.indexOf("]") != -1) {
str.insert(str.lastIndexOf("]"), "\n " );
}
return str.toString();
}
Have that issue. So long time pass... Without side-fields of page it's break normal, but when fields appears, page and "page break space" will scale. So, with a normal field, within a document, it was shown incorrect. I fix it with set
width:100%
and use
div.page
{
page-break-before: always;
page-break-inside: avoid;
}
Use it on first line.
Similar to other answers I had miss typed the query.
I had -
SELECT t.id FROM t.table LEFT JOIN table2 AS t2 ON t.id = t2.table_id
Should have been
SELECT t.id FROM table AS t LEFT JOIN table2 AS t2 ON t.id = t2.table_id
Mysql was trying to find a database called t which the user didn't have permission for.
Imports System.IO
Public Class Form1
Public line, counter As String
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
counter += 1
If TextBox1.Text = "" Then
MsgBox("Enter a DNS address to ping")
Else
'line = ":start" + vbNewLine
'line += "ping " + TextBox1.Text
'MsgBox(line)
Dim StreamToWrite As StreamWriter
StreamToWrite = New StreamWriter("C:\Desktop\Ping" + counter + ".bat")
StreamToWrite.Write(":start" + vbNewLine + _
"Ping -t " + TextBox1.Text)
StreamToWrite.Close()
Dim p As New System.Diagnostics.Process()
p.StartInfo.FileName = "C:\Desktop\Ping" + counter + ".bat"
p.Start()
End If
End Sub
End Class
This works as well
I use two methods for relative sizing. I have a class called Relative
with three attached properties To
, WidthPercent
and HeightPercent
which is useful if I want an element to be a relative size of an element anywhere in the visual tree and feels less hacky than the converter approach - although use what works for you, that you're happy with.
The other approach is rather more cunning. Add a ViewBox
where you want relative sizes inside, then inside that, add a Grid
at width 100. Then if you add a TextBlock
with width 10 inside that, it is obviously 10% of 100.
The ViewBox
will scale the Grid
according to whatever space it has been given, so if its the only thing on the page, then the Grid
will be scaled out full width and effectively, your TextBlock
is scaled to 10% of the page.
If you don't set a height on the Grid
then it will shrink to fit its content, so it'll all be relatively sized. You'll have to ensure that the content doesn't get too tall, i.e. starts changing the aspect ratio of the space given to the ViewBox
else it will start scaling the height as well. You can probably work around this with a Stretch
of UniformToFill
.
This works well in ASP.NET webforms.
Change the script to
<img src="' + imagePath + 'chevron-large-right-grey.gif" alt="'.....
I have a master page for each directory level and this is in the Page_Init event
Dim vPath As String = ResolveUrl("~/Images/")
Dim SB As New StringBuilder
SB.Append("var imagePath = '" & vPath & "'; ")
ScriptManager.RegisterClientScriptBlock(Me, Me.GetType(), "LoadImagePath", SB.ToString, True)
Now regardless of whether the application is run locally or deployed you get the correct full path
http://localhost:57387/Images/chevron-large-left-blue.png
In CSS3 you have:
:nth-last-child(2)
See: https://developer.mozilla.org/en-US/docs/Web/CSS/:nth-last-child
nth-last-child Browser Support:
- Chrome 2
- Firefox 3.5
- Opera 9.5, 10
- Safari 3.1, 4
- Internet Explorer 9
In newer versions of phpMyAdmin access permissions for user-names + ip-addresses can be set up inside the phpMyAdmin's config.inc.php file. This is a much better and more robust method of restricting access (over hard-coding URLs and IP addresses into Apache's httpd.conf).
Here is a full example of how to switch to white-listing all users (no one outside this list will be allowed access), and also how to restrict user root to the local system and network only.
$cfg['Servers'][$i]['AllowDeny']['order'] = 'deny,allow';
$cfg['Servers'][$i]['AllowDeny']['rules'] = array(
'deny % from all', // deny everyone by default, then -
'allow % from 127.0.0.1', // allow all local users
'allow % from ::1',
//'allow % from SERVER_ADDRESS', // allow all from server IP
// allow user:root access from these locations (local network)
'allow root from localhost',
'allow root from 127.0.0.1',
'allow root from 10.0.0.0/8',
'allow root from 172.16.0.0/12',
'allow root from 192.168.0.0/16',
'allow root from ::1',
// add more usernames and their IP (or IP ranges) here -
);
Source: How to Install and Secure phpMyAdmin on localhost for Windows
This gives you much more fine-grained access restrictions than Apache's URL permissions or an .htaccess file can provide, at the MySQL user name level.
Make sure that the user you are login in with, has its MySQL Host:
field set to 127.0.0.1
or ::1
, as phpMyAdmin and MySQL are on the same system.
You can simply add this class.
.btn {
white-space:normal !important;
word-wrap: break-word;
}
I used:
git reset --hard
I lost some changes, but this is ok.
If I understand the situation correctly, you are just passing json data through the http body, instead of application/x-www-form-urlencoded
data.
You can fetch this data with this snippet:
$request_body = file_get_contents('php://input');
If you are passing json, then you can do:
$data = json_decode($request_body);
$data
then contains the json data is php array.
php://input
is a so called wrapper.
php://input is a read-only stream that allows you to read raw data from the request body. In the case of POST requests, it is preferable to use php://input instead of $HTTP_RAW_POST_DATA as it does not depend on special php.ini directives. Moreover, for those cases where $HTTP_RAW_POST_DATA is not populated by default, it is a potentially less memory intensive alternative to activating always_populate_raw_post_data. php://input is not available with enctype="multipart/form-data".
The addition of a string literal with an std::string
yields another std::string
. system
expects a const char*
. You can use std::string::c_str()
for that:
string name = "john";
string tmp = " quickscan.exe resolution 300 selectscanner jpg showui showprogress filename '"+name+".jpg'"
system(tmp.c_str());
Selector > child:
.text-center-row>th,_x000D_
.text-center-row>td {_x000D_
text-align: center;_x000D_
}
_x000D_
<table border="1" width='500px'>_x000D_
<tr class="text-center-row">_x000D_
<th>Text</th>_x000D_
<th>Text</th>_x000D_
<th>Text</th>_x000D_
<th>Text</th>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>Text</td>_x000D_
<td>Text</td>_x000D_
<td>Text</td>_x000D_
<td>Text</td>_x000D_
</tr>_x000D_
<tr class="text-center-row">_x000D_
<td>Text</td>_x000D_
<td>Text</td>_x000D_
<td>Text</td>_x000D_
<td>Text</td>_x000D_
</tr>_x000D_
</table>
_x000D_
With newer releases of jquery (1.3+ I think), all you have to do is set one of the members of the radio set to be required and jquery will take care of the rest:
<input type="radio" name="myoptions" value="blue" class="required"> Blue<br />
<input type="radio" name="myoptions" value="red"> Red<br />
<input type="radio" name="myoptions" value="green"> Green
The above would require at least 1 of the 3 radio options w/ the name of "my options" to be selected before proceeding.
The label suggestion by Mahes, btw, works wonderfully!
You could just define a new xml background in the drawables folder
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle">
<solid android:color="enter_your_desired_color_here" />
<corners android:radius="enter_your_desired_radius_the_corners" />
</shape>
After this just include it in your TextView or EditText by defining it in the background.
<TextView
android:id="@+id/textView"
android:layout_width="0dp"
android:layout_height="80dp"
android:background="YOUR_FILE_HERE"
Android:layout_weight="1"
android:gravity="center"
android:text="TEXT_HERE"
android:textSize="40sp" />
Data transfer between two platform requires a common data format. JSON is a common global format to send cross platform data.
drawChart(600/50, JSON.parse('<?php echo json_encode($day); ?>'), JSON.parse('<?php echo json_encode($week); ?>'), JSON.parse('<?php echo json_encode($month); ?>'), JSON.parse('<?php echo json_encode(createDatesArray(cal_days_in_month(CAL_GREGORIAN, date('m',strtotime('-1 day')), date('Y',strtotime('-1 day'))))); ?>'))
This is the answer to your question. The answer may look very complex. You can see a simple example describing the communication between server side and client side here
$employee = array(
"employee_id" => 10011,
"Name" => "Nathan",
"Skills" =>
array(
"analyzing",
"documentation" =>
array(
"desktop",
"mobile"
)
)
);
Conversion to JSON format is required to send the data back to client application ie, JavaScript. PHP has a built in function json_encode(), which can convert any data to JSON format. The output of the json_encode function will be a string like this.
{
"employee_id": 10011,
"Name": "Nathan",
"Skills": {
"0": "analyzing",
"documentation": [
"desktop",
"mobile"
]
}
}
On the client side, success function will get the JSON string. Javascript also have JSON parsing function JSON.parse() which can convert the string back to JSON object.
$.ajax({
type: 'POST',
headers: {
"cache-control": "no-cache"
},
url: "employee.php",
async: false,
cache: false,
data: {
employee_id: 10011
},
success: function (jsonString) {
var employeeData = JSON.parse(jsonString); // employeeData variable contains employee array.
});
You add web components to a J2EE application in a package called a web application archive (WAR), which is a JAR similar to the package used for Java class libraries. A WAR usually contains other resources besides web components, including:
- Server-side utility classes (database beans, shopping carts, and so on).
- Static web resources (HTML, image, and sound files, and so on)
- Client-side classes (applets and utility classes)
A WAR has a specific hierarchical directory structure. The top-level directory of a WAR is the document root of the application. The document root is where JSP pages, client-side classes and archives, and static web resources are stored.
(source)
So a .war is a .jar, but it contains web application components and is laid out according to a specific structure. A .war is designed to be deployed to a web application server such as Tomcat or Jetty or a Java EE server such as JBoss or Glassfish.
Try this:
// found on UglifyJS
variable = void 0;
you can use sorted() method if you want it to return the sorted list. It's more convenient.
l1 = []
n = int(input())
for i in range(n):
user = int(input())
l1.append(user)
sorted(l1,reverse=True)
list.sort() method modifies the list in-place and returns None.
if you still want to use sort you can do this.
l1 = []
n = int(input())
for i in range(n):
user = int(input())
l1.append(user)
l1.sort(reverse=True)
print(l1)
I use let
to test my HTTP 404 responses in my API specs using contexts.
To create the resource, I use let!
. But to store the resource identifier, I use let
. Take a look how it looks like:
let!(:country) { create(:country) }
let(:country_id) { country.id }
before { get "api/countries/#{country_id}" }
it 'responds with HTTP 200' { should respond_with(200) }
context 'when the country does not exist' do
let(:country_id) { -1 }
it 'responds with HTTP 404' { should respond_with(404) }
end
That keeps the specs clean and readable.
why not just pass an data an object with your key/value pairs then you don't have to worry about encoding
$.ajax({
type: "Post",
url: "getdata.php",
data:{
timestamp: timestamp,
uid: id,
uname: name
},
async: true,
cache: false,
success: function(data) {
};
}?);?
I realise this is an old post, but in case it helps, you can apply this CSS to have IE11 draw a dotted outline for the focus indication of a <select>
element so that it resembles Firefox's focus indication:
select:focus::-ms-value {
background: transparent;
color: inherit;
outline-style: dotted;
outline-width: thin;
}
In order to obtain a program that generates a list of random values without duplicates that is deterministic, efficient and built with basic programming constructs consider the function extractSamples
defined below,
def extractSamples(populationSize, sampleSize, intervalLst) :
import random
if (sampleSize > populationSize) :
raise ValueError("sampleSize = "+str(sampleSize) +" > populationSize (= " + str(populationSize) + ")")
samples = []
while (len(samples) < sampleSize) :
i = random.randint(0, (len(intervalLst)-1))
(a,b) = intervalLst[i]
sample = random.randint(a,b)
if (a==b) :
intervalLst.pop(i)
elif (a == sample) : # shorten beginning of interval
intervalLst[i] = (sample+1, b)
elif ( sample == b) : # shorten interval end
intervalLst[i] = (a, sample - 1)
else :
intervalLst[i] = (a, sample - 1)
intervalLst.append((sample+1, b))
samples.append(sample)
return samples
The basic idea is to keep track of intervals intervalLst
for possible values from which to select our required elements from. This is deterministic in the sense that we are guaranteed to generate a sample within a fixed number of steps (solely dependent on populationSize
and sampleSize
).
To use the above function to generate our required list,
In [3]: populationSize, sampleSize = 10**17, 10**5
In [4]: %time lst1 = extractSamples(populationSize, sampleSize, [(0, populationSize-1)])
CPU times: user 289 ms, sys: 9.96 ms, total: 299 ms
Wall time: 293 ms
We may also compare with an earlier solution (for a lower value of populationSize)
In [5]: populationSize, sampleSize = 10**8, 10**5
In [6]: %time lst = random.sample(range(populationSize), sampleSize)
CPU times: user 1.89 s, sys: 299 ms, total: 2.19 s
Wall time: 2.18 s
In [7]: %time lst1 = extractSamples(populationSize, sampleSize, [(0, populationSize-1)])
CPU times: user 449 ms, sys: 8.92 ms, total: 458 ms
Wall time: 442 ms
Note that I reduced populationSize
value as it produces Memory Error for higher values when using the random.sample
solution (also mentioned in previous answers here and here). For above values, we can also observe that extractSamples
outperforms the random.sample
approach.
P.S. : Though the core approach is similar to my earlier answer, there are substantial modifications in implementation as well as approach alongwith improvement in clarity.
I'd rather use static widths and if you'd like your page to resize depending on screen size, you can have a look at media queries.
Or, you can set a min-width on elements like header, navigation, content etc.
I feel many might be interested in free parameters to alter the shape of the sigmoid function. Second for many applications you want to use a mirrored sigmoid function. Third you might want to do a simple normalization for example the output values are between 0 and 1.
Try:
def normalized_sigmoid_fkt(a, b, x):
'''
Returns array of a horizontal mirrored normalized sigmoid function
output between 0 and 1
Function parameters a = center; b = width
'''
s= 1/(1+np.exp(b*(x-a)))
return 1*(s-min(s))/(max(s)-min(s)) # normalize function to 0-1
And to draw and compare:
def draw_function_on_2x2_grid(x):
fig, ((ax1, ax2), (ax3, ax4)) = plt.subplots(2, 2)
plt.subplots_adjust(wspace=.5)
plt.subplots_adjust(hspace=.5)
ax1.plot(x, normalized_sigmoid_fkt( .5, 18, x))
ax1.set_title('1')
ax2.plot(x, normalized_sigmoid_fkt(0.518, 10.549, x))
ax2.set_title('2')
ax3.plot(x, normalized_sigmoid_fkt( .7, 11, x))
ax3.set_title('3')
ax4.plot(x, normalized_sigmoid_fkt( .2, 14, x))
ax4.set_title('4')
plt.suptitle('Different normalized (sigmoid) function',size=10 )
return fig
Finally:
x = np.linspace(0,1,100)
Travel_function = draw_function_on_2x2_grid(x)
here is a very mechanical method without the distracting theories:
This more practical method is in accordance to the much theoretical answers above. So, those still reading those Java books saying to use modulo, this is definitely wrong since the 4 steps I outlined above is definitely not a modulo operation.
In addition Swiss Mister post, in my case the window.open was launched inside a promise, which turned the popup blocker on, my solution was: in angular:
$scope.gotClick = function(){
var myNewTab = browserService.openNewTab();
someService.getUrl().then(
function(res){
browserService.updateTabLocation(res.url, myNewTab);
}
);
};
browserService:
this.openNewTab = function(){
var newTabWindow = $window.open();
return newTabWindow;
}
this.updateTabLocation = function(tabLocation, tab) {
if(!tabLocation){
tab.close();
}
tab.location.href = tabLocation;
}
this is how you can open a new tab using the promise response and not invoking the popup blocker.
in my case problem was build tools version which was 23.0.0 rc3 and i changed to 22.0.1 and my problem fixed.
You say that the matrices are the same dimensions, and yet you are trying to perform matrix multiplication on them. Multiplication of matrices with the same dimension is only possible if they are square. In your case, you get an assertion error, because the dimensions are not square. You have to be careful when multiplying matrices, as there are two possible meanings of multiply.
Matrix multiplication is where two matrices are multiplied directly. This operation multiplies matrix A of size [a x b] with matrix B of size [b x c] to produce matrix C of size [a x c]. In OpenCV it is achieved using the simple *
operator:
C = A * B
Element-wise multiplication is where each pixel in the output matrix is formed by multiplying that pixel in matrix A by its corresponding entry in matrix B. The input matrices should be the same size, and the output will be the same size as well. This is achieved using the mul()
function:
output = A.mul(B);
Yes you can. However, it depends on the C-library that you are linking against and you need to be aware of the consequences.
Since you are programming for embedded applications, realise that floating-point support is emulated for a lot of embedded architectures. Compiling in this floating-point support will end up increasing the size of your executable significantly.
My Code Is Very Easy To Understand
var year = 2015;
var LeapYear = year % 4;
if (LeapYear==0) {
alert("This is Leap Year");
} else {
alert("This is not leap year");
}
If your index is less than the size of your list then it does exist, possibly with null
value. If index is bigger then you may call ensureCapacity()
to be able to use that index.
If you want to check if a value at your index is null
or not, call get()
A modern alternative:
const textToFind = 'Google';
const dd = document.getElementById ('MyDropDown');
dd.selectedIndex = [...dd.options].findIndex (option => option.text === textToFind);
This UtilException
helper class lets you use any checked exceptions in Java streams, like this:
Stream.of("java.lang.Object", "java.lang.Integer", "java.lang.String")
.map(rethrowFunction(Class::forName))
.collect(Collectors.toList());
Note Class::forName
throws ClassNotFoundException
, which is checked. The stream itself also throws ClassNotFoundException
, and NOT some wrapping unchecked exception.
public final class UtilException {
@FunctionalInterface
public interface Consumer_WithExceptions<T, E extends Exception> {
void accept(T t) throws E;
}
@FunctionalInterface
public interface BiConsumer_WithExceptions<T, U, E extends Exception> {
void accept(T t, U u) throws E;
}
@FunctionalInterface
public interface Function_WithExceptions<T, R, E extends Exception> {
R apply(T t) throws E;
}
@FunctionalInterface
public interface Supplier_WithExceptions<T, E extends Exception> {
T get() throws E;
}
@FunctionalInterface
public interface Runnable_WithExceptions<E extends Exception> {
void run() throws E;
}
/** .forEach(rethrowConsumer(name -> System.out.println(Class.forName(name)))); or .forEach(rethrowConsumer(ClassNameUtil::println)); */
public static <T, E extends Exception> Consumer<T> rethrowConsumer(Consumer_WithExceptions<T, E> consumer) throws E {
return t -> {
try { consumer.accept(t); }
catch (Exception exception) { throwAsUnchecked(exception); }
};
}
public static <T, U, E extends Exception> BiConsumer<T, U> rethrowBiConsumer(BiConsumer_WithExceptions<T, U, E> biConsumer) throws E {
return (t, u) -> {
try { biConsumer.accept(t, u); }
catch (Exception exception) { throwAsUnchecked(exception); }
};
}
/** .map(rethrowFunction(name -> Class.forName(name))) or .map(rethrowFunction(Class::forName)) */
public static <T, R, E extends Exception> Function<T, R> rethrowFunction(Function_WithExceptions<T, R, E> function) throws E {
return t -> {
try { return function.apply(t); }
catch (Exception exception) { throwAsUnchecked(exception); return null; }
};
}
/** rethrowSupplier(() -> new StringJoiner(new String(new byte[]{77, 97, 114, 107}, "UTF-8"))), */
public static <T, E extends Exception> Supplier<T> rethrowSupplier(Supplier_WithExceptions<T, E> function) throws E {
return () -> {
try { return function.get(); }
catch (Exception exception) { throwAsUnchecked(exception); return null; }
};
}
/** uncheck(() -> Class.forName("xxx")); */
public static void uncheck(Runnable_WithExceptions t)
{
try { t.run(); }
catch (Exception exception) { throwAsUnchecked(exception); }
}
/** uncheck(() -> Class.forName("xxx")); */
public static <R, E extends Exception> R uncheck(Supplier_WithExceptions<R, E> supplier)
{
try { return supplier.get(); }
catch (Exception exception) { throwAsUnchecked(exception); return null; }
}
/** uncheck(Class::forName, "xxx"); */
public static <T, R, E extends Exception> R uncheck(Function_WithExceptions<T, R, E> function, T t) {
try { return function.apply(t); }
catch (Exception exception) { throwAsUnchecked(exception); return null; }
}
@SuppressWarnings ("unchecked")
private static <E extends Throwable> void throwAsUnchecked(Exception exception) throws E { throw (E)exception; }
}
Many other examples on how to use it (after statically importing UtilException
):
@Test
public void test_Consumer_with_checked_exceptions() throws IllegalAccessException {
Stream.of("java.lang.Object", "java.lang.Integer", "java.lang.String")
.forEach(rethrowConsumer(className -> System.out.println(Class.forName(className))));
Stream.of("java.lang.Object", "java.lang.Integer", "java.lang.String")
.forEach(rethrowConsumer(System.out::println));
}
@Test
public void test_Function_with_checked_exceptions() throws ClassNotFoundException {
List<Class> classes1
= Stream.of("Object", "Integer", "String")
.map(rethrowFunction(className -> Class.forName("java.lang." + className)))
.collect(Collectors.toList());
List<Class> classes2
= Stream.of("java.lang.Object", "java.lang.Integer", "java.lang.String")
.map(rethrowFunction(Class::forName))
.collect(Collectors.toList());
}
@Test
public void test_Supplier_with_checked_exceptions() throws ClassNotFoundException {
Collector.of(
rethrowSupplier(() -> new StringJoiner(new String(new byte[]{77, 97, 114, 107}, "UTF-8"))),
StringJoiner::add, StringJoiner::merge, StringJoiner::toString);
}
@Test
public void test_uncheck_exception_thrown_by_method() {
Class clazz1 = uncheck(() -> Class.forName("java.lang.String"));
Class clazz2 = uncheck(Class::forName, "java.lang.String");
}
@Test (expected = ClassNotFoundException.class)
public void test_if_correct_exception_is_still_thrown_by_method() {
Class clazz3 = uncheck(Class::forName, "INVALID");
}
But don't use it before understanding the following advantages, disadvantages, and limitations:
• If the calling-code is to handle the checked exception you MUST add it to the throws clause of the method that contains the stream. The compiler will not force you to add it anymore, so it's easier to forget it.
• If the calling-code already handles the checked exception, the compiler WILL remind you to add the throws clause to the method declaration that contains the stream (if you don't it will say: Exception is never thrown in body of corresponding try statement).
• In any case, you won't be able to surround the stream itself to catch the checked exception INSIDE the method that contains the stream (if you try, the compiler will say: Exception is never thrown in body of corresponding try statement).
• If you are calling a method which literally can never throw the exception that it declares, then you should not include the throws clause. For example: new String(byteArr, "UTF-8") throws UnsupportedEncodingException, but UTF-8 is guaranteed by the Java spec to always be present. Here, the throws declaration is a nuisance and any solution to silence it with minimal boilerplate is welcome.
• If you hate checked exceptions and feel they should never be added to the Java language to begin with (a growing number of people think this way, and I am NOT one of them), then just don't add the checked exception to the throws clause of the method that contains the stream. The checked exception will, then, behave just like an UNchecked exception.
• If you are implementing a strict interface where you don't have the option for adding a throws declaration, and yet throwing an exception is entirely appropriate, then wrapping an exception just to gain the privilege of throwing it results in a stacktrace with spurious exceptions which contribute no information about what actually went wrong. A good example is Runnable.run(), which does not throw any checked exceptions. In this case, you may decide not to add the checked exception to the throws clause of the method that contains the stream.
• In any case, if you decide NOT to add (or forget to add) the checked exception to the throws clause of the method that contains the stream, be aware of these 2 consequences of throwing CHECKED exceptions:
1) The calling-code won't be able to catch it by name (if you try, the compiler will say: Exception is never thrown in body of corresponding try statement). It will bubble and probably be catched in the main program loop by some "catch Exception" or "catch Throwable", which may be what you want anyway.
2) It violates the principle of least surprise: it will no longer be enough to catch RuntimeException to be able to guarantee catching all possible exceptions. For this reason, I believe this should not be done in framework code, but only in business code that you completely control.
In conclusion: I believe the limitations here are not serious, and the UtilException
class may be used without fear. However, it's up to you!
It’s a chicken-and-egg problem. You won’t be able to do it because you need to load the assets to display the progress bar widget, by which time your page will be either fully or partially downloaded. Also, you need to know the total size of the page prior to the user requesting in order to calculate a percentage.
It’s more hassle than it’s worth.
If you need to connect to LocalDB during development, you can use:
sqlcmd -S "(localdb)\MSSQLLocalDB" -d dbname -i file.sql
shift
can be used in places where you want to get the first element (index=0
) of an array and chain with other array methods.
example:
const comps = [{}, {}, {}]
const specComp = comps
.map(fn1)
.filter(fn2)
.shift()
Remember shift
mutates the array, which is very different from accessing via an indexer.
dbms_output.put_line('Hi,');
dbms_output.put_line('good');
dbms_output.put_line('morning');
dbms_output.put_line('friends');
or
DBMS_OUTPUT.PUT_LINE('Hi, ' || CHR(13) || CHR(10) ||
'good' || CHR(13) || CHR(10) ||
'morning' || CHR(13) || CHR(10) ||
'friends' || CHR(13) || CHR(10) ||);
try it.
As was in my case if your sql is generated by concatenating or uses converts then sql at execute need to be prefixed with letter N as below
e.g.
Exec N'Select bla..'
the N defines string literal is unicode.
Because of the security enhancements in IE, you can't close a window unless it is opened by a script. So the way around this will be to let the browser think that this page is opened using a script, and then to close the window. Below is the implementation.
Try this, it works like a charm!
javascript close current window without prompt IE
<script type="text/javascript">
function closeWP() {
var Browser = navigator.appName;
var indexB = Browser.indexOf('Explorer');
if (indexB > 0) {
var indexV = navigator.userAgent.indexOf('MSIE') + 5;
var Version = navigator.userAgent.substring(indexV, indexV + 1);
if (Version >= 7) {
window.open('', '_self', '');
window.close();
}
else if (Version == 6) {
window.opener = null;
window.close();
}
else {
window.opener = '';
window.close();
}
}
else {
window.close();
}
}
</script>
for item in array: array2.append (item)
Or, in this case:
array2 += array
You can set the proxy in your app. This can be done using Settings class. For example you can add following line to your "onCreate" method.
Settings.System.putString(getContentResolver(), Settings.System.HTTP_PROXY, "myproxy:8080");
To change the proxy settings you have to have the android.permission.WRITE_SETTINGS permission in your AndroidManifest.xml file.
That code doesn't work very well i fixed it a little bit
var el = $('.caja-pago');
var elpos_original = el.offset().top;
$(window).scroll(function(){
var elpos = el.offset().top;
var windowpos = $(window).scrollTop();
var finaldestination = windowpos;
if(windowpos<elpos_original) {
finaldestination = elpos_original;
el.stop().animate({'top':400},500);
} else {
el.stop().animate({'top':windowpos+10},500);
}
});
You may need to go to Window -> Android SDK Manager -> Packages -> Reload to fetch latest updates and then update the SDK.
Assumption:
list - List<String>
Using Java 8 Streams,
to get first N elements from a list into a list,
List<String> firstNElementsList = list.stream().limit(n).collect(Collectors.toList());
to get first N elements from a list into an Array,
String[] firstNElementsArray = list.stream().limit(n).collect(Collectors.toList()).toArray(new String[n]);
DECLARE @theDate DATETIME
SET @theDate = '2010-01-01'
Then change your query to use this logic:
AND
(
tblWO.OrderDate > DATEADD(MILLISECOND, -1, @theDate)
AND tblWO.OrderDate < DATEADD(DAY, 1, @theDate)
)
ROWS UNBOUNDED PRECEDING
is no Teradata-specific syntax, it's Standard SQL. Together with the ORDER BY
it defines the window on which the result is calculated.
Logically a Windowed Aggregate Function is newly calculated for each row within the PARTITION based on all ROWS between a starting row and an ending row.
Starting and ending rows might be fixed or relative to the current row based on the following keywords:
Possible kinds of calculation include:
So SUM(x) OVER (ORDER BY col ROWS UNBOUNDED PRECEDING)
results in a Cumulative Sum or Running Total
11 -> 11
2 -> 11 + 2 = 13
3 -> 13 + 3 (or 11+2+3) = 16
44 -> 16 + 44 (or 11+2+3+44) = 60
print fast five maximum and minimum number from array without use of sorting array in php :-
<?php
$array = explode(',',"78, 60, 62, 68, 71, 68, 73, 85, 66, 64, 76, 63, 81, 76, 73,
68, 72, 73, 75, 65, 74, 63, 67, 65, 64, 68, 73, 75, 79, 73");
$t=0;
$l=count($array);
foreach($array as $v)
{
$t += $v;
}
$avg= $t/$l;
echo "average Temperature is : ".$avg." ";
echo "<br>List of seven highest temperatsures :-";
$m[0]= max($array);
for($i=1; $i <7 ; $i++)
{
$m[$i]=max(array_diff($array,$m));
}
foreach ($m as $key => $value) {
echo " ".$value;
}
echo "<br> List of seven lowest temperatures : ";
$mi[0]= min($array);
for($i=1; $i <7 ; $i++)
{
$mi[$i]=min(array_diff($array,$mi));
}
foreach ($mi as $key => $value) {
echo " ".$value;
}
?>
I had the same problem, also in my XCTestCase
files, but not in the regular project files.
To get rid of the:
Use of unresolved identifier 'PrimeNumberModel'
I needed to import
the base module in the test file. In my case, my target is called 'myproject' and I added import myproject
and the class was recognised.
Assume logs are already put to stdout/stderr, and have systemd unit's log in /var/log/syslog
journalctl -u unitxxx.service
Jun 30 13:51:46 host unitxxx[1437]: time="2018-06-30T11:51:46Z" level=info msg="127.0.0.1
Jun 30 15:02:15 host unitxxx[1437]: time="2018-06-30T13:02:15Z" level=info msg="127.0.0.1
Jun 30 15:33:02 host unitxxx[1437]: time="2018-06-30T13:33:02Z" level=info msg="127.0.0.1
Jun 30 15:56:31 host unitxxx[1437]: time="2018-06-30T13:56:31Z" level=info msg="127.0.0.1
Config rsyslog (System Logging Service)
# Create directory for log file
mkdir /var/log/unitxxx
# Then add config file /etc/rsyslog.d/unitxxx.conf
if $programname == 'unitxxx' then /var/log/unitxxx/unitxxx.log
& stop
Restart rsyslog
systemctl restart rsyslog.service
For Windows 7.1, these directions helped me to fix my build environment:
https://github.com/mongodb/js-bson/issues/58#issuecomment-68217275
http://christiankvalheim.com/post/diagnose_installation_problems/
An authority is a portion of a URI. Your error suggests that it was not expecting one. The authority section is shown below, it is what is known as the website part of the url.
From RFC3986 on URIs:
The following is an example URI and its component parts:
foo://example.com:8042/over/there?name=ferret#nose
\_/ \______________/\_________/ \_________/ \__/
| | | | |
scheme authority path query fragment
| _____________________|__
/ \ / \
urn:example:animal:ferret:nose
So there are two formats, one with an authority and one not. Regarding slashes:
"When authority is not present, the path cannot begin with two slash
characters ("//")."
Source: https://tools.ietf.org/rfc/rfc3986.txt (search for text 'authority is not present, the path cannot begin with two slash')
Try:
function is_numeric(str){
try {
return isFinite(str)
}
catch(err) {
return false
}
}
ES6 (fastest)
const a = ['a', 'b', 'c'];
const b = ['c', 'a', 'd'];
a.some(v=> b.indexOf(v) !== -1)
ES2016
const a = ['a', 'b', 'c'];
const b = ['c', 'a', 'd'];
a.some(v => b.includes(v));
Underscore
const a = ['a', 'b', 'c'];
const b = ['c', 'a', 'd'];
_.intersection(a, b)
DEMO: https://jsfiddle.net/r257wuv5/
jsPerf: https://jsperf.com/array-contains-any-element-of-another-array
The current answers are fine and should work ok, but what's wrong with the more simple, more obvious, and more maintainable:
IF @flag = 1
UPDATE table_name SET column_A = column_A + @new_value WHERE ID = @ID;
ELSE
UPDATE table_name SET column_B = column_B + @new_value WHERE ID = @ID;
This is much easier to read albeit this is a very simple query.
Here's a working example courtesy of @snyder: SqlFiddle.
I found this implementation very easy to use. Also has a generous BSD-style license:
jsSHA: https://github.com/Caligatio/jsSHA
I needed a quick way to get the hex-string representation of a SHA-256 hash. It only took 3 lines:
var sha256 = new jsSHA('SHA-256', 'TEXT');
sha256.update(some_string_variable_to_hash);
var hash = sha256.getHash("HEX");
Well one way to do it is set the height of your body to the height
that you want your page
to be. In this example I did 600px
.
Then set your wrapper
height to a percentage of the body here I did 70%
This will adjust your table so that it does not fill up the whole screen but in stead just takes up a percentage of the specified page height.
body {
padding-top: 70px;
border:1px solid black;
height:600px;
}
.mygrid-wrapper-div {
border: solid red 5px;
overflow: scroll;
height: 70%;
}
Update How about a jQuery approach.
$(function() {
var window_height = $(window).height(),
content_height = window_height - 200;
$('.mygrid-wrapper-div').height(content_height);
});
$( window ).resize(function() {
var window_height = $(window).height(),
content_height = window_height - 200;
$('.mygrid-wrapper-div').height(content_height);
});
If you need to focus some textbox and your only problem is that the entire text gets highlighted whereas you want the caret to be at the end, then in that specific case, you can use this trick of setting the textbox value to itself after focus:
$("#myinputfield").focus().val($("#myinputfield").val());
Please try below:
DECLARE @Today DATETIME;
SET @Today = '12/5/2007';
SET LANGUAGE Italian;
SELECT DATENAME(month, @Today) AS 'Month Name';
SET LANGUAGE us_english;
SELECT DATENAME(month, @Today) AS 'Month Name' ;
GO
Reference:
https://docs.microsoft.com/en-us/sql/t-sql/statements/set-language-transact-sql
There is no “universal” documentation that javascript caters to; every browser that has javascript is really an implementation. However, there is a standard that most modern browsers tend to follow, and that’s the EMCAScript standard; the ECMAScript standard strings would take, minimally, a modified implementation of the ISO 8601 definition.
In addition to this, there is a second standard set forward by the IETF that browsers tend to follow as well, which is the definition for timestamps made in the RFC 2822. Actual documentation can be found in the references list at the bottom.
From this you can expect basic functionality, but what “ought” to be is not inherently what “is”. I’m going to go a little in depth with this procedurally though, as it appears only three people actually answered the question (Scott, goofballLogic, and peller namely) which, to me, suggests most people are unaware of what actually happens when you create a Date object.
Where is the documentation which lists the format specifiers supported by the Date() object?
To answer the question, or typically even look for the answer to this question, you need to know that javascript is not a novel language; it’s actually an implementation of ECMAScript, and follows the ECMAScript standards (but note, javascript also actually pre-dated those standards; EMCAScript standards are built off the early implementation of LiveScript/JavaScript). The current ECMAScript standard is 5.1 (2011); at the time that the question was originally asked (June ’09), the standard was 3 (4 was abandoned), but 5 was released shortly after the post at the end of 2009. This should outline one problem; what standard a javascript implementation may follow, may not reflect what is actually in place, because a) it’s an implementation of a given standard, b) not all implementations of a standard are puritan, and c) functionality is not released in synchronization with a new standard as d) an implementation is a constant work in progress
Essentially, when dealing with javascript, you’re dealing with a derivative (javascript specific to the browser) of an implementation (javascript itself). Google’s V8, for example, implements ECMAScript 5.0, but Internet Explorer’s JScript doesn’t attempt to conform to any ECMAScript standard, yet Internet Explorer 9 does conform to ECMAScript 5.0.
When a single argument is passed to new Date(), it casts this function prototype:
new Date(value)
When two or more arguments are passed to new Date(), it casts this function prototype:
new Date (year, month [, date [, hours [, minutes [, seconds [, ms ] ] ] ] ] )
Both of those functions should look familiar, but this does not immediately answer your question and what quantifies as an acceptable “date format” requires further explanation. When you pass a string to new Date(), it will call the prototype (note that I'm using the word prototype loosely; the versions may be individual functions, or it may be part of a conditional statement in a single function) for new Date(value) with your string as the argument for the “value” parameter. This function will first check whether it is a number or a string. The documentation for this function can be found here:
http://www.ecma-international.org/ecma-262/5.1/#sec-15.9.3.2
From this, we can deduce that to get the string formatting allowed for new Date(value), we have to look at the method Date.parse(string). The documentation for this method can be found here:
http://www.ecma-international.org/ecma-262/5.1/#sec-15.9.4.2
And we can further infer that dates are expected to be in a modified ISO 8601 Extended Format, as specified here:
http://www.ecma-international.org/ecma-262/5.1/#sec-15.9.1.15
However, we can recognize from experience that javascript’s Date object accepts other formats (enforced by the existence of this question in the first place), and this is okay because ECMAScript allows for implementation specific formats. However, that still doesn’t answer the question of what documentation is available on the available formats, nor what formats are actually allowed. We’re going to look at Google’s javascript implementation, V8; please note I’m not suggesting this is the “best” javascript engine (how can one define “best” or even “good”) and one cannot assume that the formats allowed in V8 represent all formats available today, but I think it’s fair to assume they do follow modern expectations.
Google’s V8, date.js, DateConstructor
https://code.google.com/p/v8/source/browse/trunk/src/date.js?r=18400#141
Looking at the DateConstructor function, we can deduce we need to find the DateParse function; however, note that “year” is not the actual year and is only a reference to the “year” parameter.
Google’s V8, date.js, DateParse
https://code.google.com/p/v8/source/browse/trunk/src/date.js?r=18400#270
This calls %DateParseString, which is actually a run-time function reference for a C++ function. It refers to the following code:
Google’s V8, runtime.cc, %DateParseString
https://code.google.com/p/v8/source/browse/trunk/src/runtime.cc?r=18400#9559
The function call we’re concerned with in this function is for DateParser::Parse(); ignore the logic surrounding those function calls, these are just checks to conform to the encoding type (ASCII and UC16). DateParser::Parse is defined here:
Google's V8, dateparser-inl.h, DateParser::Parse
https://code.google.com/p/v8/source/browse/trunk/src/dateparser-inl.h?r=18400#36
This is the function that actually defines what formats it accepts. Essentially, it checks for the EMCAScript 5.0 ISO 8601 standard and if it is not standards compliant, then it will attempt to build the date based on legacy formats. A few key points based on the comments:
So this should be enough to give you a basic idea of what to expect when it comes to passing a string into a Date object. You can further expand upon this by looking at the following specification that Mozilla points to on the Mozilla Developer Network (compliant to the IETF RFC 2822 timestamps):
The Microsoft Developer Network additionally mentions an additional standard for the Date object: ECMA-402, the ECMAScript Internationalization API Specification, which is complementary to the ECMAScript 5.1 standard (and future ones). That can be found here:
In any case, this should aid in highlighting that there is no "documentation" that universally represents all implementations of javascript, but there is still enough documentation available to make reasonable sense of what strings are acceptable for a Date object. Quite the loaded question when you think about it, yes? :P
References
http://www.ecma-international.org/ecma-262/5.1/#sec-15.9.3.2
http://www.ecma-international.org/ecma-262/5.1/#sec-15.9.4.2
http://www.ecma-international.org/ecma-262/5.1/#sec-15.9.1.15
http://tools.ietf.org/html/rfc2822#page-14
http://www.ecma-international.org/ecma-402/1.0/
https://code.google.com/p/v8/source/browse/trunk/src/date.js?r=18400#141
https://code.google.com/p/v8/source/browse/trunk/src/date.js?r=18400#270
https://code.google.com/p/v8/source/browse/trunk/src/runtime.cc?r=18400#9559
https://code.google.com/p/v8/source/browse/trunk/src/dateparser-inl.h?r=18400#36
Resources
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date
http://msdn.microsoft.com/en-us/library/ff743760(v=vs.94).aspx
TL;DR To fix this issue, invoke packaging plugin before, e.g. for jar
packaging use maven-jar-plugin
, as following:
mvn jar:jar install:install
Or
mvn jar:jar deploy:deploy
If you actually needed to deploy.
Gotcha This approach won't work if you have multi-module project with different packagings (ear/war/jar/zip) – even worse, wrong artifacts will be installed/deployed! In such case use reactor options to only build the deployable module (e.g. the war
).
Explanation
In some cases you actually want to run directly a install:install
or deploy:deploy
goal (that is, from the maven-deploy-plugin
, the deploy
goal, not the Maven deploy
phase) and you would end up in the annoying The packaging for this project did not assign a file to the build artifact
.
A classic example is a CI job (a Jenkins or Bamboo job, e.g.) where in different steps you want to execute/care about different aspects:
mvn clean install
, performing tests and test coveragemvn sonar:sonar
plus further optionsmvn deploy
, because it would again execute previous phases (and compile, test, etc.) and you want your build to be effective but yet fast.Yes, you could speed up this last step at least skipping tests (compilation and execution, via -Dmaven.test.skip=true
) or play with a particular profile (to skip as many plugins as possible), but it is much easier and clear to simply run mvn deploy:deploy
then.
But it would fail with the error above, because as also specified by the plugin FAQ:
During the packaging-phase all gathered and placed in context. With this mechanism Maven can ensure that the
maven-install-plugin
andmaven-deploy-plugin
are copying/uploading the same set of files. So when you only executedeploy:deploy
, then there are no files put in the context and there is nothing to deploy.
Indeed, the deploy:deploy
needs some runtime information placed in the build context by previous phases (or previous plugins/goals executions).
It has also reported as a potential bug: MDEPLOY-158
: deploy:deploy does not work for only Deploying artifact to Maven Remote repo
But then rejected as not a problem.
The deployAtEnd
configuration option of the maven-deploy-plugin
won't help neither in certain scenarios because we have intermediate job steps to execute:
Whether every project should be deployed during its own deploy-phase or at the end of the multimodule build. If set to
true
and the build fails, none of the reactor projects is deployed. (experimental)
So, how to fix it?
Simply run the following in such a similar third/last step:
mvn jar:jar deploy:deploy
The maven-jar-plugin
will not re-create any jar as part of your build, thanks to its forceCreation
option set to false
by default:
Require the jar plugin to build a new JAR even if none of the contents appear to have changed. By default, this plugin looks to see if the output jar exists and inputs have not changed. If these conditions are true, the plugin skips creation of the jar.
But it will nicely populate the build context for us and make deploy:deploy
happy. No tests to skip, no profiles to add. Just what you need: speed.
Additional note: if you are using the build-helper-maven-plugin
, buildnumber-maven-plugin
or any other similar plugin to generate meta-data later on used by the maven-jar-plugin
(e.g. entries for the Manifest file), you most probably have executions linked to the validate
phase and you still want to have them during the jar:jar
build step (and yet keep a fast execution). In this case the almost harmless overhead is to invoke the validate
phase as following:
mvn validate jar:jar deploy:deploy
Yet another additional note: if you have not jar
but, say, war
packaging, use war:war
before install/deploy instead.
Gotcha as pointed out above, check behavior in multi module projects.
Comparing Java 7 and C# 3
(Some features of Java 7 aren't mentioned here, but the using
statement advantage of all versions of C# over Java 1-6 has been removed.)
Not all of your summary is correct:
Beyond that (and what's in your summary already):
List<byte>
as a byte[]
backing it, rather than an array of boxed bytes.)ref
and out
for passing parameters by referenceThis is not exhaustive, but it covers everything I can think of off-hand.
You can use smth like this:
val fragment = supportFragmentManager.fragmentFactory.instantiate(classLoader, YourFragment::class.java.name)
because this answer now is Deprecated
I would recommend to call the script like this
...
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script src="/js/my.js"></script>
</body>
The js and css files must be treat differently
Put
jquery
as the first before otherJS scripts
at the bottom of<BODY>
tag
HTTP/1.1 specification
suggests that browsers download no more than two components in parallel per hostname. <head>
tags and let the rest including the jquery
to be called on the bottom <body>
tag.Put
CSS style
on top of<HEAD>
tag after the other more priority tags
HEAD
makes pages appear to be loading faster. This is because putting style sheets in the HEAD
allows the page to render progressively.css
sheets, it is better to put them all on the <head>
tag but let the style that shall be immediately rendered to be put in <style>
tags inside <HEAD>
and the rest in <body>
.You may also find other suggestion when you test your page like on Google PageSpeed Insight
Some readers will have another issue and need this fix. read the links below. the same problem occured with visual studio 2015 with the advent of windows sdk 10 which brings up libucrt. ucrt is the windows implementation of C Runtime (CRT) aka the posix runtime library. You most likely have code that was ported from unix... Welcome to the drawback
https://github.com/lordmulder/libsndfile-MSVC/blob/master/src/sf_unistd.h
https://lists.gnu.org/archive/html/bug-gnulib/2011-09/msg00224.html
https://msdn.microsoft.com/en-us/library/y23kc048.aspx
https://blogs.msdn.microsoft.com/vcblog/2015/03/03/introducing-the-universal-crt/
Here is the extension method to load an image from URI:
public static BitmapImage GetBitmapImage(
this Uri imageAbsolutePath,
BitmapCacheOption bitmapCacheOption = BitmapCacheOption.Default)
{
BitmapImage image = new BitmapImage();
image.BeginInit();
image.CacheOption = bitmapCacheOption;
image.UriSource = imageAbsolutePath;
image.EndInit();
return image;
}
Sample of use:
Uri _imageUri = new Uri(imageAbsolutePath);
ImageXamlElement.Source = _imageUri.GetBitmapImage(BitmapCacheOption.OnLoad);
Simple as that!
Your DOS command 2> nul
Read page Using command redirection operators. Besides the "2>" construct mentioned by Tanuki Software, it lists some other useful combinations.
Simply put a file named favicon.ico
in the webroot.
If you want to know more, please start reading:
A combination of the few responses I've seen here. (Tested in FF, Chrome, IE11)
function functionName()
{
var myName = functionName.caller.toString();
myName = myName.substr('function '.length);
myName = myName.substr(0, myName.indexOf('('));
return myName;
}
function randomFunction(){
var proof = "This proves that I found the name '" + functionName() + "'";
alert(proof);
}
Calling randomFunction() will alert a string that contains the function name.
JS Fiddle Demo: http://jsfiddle.net/mjgqfhbe/
And if tools\android
works for you while .exe doesn't, it's probably the x64 java.
It started working when i completely uninstalled JDK with JRE (shows as separate option in windows uninstal control panel applet) and android sdk and reinstalled using x86 version.
Why does it worth the time, you may ask? Well, such an inconsistency obvoiusly means that amount of testing with x64 java is zero and so you can probably experience many other failures in the future.
If you're open to a PHP solution:
<td><img src='<?PHP
$path1 = "path/to/your/image.jpg";
$path2 = "alternate/path/to/another/image.jpg";
echo file_exists($path1) ? $path1 : $path2;
?>' alt='' />
</td>
////EDIT OK, here's a JS version:
<table><tr>
<td><img src='' id='myImage' /></td>
</tr></table>
<script type='text/javascript'>
document.getElementById('myImage').src = "newImage.png";
document.getElementById('myImage').onload = function() {
alert("done");
}
document.getElementById('myImage').onerror = function() {
alert("Inserting alternate");
document.getElementById('myImage').src = "alternate.png";
}
</script>
Let's break this down:
The error says
Cannot invoke an expression whose type lacks a call signature.
The code:
The problem is in this line public toggleBody: string;
&
it's relation to these lines:
...
return this.toggleBody(true);
...
return this.toggleBody(false);
Your saying toggleBody
is a string
but then your treating it like something that has a call signature
(i.e. the structure of something that can be called: lambdas, proc, functions, methods, etc. In JS just function tho.). You need to change the declaration to be public toggleBody: (arg: boolean) => boolean;
.
Extra Details:
"invoke" means your calling or applying a function.
"an expression" in Javascript is basically something that produces a value, so this.toggleBody()
counts as an expression.
"type" is declared on this line public toggleBody: string
"lacks a call signature" this is because your trying to call something this.toggleBody()
that doesn't have signature(i.e. the structure of something that can be called: lambdas, proc, functions, methods, etc.) that can be called. You said this.toggleBody
is something that acts like a string.
In other words the error is saying
Cannot call an expression (this.toggleBody) because it's type (:string) lacks a call signature (bc it has a string signature.)
I have some useful comments. Because I had similar problem with location of figures. I used package "wrapfig" that allows to make figures wrapped by text. Something like
...
\usepackage{wrapfig}
\usepackage{graphicx}
...
\begin{wrapfigure}{r}{53pt}
\includegraphics[width=53pt]{cone.pdf}
\end{wrapfigure}
In options {r}
means to put figure from right side. {l}
can be use for left side.
Use the -o ConnectTimeout
and -o BatchMode=yes -o StrictHostKeyChecking=no
.
ConnectTimeout keeps the script from hanging, BatchMode keeps it from hanging with Host unknown, YES to add to known_hosts, and StrictHostKeyChecking adds the fingerprint automatically.
**** NOTE **** The "StrictHostKeyChecking" was only intended for internal networks where you trust you hosts. Depending on the version of the SSH client, the "Are you sure you want to add your fingerprint" can cause the client to hang indefinitely (mainly old versions running on AIX). Most modern versions do not suffer from this issue. If you have to deal with fingerprints with multiple hosts, I recommend maintaining the known_hosts file with some sort of configuration management tool like puppet/ansible/chef/salt/etc.
For me it works like this
Rotate clockwise
ffmpeg -i "path_source_video.mp4" -filter:v "transpose=1" "path_output_video.mp4"
Rotate counterclockwise
ffmpeg -i "path_source_video.mp4" -filter:v "transpose=0,transpose=1,transpose=0" -acodec copy "path_output_video.mp4"
the package I use zeranoe
I had the same problem under Windows and could solve it by running cmd.exe as administrator (right-click in start menu, then "Run as administrator).
If you want to get any element that has part of a URL in their href attribute you could use:
$( 'a[href*="google.com"]' );
This will select all elements with a href that contains google.com, for example:
As stated by @BalusC in the comments below, it will also match elements that have google.com
at any position in the href, like blahgoogle.com
.
Well, depending on your needs you can choose any of the following. Out put is written against each method
You can choose the one you need
This will round
decimal d = 2.5789m;
Console.WriteLine(d.ToString("#.##")); // 2.58
This will ensure that 2 decimal places are written.
d = 2.5m;
Console.WriteLine(d.ToString("F")); //2.50
if you want to write commas you can use this
d=23545789.5432m;
Console.WriteLine(d.ToString("n2")); //23,545,789.54
if you want to return the rounded of decimal value you can do this
d = 2.578m;
d = decimal.Round(d, 2, MidpointRounding.AwayFromZero); //2.58
Use the modulo operator:
if wordLength % 2 == 0:
print "wordLength is even"
else:
print "wordLength is odd"
For your problem, the simplest is to check if the word is equal to its reversed brother. You can do that with word[::-1]
, which create the list from word
by taking every character from the end to the start:
def is_palindrome(word):
return word == word[::-1]
Using your example dataframe, we could:
xtabs(value ~ name + numbers, data = dat1)
If you only need to show time value in a datagrid or label similar, best way is convert directly time in datetime datatype.
SELECT CONVERT(datetime,myTimeField) as myTimeField FROM Table1
Perhaps you would accomplish this with something to the effect of
text = raw_input("please give 2 numbers to multiply separated with a comma:")
split_text = text.split(',')
a = int(split_text[0])
b = int(split_text[1])
# The last three lines could be written: a, b = map(int, text.split(','))
# but you may find the code I used a bit easier to understand for now.
if b > 0:
num_times = b
else:
num_times = -b
total = 0
# While loops with counters basically should not be used, so I replaced the loop
# with a for loop. Using a while loop at all is rare.
for i in xrange(num_times):
total += a
# We do this a times, giving us total == a * abs(b)
if b < 0:
# If b is negative, adjust the total to reflect this.
total = -total
print total
or maybe
a * b
Most of the answers here are using built-in methods or using libraries/frameworks. This simple method should work fine:
function copy(x) {
return JSON.parse( JSON.stringify(x) );
}
// Usage
var a = 'some';
var b = copy(a);
a += 'thing';
console.log(b); // "some"
var c = { x: 1 };
var d = copy(c);
c.x = 2;
console.log(d); // { x: 1 }
This feature is known as generics. http://msdn.microsoft.com/en-us/library/512aeb7t(v=vs.100).aspx
An example of this is to make a collection of items of a specific type.
class MyArray<T>
{
T[] array = new T[10];
public T GetItem(int index)
{
return array[index];
}
}
In your code, you could then do something like this:
MyArray<int> = new MyArray<int>();
In this case, T[] array
would work like int[] array
, and public T GetItem
would work like public int GetItem
.
Give hibernate.connection.url
as "jdbc:oracle:thin:@127.0.0.1:1521:xe"
then you can solve above issue. Because oracle's default SID is "xe" so we should give like this. When I gave like this data has been inserted into DB without any SQL exceptions, it's my real time experience.
You can use ARG
- see https://docs.docker.com/engine/reference/builder/#arg
The
ARG
instruction defines a variable that users can pass at build-time to the builder with thedocker build
command using the--build-arg <varname>=<value>
flag. If a user specifies a build argument that was not defined in the Dockerfile, the build outputs an error.
From JLS http://docs.oracle.com/javase/specs/jls/se5.0/html/arrays.html#10.2
Here are examples of declarations of array variables that do not create arrays:
int[ ] ai; // array of int
short[ ][ ] as; // array of array of short
Object[ ] ao, // array of Object
otherAo; // array of Object
Collection<?>[ ] ca; // array of Collection of unknown type
short s, // scalar short
aas[ ][ ]; // array of array of short
Here are some examples of declarations of array variables that create array objects:
Exception ae[ ] = new Exception[3];
Object aao[ ][ ] = new Exception[2][3];
int[ ] factorial = { 1, 1, 2, 6, 24, 120, 720, 5040 };
char ac[ ] = { 'n', 'o', 't', ' ', 'a', ' ',
'S', 't', 'r', 'i', 'n', 'g' };
String[ ] aas = { "array", "of", "String", };
The [ ] may appear as part of the type at the beginning of the declaration, or as part of the declarator for a particular variable, or both, as in this example:
byte[ ] rowvector, colvector, matrix[ ];
This declaration is equivalent to:
byte rowvector[ ], colvector[ ], matrix[ ][ ];
Does it mean that I'm blocking reading any input from the Server/Client for this socket for 2000 millisecond and after this time the socket is ready to read data?
No, it means that if no data arrives within 2000ms a SocketTimeoutException
will be thrown.
What does it mean timeout expire?
It means the 2000ms (in your case) elapses without any data arriving.
What is the option which must be enabled prior to blocking operation?
There isn't one that 'must be' enabled. If you mean 'may be enabled', this is one of them.
Infinite Timeout menas that the socket does't read anymore?
What a strange suggestion. It means that if no data ever arrives you will block in the read forever.
To set a title for a button in Xcode using swift - 04: first create a method called setTitle with parameter title and UIController state like below ;
func setTitle(_ title : String?, for state : UIControl.State) {
}
and recall this method in your button action method like ;
yourButtonName.setTitle("String", for: .state)
In a very simple words any value which has a definite size can be treated as a value type.
For me none worked. I compared my existing eclipse.ini
with a new one and started removing options and testing if eclipse worked.
The only option that prevented eclipse from starting was -XX:+UseParallelGC
, so I removed it and voilá!
Resolved by adding the missing component Modify->continue add as follow
As Peter already pointed out:
In [1]: import requests
In [2]: r = requests.get('https://api.github.com/events')
In [3]: type(r)
Out[3]: requests.models.Response
In [4]: type(r.content)
Out[4]: str
You may also want to check r.text
.
Also: https://2.python-requests.org/en/latest/user/quickstart/
I've just solved this problem on a site I'm working on, and thought I would share it in the hope it helps someone.
My solution takes the distance from the footer to the top of the page - if the user has scrolled further than this, it pulls the sidebar back up with a negative margin.
$(window).scroll(() => {
// Distance from top of document to top of footer.
topOfFooter = $('#footer').position().top;
// Distance user has scrolled from top, adjusted to take in height of sidebar (570 pixels inc. padding).
scrollDistanceFromTopOfDoc = $(document).scrollTop() + 570;
// Difference between the two.
scrollDistanceFromTopOfFooter = scrollDistanceFromTopOfDoc - topOfFooter;
// If user has scrolled further than footer,
// pull sidebar up using a negative margin.
if (scrollDistanceFromTopOfDoc > topOfFooter) {
$('#cart').css('margin-top', 0 - scrollDistanceFromTopOfFooter);
} else {
$('#cart').css('margin-top', 0);
}
});
echo "12|23|11" | awk '{split($0,a,"|"); print a[3] a[2] a[1]}'
If you are providing mappings like this:
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Configurations.Add(new ClassificationMap());
modelBuilder.Configurations.Add(new CompanyMap());
modelBuilder.Configurations.Add(new GroupMap());
....
}
Remember to add the map for BaseCs.
You won't get a compile error if it is missing. But you will get a runtime error when you use the entity.
Here's another way of doing the code above using the openpyxl
module that's compatible with xlsx. From what I've seen so far, it also keeps formatting.
from openpyxl import load_workbook
wb = load_workbook('names.xlsx')
ws = wb['SheetName']
ws['A1'] = 'A1'
wb.save('names.xlsx')
According to the docs numpy.loadtxt
is
a fast reader for simply formatted files. The genfromtxt function provides more sophisticated handling of, e.g., lines with missing values.
so there are only a few options to handle more complicated files.
As mentioned numpy.genfromtxt
has more options. So as an example you could use
import numpy as np
data = np.genfromtxt('e:\dir1\datafile.csv', delimiter=',', skip_header=10,
skip_footer=10, names=['x', 'y', 'z'])
to read the data and assign names to the columns (or read a header line from the file with names=True
) and than plot it with
ax1.plot(data['x'], data['y'], color='r', label='the data')
I think numpy is quite well documented now. You can easily inspect the docstrings from within ipython
or by using an IDE like spider
if you prefer to read them rendered as HTML.
I was able to absolutely position a right-floated element with one layer of nesting and a tricky margin:
function test() {_x000D_
document.getElementById("box").classList.toggle("hide");_x000D_
}
_x000D_
.right {_x000D_
float:right;_x000D_
}_x000D_
#box {_x000D_
position:absolute; background:#feb;_x000D_
width:20em; margin-left:-20em; padding:1ex;_x000D_
}_x000D_
#box.hide {_x000D_
display:none;_x000D_
}
_x000D_
<div>_x000D_
<div class="right">_x000D_
<button onclick="test()">box</button>_x000D_
<div id="box">Lorem ipsum dolor sit amet, consectetur adipiscing elit,_x000D_
sed do eiusmod tempor incididunt ut labore et dolore magna aliqua._x000D_
Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris_x000D_
nisi ut aliquip ex ea commodo consequat._x000D_
</div>_x000D_
</div>_x000D_
<p>_x000D_
Lorem ipsum dolor sit amet, consectetur adipiscing elit,_x000D_
sed do eiusmod tempor incididunt ut labore et dolore magna aliqua._x000D_
Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris_x000D_
nisi ut aliquip ex ea commodo consequat._x000D_
</p>_x000D_
</div>
_x000D_
I decided to make this toggleable so you can see how it does not affect the flow of the surrounding text (run it and press the button to show/hide the floated absolute box).
You could also use countplot
from seaborn
. This package builds on pandas
to create a high level plotting interface. It gives you good styling and correct axis labels for free.
import pandas as pd
import seaborn as sns
sns.set()
df = pd.DataFrame({'colour': ['red', 'blue', 'green', 'red', 'red', 'yellow', 'blue'],
'direction': ['up', 'up', 'down', 'left', 'right', 'down', 'down']})
sns.countplot(df['colour'], color='gray')
It also supports coloring the bars in the right color with a little trick
sns.countplot(df['colour'],
palette={color: color for color in df['colour'].unique()})
There is an option without additional packages that works under pdflatex
Adapt this code
\begin{figure}[h]
\centering
\includegraphics[width=\ScaleIfNeeded]{figuras/diagrama-spearman.pdf}
\caption{Schematical view of Spearman's theory.}
\end{figure}
"diagrama-spearman.pdf" is a plot generated with TikZ and this is the code (it is another .tex file different from the .tex file where I want to insert a pdf)
\documentclass[border=3mm]{standalone}
\usepackage[applemac]{inputenc}
\usepackage[protrusion=true,expansion=true]{microtype}
\usepackage[bb=lucida,bbscaled=1,cal=boondoxo]{mathalfa}
\usepackage[stdmathitalics=true,math-style=iso,lucidasmallscale=true,romanfamily=bright]{lucimatx}
\usepackage{tikz}
\usetikzlibrary{intersections}
\newcommand{\at}{\makeatletter @\makeatother}
\begin{document}
\begin{tikzpicture}
\tikzset{venn circle/.style={draw,circle,minimum width=5cm,fill=#1,opacity=1}}
\node [venn circle = none, name path=A] (A) at (45:2cm) { };
\node [venn circle = none, name path=B] (B) at (135:2cm) { };
\node [venn circle = none, name path=C] (C) at (225:2cm) { };
\node [venn circle = none, name path=D] (D) at (315:2cm) { };
\node[above right] at (barycentric cs:A=1) {logical};
\node[above left] at (barycentric cs:B=1) {mechanical};
\node[below left] at (barycentric cs:C=1) {spatial};
\node[below right] at (barycentric cs:D=1) {arithmetical};
\node at (0,0) {G};
\end{tikzpicture}
\end{document}
This is the diagram I included
Just select from the Visual Studio menu View- > ToolBox .
How about:
if (regexMatcher.find()) {
resultString = regexMatcher.replaceAll(
String.valueOf(3 * Integer.parseInt(regexMatcher.group(1))));
}
To get the first match, use #find()
. After that, you can use #group(1)
to refer to this first match, and replace all matches by the first maches value multiplied by 3.
And in case you want to replace each match with that match's value multiplied by 3:
Pattern p = Pattern.compile("(\\d{1,2})");
Matcher m = p.matcher("12 54 1 65");
StringBuffer s = new StringBuffer();
while (m.find())
m.appendReplacement(s, String.valueOf(3 * Integer.parseInt(m.group(1))));
System.out.println(s.toString());
You may want to look through Matcher
's documentation, where this and a lot more stuff is covered in detail.
The link you gave does actually describe the differences, but it's buried at the bottom of the page:
http://www.cplusplus.com/reference/cstdio/fopen/
Text files are files containing sequences of lines of text. Depending on the environment where the application runs, some special character conversion may occur in input/output operations in text mode to adapt them to a system-specific text file format. Although on some environments no conversions occur and both text files and binary files are treated the same way, using the appropriate mode improves portability.
The conversion could be to normalize \r\n
to \n
(or vice-versa), or maybe ignoring characters beyond 0x7F (a-la 'text mode' in FTP). Personally I'd open everything in binary-mode and use a good text-encoding library for dealing with text.
I guess this may work, in Eclipse select your project ? then click on project menu bar on top ? goto to properties ? click on Targeted Runtimes ? now you must select a check box next to the server you are using to run current project ? click Apply ? then click OK button. That's it, give a try.
One-liner that does not change given array.
a[0].map((col, i) => a.map(([...row]) => row[i]))
You could also do something as follow
public enum DAY {MON, TUES, WED, THU, FRI, SAT, SUN};
EnumSet.allOf(DAY.class).stream().map(e -> e.name()).collect(Collectors.toList())
or
EnumSet.allOf(DAY.class).stream().map(DAY::name).collect(Collectors.toList())
The main reason why I stumbled across this question is that I wanted to write a generic validator that validates whether a given string enum name is valid for a given enum type (Sharing in case anyone finds useful).
For the validation, I had to use Apache's EnumUtils
library since the type of enum is not known at compile time.
@SuppressWarnings({ "unchecked", "rawtypes" })
public static void isValidEnumsValid(Class clazz, Set<String> enumNames) {
Set<String> notAllowedNames = enumNames.stream()
.filter(enumName -> !EnumUtils.isValidEnum(clazz, enumName))
.collect(Collectors.toSet());
if (notAllowedNames.size() > 0) {
String validEnumNames = (String) EnumUtils.getEnumMap(clazz).keySet().stream()
.collect(Collectors.joining(", "));
throw new IllegalArgumentException("The requested values '" + notAllowedNames.stream()
.collect(Collectors.joining(",")) + "' are not valid. Please select one more (case-sensitive) "
+ "of the following : " + validEnumNames);
}
}
I was too lazy to write an enum annotation validator as shown in here https://stackoverflow.com/a/51109419/1225551
The equivalent is:
python3 -m http.server
it works perfectly for me :
document.getElementById('iframe_id').contentWindow.document.body.innerHTML;
It sort of depends on what that large block is. Maybe you just mean to delete a paragraph in which case a dip would do.
So you have committed your local changes to your local repository. Then in order to get remote changes to your local repository without making changes to your local files, you can use git fetch
. Actually git pull
is a two step operation: a non-destructive git fetch
followed by a git merge
. See What is the difference between 'git pull' and 'git fetch'? for more discussion.
Detailed example:
Suppose your repository is like this (you've made changes test2
:
* ed0bcb2 - (HEAD, master) test2
* 4942854 - (origin/master, origin/HEAD) first
And the origin
repository is like this (someone else has committed test1
):
* 5437ca5 - (HEAD, master) test1
* 4942854 - first
At this point of time, git will complain and ask you to pull first if you try to push your test2
to remote repository. If you want to see what test1 is without modifying your local repository, run this:
$ git fetch
Your result local repository would be like this:
* ed0bcb2 - (HEAD, master) test2
| * 5437ca5 - (origin/master, origin/HEAD) test1
|/
* 4942854 - first
Now you have the remote changes in another branch, and you keep your local files intact.
Then what's next? You can do a git merge
, which will be the same effect as git pull
(when combined with the previous git fetch
), or, as I would prefer, do a git rebase origin/master
to apply your change on top of origin/master
, which gives you a cleaner history.
I have some experience at recovering from eclipse when it becomes unstartable for whatever reason, could these blog entries help you?
link (archived)
also search for "cannot start eclipse" (I am a new user, I can only post a single hyperlink, so I have to just ask that you search for the second :( sorry)
perhaps those allow you to recover your workspace as well, I hope it helps.
You can do This :
$("#td_id").removeClass('Old_class');
$("#td_id").addClass('New_class');
Or You can do This
$("#td_id").removeClass('Old_class').addClass('New_class');
In regards to the "at the same time" definition of synchronous execution (which is sometimes confusing), here's a good way to understand it:
Synchronous Execution: All tasks within a block of code are all executed at the same time.
Asynchronous Execution: All tasks within a block of code are not all executed at the same time.
As said, to follow redirects you can use the flag -L
or --location
:
curl -L http://www.example.com
But, if you want limit the number of redirects, add the parameter --max-redirs
--max-redirs <num>
Set maximum number of redirection-followings allowed. If
-L
,--location
is used, this option can be used to prevent curl from following redirections "in absurdum". By default, the limit is set to 50 redirections. Set this option to -1 to make it limitless. If this option is used several times, the last one will be used.
To read a file from internal storage:
Call openFileInput() and pass it the name of the file to read. This returns a FileInputStream. Read bytes from the file with read(). Then close the stream with close().
code::
StringBuilder sb = new StringBuilder();
try{
BufferedReader reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line).append("\n");
}
is.close();
} catch(OutOfMemoryError om){
om.printStackTrace();
} catch(Exception ex){
ex.printStackTrace();
}
String result = sb.toString();
Try this one line code it worked for me like charm:
var data = (store.getData().getSource() || store.getData()).getRange();
git log --format="%h" | tail -1
gives you the commit hash (ie 0dd89fb
), which you can feed into other commands, by doing something like
git diff `git log --format="%h" --after="1 day"| tail -1`..HEAD
to view all the commits in the last day.
Everybody jumped on this one!!! I too made a fiddle:
http://jsfiddle.net/audetwebdesign/kh4aR/
RobAgar gets a point for pointing out white-space:nowrap
first.
Couple of things here, you need overflow: hidden
if you don't want to see the extra characters poking out into your layout.
Also, as mentioned, you could use white-space: pre
(see EnderMB) keeping in mind that pre
will not collapse white space whereas white-space: nowrap
will.
My solution is based on @Martijn Pieters' comment:
register_namespace
only influences serialisation, not search.
So the trick here is to use different dictionaries for serialization and for searching.
namespaces = {
'': 'http://www.example.com/default-schema',
'spec': 'http://www.example.com/specialized-schema',
}
Now, register all namespaces for parsing and writing:
for name, value in namespaces.iteritems():
ET.register_namespace(name, value)
For searching (find()
, findall()
, iterfind()
) we need a non-empty prefix. Pass these functions a modified dictionary (here I modify the original dictionary, but this must be made only after the namespaces are registered).
self.namespaces['default'] = self.namespaces['']
Now, the functions from the find()
family can be used with the default
prefix:
print root.find('default:myelem', namespaces)
but
tree.write(destination)
does not use any prefixes for elements in the default namespace.
Use this one to change only font size not the name of the font
label1.Font = new System.Drawing.Font(label1.Font.Name, 24F);
You don't need to use GROUP BY but using it won't change the outcome. Just add an ORDER BY line at the end to sort your results.
SELECT player_name, player_salary, SUM(player_salary*1.1) AS NewSalary
FROM players
GROUP BY player_salary, player_name;
ORDER BY SUM(player_salary*1.1) DESC
First off, you shouldn't add $
when you're outside of strings ($class
in your first function being an exception), so it should be:
def doCopyMibArtefactsHere(projectName) {
step ([
$class: 'CopyArtifact',
projectName: projectName,
filter: '**/**.mib',
fingerprintArtifacts: true,
flatten: true
]);
}
def BuildAndCopyMibsHere(projectName, params) {
build job: project, parameters: params
doCopyMibArtefactsHere(projectName)
}
...
Now, as for your problem; the second function takes two arguments while you're only supplying one argument at the call. Either you have to supply two arguments at the call:
...
node {
stage('Prepare Mib'){
BuildAndCopyMibsHere('project1', null)
}
}
... or you need to add a default value to the functions' second argument:
def BuildAndCopyMibsHere(projectName, params = null) {
build job: project, parameters: params
doCopyMibArtefactsHere($projectName)
}
if you use Bootstrap 2.2.1 then maybe is this what you are looking for.
Sample file index.html
<!DOCTYPE html>_x000D_
<html xmlns="http://www.w3.org/1999/xhtml">_x000D_
<head>_x000D_
<title></title>_x000D_
<link href="Content/bootstrap.min.css" rel="stylesheet" />_x000D_
<link href="Content/Site.css" rel="stylesheet" />_x000D_
</head>_x000D_
<body>_x000D_
<menu>_x000D_
<div class="navbar navbar-default navbar-fixed-top">_x000D_
<div class="container">_x000D_
<div class="navbar-header">_x000D_
<button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">_x000D_
<span class="icon-bar"></span>_x000D_
<span class="icon-bar"></span>_x000D_
<span class="icon-bar"></span>_x000D_
</button>_x000D_
<a class="navbar-brand" href="/">Application name</a>_x000D_
</div>_x000D_
<div class="navbar-collapse collapse">_x000D_
<ul class="nav navbar-nav">_x000D_
<li><a href="/">Home</a></li>_x000D_
<li><a href="/Home/About">About</a></li>_x000D_
<li><a href="/Home/Contact">Contact</a></li>_x000D_
</ul>_x000D_
<ul class="nav navbar-nav navbar-right">_x000D_
<li><a href="/Account/Register" id="registerLink">Register</a></li>_x000D_
<li><a href="/Account/Login" id="loginLink">Log in</a></li>_x000D_
</ul>_x000D_
_x000D_
</div>_x000D_
</div>_x000D_
</div>_x000D_
</menu>_x000D_
_x000D_
<nav>_x000D_
<div class="col-md-2">_x000D_
<a href="#" class="btn btn-block btn-info">Some Menu</a>_x000D_
<a href="#" class="btn btn-block btn-info">Some Menu</a>_x000D_
<a href="#" class="btn btn-block btn-info">Some Menu</a>_x000D_
<a href="#" class="btn btn-block btn-info">Some Menu</a>_x000D_
</div>_x000D_
_x000D_
</nav>_x000D_
<content>_x000D_
<div class="col-md-10">_x000D_
_x000D_
<h2>About.</h2>_x000D_
<h3>Your application description page.</h3>_x000D_
<p>Use this area to provide additional information.</p>_x000D_
<p>Use this area to provide additional information.</p>_x000D_
<p>Use this area to provide additional information.</p>_x000D_
<p>Use this area to provide additional information.</p>_x000D_
<p>Use this area to provide additional information.</p>_x000D_
<p>Use this area to provide additional information.</p>_x000D_
<hr />_x000D_
</div>_x000D_
</content>_x000D_
_x000D_
<footer>_x000D_
<div class="navbar navbar-default navbar-fixed-bottom">_x000D_
<div class="container" style="font-size: .8em">_x000D_
<p class="navbar-text">_x000D_
© Some info_x000D_
</p>_x000D_
</div>_x000D_
</div>_x000D_
</footer>_x000D_
_x000D_
</body>_x000D_
</html>
_x000D_
body {_x000D_
padding-bottom: 70px;_x000D_
padding-top: 70px;_x000D_
}
_x000D_
The main reason was first event's last access time was current time(file write or changed time). then second event was file's original last access time. I solve under code.
var lastRead = DateTime.MinValue;
Watcher = new FileSystemWatcher(...)
{
NotifyFilter = NotifyFilters.FileName | NotifyFilters.LastWrite,
Filter = "*.dll",
IncludeSubdirectories = false,
};
Watcher.Changed += (senderObject, ea) =>
{
var now = DateTime.Now;
var lastWriteTime = File.GetLastWriteTime(ea.FullPath);
if (now == lastWriteTime)
{
return;
}
if (lastWriteTime != lastRead)
{
// do something...
lastRead = lastWriteTime;
}
};
Watcher.EnableRaisingEvents = true;
hash[key]=value Associates the value given by value with the key given by key.
hash[:newKey] = "newValue"
From Ruby documentation: http://www.tutorialspoint.com/ruby/ruby_hashes.htm
Simply:
try {
const cmd = 'git rev-parse --is-inside-work-tree';
execSync(cmd).toString();
} catch (error) {
console.log(`Status Code: ${error.status} with '${error.message}'`;
}
Ref: https://stackoverflow.com/a/43077917/104085
// nodejs
var execSync = require('child_process').execSync;
// typescript
const { execSync } = require("child_process");
try {
const cmd = 'git rev-parse --is-inside-work-tree';
execSync(cmd).toString();
} catch (error) {
error.status; // 0 : successful exit, but here in exception it has to be greater than 0
error.message; // Holds the message you typically want.
error.stderr; // Holds the stderr output. Use `.toString()`.
error.stdout; // Holds the stdout output. Use `.toString()`.
}
Threads do not really have return values. However, if you create a delegate, you can invoke it asynchronously via the BeginInvoke
method. This will execute the method on a thread pool thread. You can get any return value from such as call via EndInvoke
.
Example:
static int GetAnswer() {
return 42;
}
...
Func<int> method = GetAnswer;
var res = method.BeginInvoke(null, null); // provide args as needed
var answer = method.EndInvoke(res);
GetAnswer
will execute on a thread pool thread and when completed you can retrieve the answer via EndInvoke
as shown.
Just another approach:
SELECT col1 * 1.0 / col2 FROM tbl1
Multiplying by 1.0 turns an integer into a float numeric(13,1) and so works like a typecast, but most probably it is slower than that.
A slightly shorter variation suggested by Aleksandr Fedorenko in a comment:
SELECT col1 * 1. / col2 FROM tbl1
The effect would be basically the same. The only difference is that the multiplication result in this case would be numeric(12,0).
Principal advantage: less wordy than other approaches.
Personally, I like to use named entities when they are available, because they make my HTML more readable. Because of that, I like to use ✓
for ✓ and ✗
for ✗. If you're not sure whether a named entity exists for the character you want, try the &what search site. It includes the name for each entity, if there is one.
As mentioned in the comments, ✓
and ✗
are not supported in HTML4, so you may be better off using the more cryptic ✓
and ✗
if you want to target the most browsers. The most definitive references I could find were on the W3C site: HTML4 and HTML5.
The following solution worked well for me. Navigate to the command prompt shortcut in the start menu:
C:\Users\ your username \AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Accessories\Command Prompt
Right click on the shortcut file to open the properties dialog. Inside the "Start in:" textbox you should see %HOMEDRIVE%%HOMEPATH%. If you want the prompt to start in C:\ just replace the variables with "C:\" (without quotes).
update
It appears that Microsoft has changed this behavior recently and so now an additional step is required. After performing the steps above copy the modified shortcut "Command Prompt" and rename it to "cmd". Then when typing "cmd" in the start menu it should once again work.
You're only adding the File object to the JSON object. The File object only contains meta information about the file: Path, name and so on.
You must load the image and read the bytes from it. Then put these bytes into the JSON object.
With the Material Components Library you can use the LinearProgressIndicator
with the app:indicatorColor
attribute to change the color:
<com.google.android.material.progressindicator.LinearProgressIndicator
app:indicatorColor="@color/..."
app:trackThickness="..."
app:trackColor="@color/..."
/>
Note: it requires at least the version 1.3.0-alpha04
.
With the ProgressBar
you can override the color using:
<ProgressBar
android:theme="@style/CustomProgressBarTheme"
..>
with:
<style name="CustomProgressBarTheme">
<item name="colorAccent">@color/primaryDarkColor</item>
</style>
By default any files you add to src/main/resources
will be included in the jar.
If you need to change that behavior for whatever reason, you can do so by configuring sourceSets
.
This part of the documentation has all the details
you can use :
git clone <url> --branch <branch>
to clone/download only the contents of the branch.
This was helpful to me especially, since the contents of my branch were entirely different from the master branch (though this is not usually the case). Hence, the suggestions listed by others above didn't help me and I would end up getting a copy of the master even after I checked out the branch and did a git pull.
This command would directly give you the contents of the branch. It worked for me.
This should solve your problem:
select replace(to_char(a, '90D90'),'.00','')
from
(
select 50 a from dual
union
select 50.57 from dual
union
select 5.57 from dual
union
select 0.35 from dual
union
select 0.4 from dual
);
Give a look also as this SQL Fiddle for test.
We can directly specify the destination file with the dest
option now. In the below example, the output json is stored into the /tmp/repo_version_file
- name: Get repository file repo_version model to set ambari_managed_repositories=false
uri:
url: 'http://<server IP>:8080/api/v1/stacks/HDP/versions/3.1/repository_versions/1?fields=operating_systems/*'
method: GET
force_basic_auth: yes
user: xxxxx
password: xxxxx
headers:
"X-Requested-By": "ambari"
"Content-type": "Application/json"
status_code: 200
dest: /tmp/repo_version_file
Amazon's CloudFront content delivery network can now be configured to pass this information through as a header. Given Amazon's size (they're big and stable, not going anywhere) and this is configuration over code (no third-party API to learn or code to maintain), all around believe this to be the best option.
If you do not use AWS CloudFront, I'd look into seeing if your CDN has a similar header option that can be turned on. Usually the large providers are quick to push for feature parity. And if you are not using a CDN, you could put CloudFront in front of your infrastructure and simply set the origin to resolve to whatever you are currently using.
Additionally, it also makes sense to resolve this at the CDN level. Your CDN is already having to figure out geo location to route the user to the nearest content node, might as well pass this information along and not figure it out twice through a third party API (this becomes chokepoint for your app, waiting for a geo location lookup to resolve). No need to do this work twice (and the second time, arguably less resilient [e.g., 3rd party geo lookup]).
https://aws.amazon.com/blogs/aws/enhanced-cloudfront-customization/
Geo-Targeting – CloudFront will detect the user’s country of origin and pass along the county code to you in the
CloudFront-Viewer-Country
header. You can use this information to customize your responses without having to use URLs that are specific to each country.
setBackgroundResource(0)
is the best option. From the documentation:
Set the background to a given resource. The resource should refer to a Drawable object or 0 to remove the background.
It works everywhere, because it's since API 1.
setBackground
was added much later, in API 16, so it will not work if your minSdkVersion
is lower than 16.
I think the difference between the two boils down to access. Environment variables are accessible by any process and Java system properties are only accessible by the process they are added to.
Also as Bohemian stated, env variables are set in the OS (however they 'can' be set through Java) and system properties are passed as command line options or set via setProperty()
.
Yes, it is because you are using auto layout. Setting the view frame and resizing mask will not work.
You should read Working with Auto Layout Programmatically and Visual Format Language.
You will need to get the current constraints, add the text field, adjust the contraints for the text field, then add the correct constraints on the text field.
In addition to rupello's excellent answer, a "dirty" but very effective trick:
For all phones, any (local) network: Set up your PC to Man-In-The-Middle your mobile device.
Use Ettercap to do ARP spoofing between your mobile device and your router, and all your mobile's traffic will appear in Wireshark. See this tutorial for set-up details
well, why don't you (get rid of sidebar and) squeeze the table so it is without show/hide effect? It looks odd to me now. The table is too robust.
Otherwise I think scunliffe's suggestion should do it. Or if you wish, you can just set the exact width of table and set either percentage or pixel width for table cells.
Use the load
event:
img = new Image();
img.onload = function(){
// image has been loaded
};
img.src = image_url;
Also have a look at:
Don't use the classes in thejava.io
package, instead use the java.nio
package . The latter has a FileLock
class. You can apply a lock to a FileChannel
.
try {
// Get a file channel for the file
File file = new File("filename");
FileChannel channel = new RandomAccessFile(file, "rw").getChannel();
// Use the file channel to create a lock on the file.
// This method blocks until it can retrieve the lock.
FileLock lock = channel.lock();
/*
use channel.lock OR channel.tryLock();
*/
// Try acquiring the lock without blocking. This method returns
// null or throws an exception if the file is already locked.
try {
lock = channel.tryLock();
} catch (OverlappingFileLockException e) {
// File is already locked in this thread or virtual machine
}
// Release the lock - if it is not null!
if( lock != null ) {
lock.release();
}
// Close the file
channel.close();
} catch (Exception e) {
}
This might be work for you
let main_string = " User not found,Want to review ? Click here"
let string_to_color = "Click here"
let range = (main_string as NSString).range(of: string_to_color)
let attribute = NSMutableAttributedString.init(string: main_string)
attribute.addAttribute(NSAttributedStringKey.foregroundColor, value: UIColor.blue , range: range)
lblClickHere.attributedText = attribute
c++ IDE for MSWindows 1-Visual Studio 2-CodeBlocks (nighitly build) others (devcpp, netbeans, eclips,...) just sucks, dont waste your time
Maybe try kint: composer require raveren/kint "dev-master" More information: Why is my debug data unformatted?
<img draggable="false" src="images/testimg1.jpg" alt=""/>
Speaking as someone who spent 18 months working at a mapping company, which included working on the routing algorithm... yes, Dijkstra's does work, with a couple of modifications:
With modifications along those lines, you can do even cross-country routing in a very reasonable timeframe.
Using @FlySwat's answer, I came up with this solution:
//var list = new List<int> { 1, 2, 3, 4, 5, 6 }; // Your sample collection
var listEnumerator = list.GetEnumerator(); // Get enumerator
for (var i = 0; listEnumerator.MoveNext() == true; i++)
{
int currentItem = listEnumerator.Current; // Get current item.
//Console.WriteLine("At index {0}, item is {1}", i, currentItem); // Do as you wish with i and currentItem
}
You get the enumerator using GetEnumerator
and then you loop using a for
loop. However, the trick is to make the loop's condition listEnumerator.MoveNext() == true
.
Since the MoveNext
method of an enumerator returns true if there is a next element and it can be accessed, making that the loop condition makes the loop stop when we run out of elements to iterate over.
You can use -b to specify a cookie file to read the cookies from as well.
In many situations using -c and -b to the same file is what you want:
curl -b cookies.txt -c cookies.txt http://example.com
Further
Using only -c will make curl start with no cookies but still parse and understand cookies and if redirects or multiple URLs are used, it will then use the received cookies within the single invoke before it writes them all to the output file in the end.
The -b option feeds a set of initial cookies into curl so that it knows about them at start, and it activates curl's cookie parser so that it'll parse and use incoming cookies as well.
See Also
The cookies chapter in the Everything curl book.
DateTime
is a DataType which is used to store both Date
and Time
. But it provides Properties to get the Date
Part.
You can get the Date part from Date
Property.
http://msdn.microsoft.com/en-us/library/system.datetime.date.aspx
DateTime date1 = new DateTime(2008, 6, 1, 7, 47, 0);
Console.WriteLine(date1.ToString());
// Get date-only portion of date, without its time.
DateTime dateOnly = date1.Date;
// Display date using short date string.
Console.WriteLine(dateOnly.ToString("d"));
// Display date using 24-hour clock.
Console.WriteLine(dateOnly.ToString("g"));
Console.WriteLine(dateOnly.ToString("MM/dd/yyyy HH:mm"));
// The example displays the following output to the console:
// 6/1/2008 7:47:00 AM
// 6/1/2008
// 6/1/2008 12:00 AM
// 06/01/2008 00:00
I'm running SQL Server 2014 64 bit
on Windows 10. I tried everything, the thing that made it work was:
EXEC sp_MSset_oledb_prop N'Microsoft.ACE.OLEDB.12.0', N'AllowInProcess', 0
I don't know why the AllowInProcess turned off makes it work but that was the key in my case. Thank you for the suggestion of turning all the options off on the linkserver.
No, the powers that be at Google chose not to support that.
https://groups.google.com/forum/#!topic/golang-nuts/-5MCaivW0qQ
query
runs a standard SQL statement and requires you to properly escape all data to avoid SQL Injections and other issues.
execute
runs a prepared statement which allows you to bind parameters to avoid the need to escape or quote the parameters. execute
will also perform better if you are repeating a query multiple times. Example of prepared statements:
$sth = $dbh->prepare('SELECT name, colour, calories FROM fruit
WHERE calories < :calories AND colour = :colour');
$sth->bindParam(':calories', $calories);
$sth->bindParam(':colour', $colour);
$sth->execute();
// $calories or $color do not need to be escaped or quoted since the
// data is separated from the query
Best practice is to stick with prepared statements and execute
for increased security.
See also: Are PDO prepared statements sufficient to prevent SQL injection?
It seems that bames53's answer can be extended to defining integer and non-integer constant values in namespace and class declarations even if they get included in multiple source files. It is not necessary to put the declarations in a header file but the definitions in a source file. The following example works for Microsoft Visual Studio 2015, for z/OS V2.2 XL C/C++ on OS/390, and for g++ (GCC) 8.1.1 20180502 on GNU/Linux 4.16.14 (Fedora 28). Note that the constants are declared/defined in only a single header file that gets included in multiple source files.
In foo.cc:
#include <cstdio> // for puts
#include "messages.hh"
#include "bar.hh"
#include "zoo.hh"
int main(int argc, const char* argv[])
{
puts("Hello!");
bar();
zoo();
puts(Message::third);
return 0;
}
In messages.hh:
#ifndef MESSAGES_HH
#define MESSAGES_HH
namespace Message {
char const * const first = "Yes, this is the first message!";
char const * const second = "This is the second message.";
char const * const third = "Message #3.";
};
#endif
In bar.cc:
#include "messages.hh"
#include <cstdio>
void bar(void)
{
puts("Wow!");
printf("bar: %s\n", Message::first);
}
In zoo.cc:
#include <cstdio>
#include "messages.hh"
void zoo(void)
{
printf("zoo: %s\n", Message::second);
}
In bar.hh:
#ifndef BAR_HH
#define BAR_HH
#include "messages.hh"
void bar(void);
#endif
In zoo.hh:
#ifndef ZOO_HH
#define ZOO_HH
#include "messages.hh"
void zoo(void);
#endif
This yields the following output:
Hello!
Wow!
bar: Yes, this is the first message!
zoo: This is the second message.
Message #3.
The data type char const * const
means a constant pointer to an array of constant characters. The first const
is needed because (according to g++) "ISO C++ forbids converting a string constant to 'char*'". The second const
is needed to avoid link errors due to multiple definitions of the (then insufficiently constant) constants. Your compiler might not complain if you omit one or both of the const
s, but then the source code is less portable.
If you know the exact axis you want, then
pylab.ylim([0,1000])
works as answered previously. But if you want a more flexible axis to fit your exact data, as I did when I found this question, then set axis limit to be the length of your dataset. If your dataset is fft
as in the question, then add this after your plot command:
length = (len(fft))
pylab.ylim([0,length])
In php.ini
, comment out:
error_reporting = E_ALL & ~E_NOTICE
error_reporting = E_ALL & ~E_NOTICE | E_STRICT
error_reporting = E_COMPILE_ERROR|E_RECOVERABLE_ERROR|E_ER… _ERROR
error_reporting = E_ALL & ~E_NOTICE
By placing a ;
ahead of it (i.e., like ;error_reporting = E_ALL & ~E_NOTICE
)
For disabling in a single file, place error_reporting(0);
after opening a php
tag.
XmlSerializer sr = new XmlSerializer(objectToSerialize.GetType());
TextWriter xmlWriter = new StreamWriter(filename);
XmlSerializerNamespaces namespaces = new XmlSerializerNamespaces();
namespaces.Add(string.Empty, string.Empty);
sr.Serialize(xmlWriter, objectToSerialize, namespaces);
Please make sure you have done below in your environment.rb file.
ENV['RAILS_ENV'] ||= 'production'
If you application runs in shared hosting environment or phushion passenger, you might need to need make changes in .httaccess (inside public folder) and set mode as production.
Reset IIS, stop services which are using your DLL (maybe console app or windows services hosted app or IIS) and then try.
It worked for me.
It is better to include stdlib.h
. Since without stdlibg it takes long as long
The return type depends on the server, sometimes the response is indeed a JSON array but sent as text/plain
Setting the accept headers in the request should get the correct type:
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
which can then be serialized to a JSON list or array. Thanks for the comment from @svick which made me curious that it should work.
The Exception I got without configuring the accept headers was System.Net.Http.UnsupportedMediaTypeException.
Following code is cleaner and should work (untested, but works in my case):
var client = new HttpClient();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
var response = await client.GetAsync("http://api.usa.gov/jobs/search.json?query=nursing+jobs");
var model = await response.Content.ReadAsAsync<List<Job>>();
I think the size of the object matters as well. In one of my projects, we had declared and initialized a large two dimensional array that was making the application throw an out-of-memory exception. We moved the declaration out of the loop instead and cleared the array at the start of every iteration.
Put it inside your <footer>
by all means, but the most fitting element is the small element.
The HTML5 spec for this says:
Small print typically features disclaimers, caveats, legal restrictions, or copyrights. Small print is also sometimes used for attribution, or for satisfying licensing requirements.
You can use MongoDB_DataObject wrapper to perform such query like below:
$model = new MongoDB_DataObject('orders');
$model->whereAdd('MONTH(created) = 4 AND YEAR(created) = 2016');
$model->find();
while ($model->fetch()) {
var_dump($model);
}
OR, similarly, using direct query string:
$model = new MongoDB_DataObject();
$model->query('SELECT * FROM orders WHERE MONTH(created) = 4 AND YEAR(created) = 2016');
while ($model->fetch()) {
var_dump($model);
}
set datestr=%date%
set result=%datestr:/=-%
@echo %result%
pause
You might want to use TRUNC function on your column when comparing with string format, so it compares only till seconds, not milliseconds.
SELECT * FROM <table_name> WHERE id = 1
AND TRUNC(usagetime, 'SS') = '2012-09-03 08:03:06';
If you wanted to truncate upto minutes, hours, etc. that is also possible, just use appropriate notation instead of 'SS':
hour ('HH'), minute('MI'), year('YEAR' or 'YYYY'), month('MONTH' or 'MM'), Day ('DD')
If you want to check if a property exists: hasOwnProperty is the way to go
And since most objects are properties of some other object (eventually leading to the window
object) this can work well for checking if values have been declared.
fetch
now supports a signal
parameter as of 20 September 2017, but not
all browsers seem support this at the moment.
2020 UPDATE: Most major browsers (Edge, Firefox, Chrome, Safari, Opera, and a few others) support the feature, which has become part of the DOM living standard. (as of 5 March 2020)
This is a change we will be seeing very soon though, and so you should be able to cancel a request by using an AbortController
s AbortSignal
.
The way it works is this:
Step 1: You create an AbortController
(For now I just used this)
const controller = new AbortController()
Step 2: You get the AbortController
s signal like this:
const signal = controller.signal
Step 3: You pass the signal
to fetch like so:
fetch(urlToFetch, {
method: 'get',
signal: signal, // <------ This is our AbortSignal
})
Step 4: Just abort whenever you need to:
controller.abort();
Here's an example of how it would work (works on Firefox 57+):
<script>_x000D_
// Create an instance._x000D_
const controller = new AbortController()_x000D_
const signal = controller.signal_x000D_
_x000D_
/*_x000D_
// Register a listenr._x000D_
signal.addEventListener("abort", () => {_x000D_
console.log("aborted!")_x000D_
})_x000D_
*/_x000D_
_x000D_
_x000D_
function beginFetching() {_x000D_
console.log('Now fetching');_x000D_
var urlToFetch = "https://httpbin.org/delay/3";_x000D_
_x000D_
fetch(urlToFetch, {_x000D_
method: 'get',_x000D_
signal: signal,_x000D_
})_x000D_
.then(function(response) {_x000D_
console.log(`Fetch complete. (Not aborted)`);_x000D_
}).catch(function(err) {_x000D_
console.error(` Err: ${err}`);_x000D_
});_x000D_
}_x000D_
_x000D_
_x000D_
function abortFetching() {_x000D_
console.log('Now aborting');_x000D_
// Abort._x000D_
controller.abort()_x000D_
}_x000D_
_x000D_
</script>_x000D_
_x000D_
_x000D_
_x000D_
<h1>Example of fetch abort</h1>_x000D_
<hr>_x000D_
<button onclick="beginFetching();">_x000D_
Begin_x000D_
</button>_x000D_
<button onclick="abortFetching();">_x000D_
Abort_x000D_
</button>
_x000D_
Before doing
git clone https://example.com/root/test.git
make sure that you have added ssh key in your system. Follow this : https://gitlab.com/profile/keys .
Once added run the above command. It will prompt for your gitlab username and password and on authentication, it will be cloned.
page 1 : Detail page 2 : <% String id = request.getParameter("userid");%> // now you can using id for sql query of hsql detail product
How about using the mysql client like this:
mysql -h <hostname> -u username -p <databasename> < file.sql
Use a Scanner
and pass in the delimiter and the original string:
result = new Scanner(result).useDelimiter("\n").next();
It's possible to change the path fill color of the svg. See below for the CSS snippet:
To apply the color for all the path: svg > path{ fill: red }
To apply for the first d path: svg > path:nth-of-type(1){ fill: green }
To apply for the second d path: svg > path:nth-of-type(2){ fill: green}
To apply for the different d path, change only the path number:
svg > path:nth-of-type(${path_number}){ fill: green}
To support the CSS in Angular 2 to 8, use the encapsulation concept:
:host::ng-deep svg path:nth-of-type(1){
fill:red;
}
It looks like you're using a mingw compile of Git on windows (or possibly another one I haven't heard about). There are ways to debug this: I believe all of the http proxy work for git is done by curl. Set this environment variable before running git:
GIT_CURL_VERBOSE=1
This should at least give you an idea of what is going on behind the scenes.
I always use this.It send form data using ajax
$(document).on("submit", "form", function(event)
{
event.preventDefault();
var url=$(this).attr("action");
$.ajax({
url: url,
type: 'POST',
data: new FormData(this),
processData: false,
contentType: false,
success: function (data, status)
{
}
});
});
Use strtotime to generate a timestamp from the given string (interpreted as local time) and use gmdate to get it as a formatted UTC date back.
As requested, here’s a simple example:
echo gmdate('d.m.Y H:i', strtotime('2012-06-28 23:55'));
I use bootstrap 3.x as well and the following code fore responsive youtube video embedding works like charm for me:
.videoWrapperOuter {
max-width:640px;
margin-left:auto;
margin-right:auto;
}
.videoWrapperInner {
float: none;
clear: both;
width: 100%;
position: relative;
padding-bottom: 50%;
padding-top: 25px;
height: 0;
}
.videoWrapperInner iframe {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
}
<div class="videoWrapperOuter">
<div class="videoWrapperInner">
<iframe src="//www.youtube.com/embed/C6-TWRn0k4I"
frameborder="0" allowfullscreen></iframe>
</div>
</div>
I gave a similiar answer on another thread (Shrink a YouTube video to responsive width), but I guess my answers can help here as well.
DocumentElement
is the root node of the document so childNodes[1]
doesn't exist in that document. childNodes[0]
would be the <Settings> node
Use ClipboardManager#setPrimaryClip
method:
import android.content.ClipboardManager;
// ...
ClipboardManager clipboard = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE);
ClipData clip = ClipData.newPlainText("label", "Text to copy");
clipboard.setPrimaryClip(clip);
In spark/scala, it's pretty easy to filter with varargs.
val d = spark.read...//data contains column named matid
val ids = Seq("BNBEL0608AH", "BNBEL00608H")
val filtered = d.filter($"matid".isin(ids:_*))
I run a small experiment to verify that printing with DBL_DECIMAL_DIG
does indeed exactly preserve the number's binary representation. It turned out that for the compilers and C libraries I tried, DBL_DECIMAL_DIG
is indeed the number of digits required, and printing with even one digit less creates a significant problem.
#include <float.h>
#include <math.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
union {
short s[4];
double d;
} u;
void
test(int digits)
{
int i, j;
char buff[40];
double d2;
int n, num_equal, bin_equal;
srand(17);
n = num_equal = bin_equal = 0;
for (i = 0; i < 1000000; i++) {
for (j = 0; j < 4; j++)
u.s[j] = (rand() << 8) ^ rand();
if (isnan(u.d))
continue;
n++;
sprintf(buff, "%.*g", digits, u.d);
sscanf(buff, "%lg", &d2);
if (u.d == d2)
num_equal++;
if (memcmp(&u.d, &d2, sizeof(double)) == 0)
bin_equal++;
}
printf("Tested %d values with %d digits: %d found numericaly equal, %d found binary equal\n", n, digits, num_equal, bin_equal);
}
int
main()
{
test(DBL_DECIMAL_DIG);
test(DBL_DECIMAL_DIG - 1);
return 0;
}
I run this with Microsoft's C compiler 19.00.24215.1 and gcc version 7.4.0 20170516 (Debian 6.3.0-18+deb9u1). Using one less decimal digit halves the number of numbers that compare exactly equal. (I also verified that rand()
as used indeed produces about one million different numbers.) Here are the detailed results.
Tested 999507 values with 17 digits: 999507 found numericaly equal, 999507 found binary equal Tested 999507 values with 16 digits: 545389 found numericaly equal, 545389 found binary equal
Tested 999485 values with 17 digits: 999485 found numericaly equal, 999485 found binary equal Tested 999485 values with 16 digits: 545402 found numericaly equal, 545402 found binary equal
Use this query:
ALTER TABLE tablename ADD columname DATATYPE(size);
And here is an example:
ALTER TABLE Customer ADD LastName VARCHAR(50);
You can get the value of a file field just the same as any other field. You can't alter it, however.
So to superficially check if a file has the right extension, you could do something like this:
var ext = $('#my_file_field').val().split('.').pop().toLowerCase();
if($.inArray(ext, ['gif','png','jpg','jpeg']) == -1) {
alert('invalid extension!');
}
I spent hours on this. I used to not get errors but mails were never sent. Finally I found a solution and I would like to share it.
<?php
include 'nav.php';
/*
Download PhpMailer from the following link:
https://github.com/Synchro/PHPMailer (CLick on Download zip on the right side)
Extract the PHPMailer-master folder into your xampp->htdocs folder
Make changes in the following code and its done :-)
You will receive the mail with the name Root User.
To change the name, go to class.phpmailer.php file in your PHPMailer-master folder,
And change the name here:
public $FromName = 'Root User';
*/
require("PHPMailer-master/PHPMailerAutoload.php"); //or select the proper destination for this file if your page is in some //other folder
ini_set("SMTP","ssl://smtp.gmail.com");
ini_set("smtp_port","465"); //No further need to edit your configuration files.
$mail = new PHPMailer();
$mail->SMTPAuth = true;
$mail->Host = "smtp.gmail.com"; // SMTP server
$mail->SMTPSecure = "ssl";
$mail->Username = "[email protected]"; //account with which you want to send mail. Or use this account. i dont care :-P
$mail->Password = "trials.php.php"; //this account's password.
$mail->Port = "465";
$mail->isSMTP(); // telling the class to use SMTP
$rec1="[email protected]"; //receiver. email addresses to which u want to send the mail.
$mail->AddAddress($rec1);
$mail->Subject = "Eventbook";
$mail->Body = "Hello hi, testing";
$mail->WordWrap = 200;
if(!$mail->Send()) {
echo 'Message was not sent!.';
echo 'Mailer error: ' . $mail->ErrorInfo;
} else {
echo //Fill in the document.location thing
'<script type="text/javascript">
if(confirm("Your mail has been sent"))
document.location = "/";
</script>';
}
?>
It may be caused by IE's box model bug. To fix this, you can use the Box Model Hack.
Only suggestion is to access your resp_dict
via .get()
for a more graceful approach that will degrade well if the data isn't as expected.
resp_dict = json.loads(resp_str)
resp_dict.get('name') # will return None if 'name' doesn't exist
You could also add some logic to test for the key if you want as well.
if 'name' in resp_dict:
resp_dict['name']
else:
# do something else here.
This solution works with Swift 4 (Xcode 9.2) and also with Swift 5 (Xcode 10.2.1+):
let fileManager = FileManager.default
let documentsURL = fileManager.urls(for: .documentDirectory, in: .userDomainMask)[0]
do {
let fileURLs = try fileManager.contentsOfDirectory(at: documentsURL, includingPropertiesForKeys: nil)
// process files
} catch {
print("Error while enumerating files \(documentsURL.path): \(error.localizedDescription)")
}
Here's a reusable FileManager extension that also lets you skip or include hidden files in the results:
import Foundation
extension FileManager {
func urls(for directory: FileManager.SearchPathDirectory, skipsHiddenFiles: Bool = true ) -> [URL]? {
let documentsURL = urls(for: directory, in: .userDomainMask)[0]
let fileURLs = try? contentsOfDirectory(at: documentsURL, includingPropertiesForKeys: nil, options: skipsHiddenFiles ? .skipsHiddenFiles : [] )
return fileURLs
}
}
// Usage
print(FileManager.default.urls(for: .documentDirectory) ?? "none")
There are several ways to do this, below are two options:
Option 1 - Right click on the database you want to copy
Choose 'Tasks' > 'Generate scripts'
'Select specific database objects'
Check 'Tables'
Mark 'Save to new query window'
Click 'Advanced'
Set 'Types of data to script' to 'Schema and data'
Next, Next
You can now run the generated query on the new database.
Option 2
Right click on the database you want to copy
'Tasks' > 'Export Data'
Next, Next
Choose the database to copy the tables to
Mark 'Copy data from one or more tables or views'
Choose the tables you want to copy
Finish
Yes, but don't - escaping forward slashes is a good thing. When using JSON inside <script>
tags it's necessary as a </script>
anywhere - even inside a string - will end the script tag.
Depending on where the JSON is used it's not necessary, but it can be safely ignored.