First installed sudo apt-get install php5-gd
, then sudo apt-get install php5-intl
and last one was sudo apt-get install php5-xsl
.
After that, it's installing as it should.
I got the solution. I am able to enable MySQLi extension in php.ini. I just uncommented this line in php.ini:
extension=php_mysqli.dll
Now MySQLi is working well. Here is the php.ini
file path in an Apache 2, PHP 7, and Ubuntu 14.04 environment:
/etc/php/7.0/apache2/php.ini
By default, the MySQLi extension is disabled in PHP 7.
mysqli is provided by php-mysql-5.3.3-40.el6_6.x86_64
You may need to try the following
yum install php-mysql-5.3.3-40.el6_6.x86_64
If you are certain that you only need column A, then you can use an End function in VBA to get that result.
If all the cells A1:A100 are filled, then to select the next empty cell use:
Range("A1").End(xlDown).Offset(1, 0).Select
Here, End(xlDown) is the equivalent of selecting A1 and pressing Ctrl + Down Arrow.
If there are blank cells in A1:A100, then you need to start at the bottom and work your way up. You can do this by combining the use of Rows.Count and End(xlUp), like so:
Cells(Rows.Count, 1).End(xlUp).Offset(1, 0).Select
Going on even further, this can be generalized to selecting a range of cells, starting at a point of your choice (not just in column A). In the following code, assume you have values in cells C10:C100, with blank cells interspersed in between. You wish to select all the cells C10:C100, not knowing that the column ends at row 100, starting by manually selecting C10.
Range(Selection, Cells(Rows.Count, Selection.Column).End(xlUp)).Select
The above line is perhaps one of the more important lines to know as a VBA programmer, as it allows you to dynamically select ranges based on very few criteria, and not be bothered with blank cells in the middle.
You don't need to download any new software. You can use Octave Online to open .m files.
Android locked down GET_ACCOUNTS
recently so some of the answers did not work for me. I got this working on Android 7.0 with the caveat that your users have to endure a permission dialog.
AndroidManifest.xml
<uses-permission android:name="android.permission.GET_ACCOUNTS"/>
MainActivity.java
package com.example.patrick.app2;
import android.content.pm.PackageManager;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.accounts.AccountManager;
import android.accounts.Account;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.*;
public class MainActivity extends AppCompatActivity {
final static int requestcode = 4; //arbitrary constant less than 2^16
private static String getEmailId(Context context) {
AccountManager accountManager = AccountManager.get(context);
Account[] accounts = accountManager.getAccountsByType("com.google");
Account account;
if (accounts.length > 0) {
account = accounts[0];
} else {
return "length is zero";
}
return account.name;
}
@Override
public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
switch (requestCode) {
case requestcode:
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
String emailAddr = getEmailId(getApplicationContext());
ShowMessage(emailAddr);
} else {
ShowMessage("Permission Denied");
}
}
}
public void ShowMessage(String email)
{
AlertDialog alertDialog = new AlertDialog.Builder(MainActivity.this).create();
alertDialog.setTitle("Alert");
alertDialog.setMessage(email);
alertDialog.setButton(AlertDialog.BUTTON_NEUTRAL, "OK",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
alertDialog.show();
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Context context = getApplicationContext();
if ( ContextCompat.checkSelfPermission( context, android.Manifest.permission.GET_ACCOUNTS )
!= PackageManager.PERMISSION_GRANTED )
{
ActivityCompat.requestPermissions( this, new String[]
{ android.Manifest.permission.GET_ACCOUNTS },requestcode );
}
else
{
String possibleEmail = getEmailId(getApplicationContext());
ShowMessage(possibleEmail);
}
}
}
The $EUID environment variable holds the current user's UID. Root's UID is 0. Use something like this in your script:
if [ "$EUID" -ne 0 ]
then echo "Please run as root"
exit
fi
Note: If you get 2: [: Illegal number:
check if you have #!/bin/sh
at the top and change it to #!/bin/bash
.
To walk through the @INC directory trees without using an external program like ls(1), one could use the File::Find::Rule
module, which has a nice declarative interface.
Also, you want to filter out duplicates in case previous Perl versions contain the same modules. The code to do this looks like:
#! /usr/bin/perl -l
use strict;
use warnings;
use File::Find::Rule;
my %seen;
for my $path (@INC) {
for my $file (File::Find::Rule->name('*.pm')->in($path)) {
my $module = substr($file, length($path)+1);
$module =~ s/.pm$//;
$module =~ s{[\\/]}{::}g;
print $module unless $seen{$module}++;
}
}
At the end of the run, you also have all your module names as keys in the %seen hash. The code could be adapted to save the canonical filename (given in $file) as the value of the key instead of a count of times seen.
The answers above are great. If you are in need of parsing all numbers out of a string that are nonconsecutive then the following may be of some help:
string input = "1-205-330-2342";
string result = Regex.Replace(input, @"[^\d]", "");
Console.WriteLine(result); // >> 12053302342
This should work:
ax1.plot(xtr, color='r', label='HHZ 1')
ax1.legend(loc="upper right")
ax2.plot(xtr, color='r', label='HHN')
ax2.legend(loc="upper right")
ax3.plot(xtr, color='r', label='HHE')
ax3.legend(loc="upper right")
Here is an approach for you to do something on a different thread and start listening to the key pressed in a different thread. And the Console will stop its processing when your actual process ends or the user terminates the process by pressing Esc key.
class SplitAnalyser
{
public static bool stopProcessor = false;
public static bool Terminate = false;
static void Main(string[] args)
{
Console.ForegroundColor = ConsoleColor.Green;
Console.WriteLine("Split Analyser starts");
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine("Press Esc to quit.....");
Thread MainThread = new Thread(new ThreadStart(startProcess));
Thread ConsoleKeyListener = new Thread(new ThreadStart(ListerKeyBoardEvent));
MainThread.Name = "Processor";
ConsoleKeyListener.Name = "KeyListener";
MainThread.Start();
ConsoleKeyListener.Start();
while (true)
{
if (Terminate)
{
Console.WriteLine("Terminating Process...");
MainThread.Abort();
ConsoleKeyListener.Abort();
Thread.Sleep(2000);
Thread.CurrentThread.Abort();
return;
}
if (stopProcessor)
{
Console.WriteLine("Ending Process...");
MainThread.Abort();
ConsoleKeyListener.Abort();
Thread.Sleep(2000);
Thread.CurrentThread.Abort();
return;
}
}
}
public static void ListerKeyBoardEvent()
{
do
{
if (Console.ReadKey(true).Key == ConsoleKey.Escape)
{
Terminate = true;
}
} while (true);
}
public static void startProcess()
{
int i = 0;
while (true)
{
if (!stopProcessor && !Terminate)
{
Console.ForegroundColor = ConsoleColor.White;
Console.WriteLine("Processing...." + i++);
Thread.Sleep(3000);
}
if(i==10)
stopProcessor = true;
}
}
}
Like this:
import java.util.*;
Set<Integer> a = new HashSet<Integer>();
a.add( 1);
a.add( 2);
a.add( 3);
Or adding from an Array/ or multiple literals; wrap to a list, first.
Integer[] array = new Integer[]{ 1, 4, 5};
Set<Integer> b = new HashSet<Integer>();
b.addAll( Arrays.asList( b)); // from an array variable
b.addAll( Arrays.asList( 8, 9, 10)); // from literals
To get the intersection:
// copies all from A; then removes those not in B.
Set<Integer> r = new HashSet( a);
r.retainAll( b);
// and print; r.toString() implied.
System.out.println("A intersect B="+r);
Hope this answer helps. Vote for it!
No, you can't instantite an abstract class.We instantiate only anonymous class.In abstract class we declare abstract methods and define concrete methods only.
You could also try something like this:
input[type="radio"] {_x000D_
margin-top: -1px;_x000D_
vertical-align: middle;_x000D_
}
_x000D_
<label class="child"><input id = "warm" type="radio" name="weathertype" value="warm" checked> Warm<br></label>_x000D_
<label class="child1"><input id = "cold" type="radio" name="weathertype" value="cold" checked> Cold<br></label>
_x000D_
As a workaround, you can create a hidden worksheet, which would hold the changed value. The cell on the visible, protected worksheet should display the value from the hidden worksheet using a simple formula.
You will be able to change the displayed value through the hidden worksheet, while your users won't be able to edit it.
For me the best and the simplest way of understanding the difference is:
var service, factory;
service = factory = function(injection) {}
How AngularJS instantiates particular components (simplified):
// service
var angularService = new service(injection);
// factory
var angularFactory = factory(injection);
So, for the service, what becomes the AngularJS component is the object instance of the class which is represented by service declaration function. For the factory, it is the result returned from the factory declaration function. The factory may behave the same as the service:
var factoryAsService = function(injection) {
return new function(injection) {
// Service content
}
}
The simplest way of thinking is the following one:
The factory 'class' example is provided in the comments around, as well as provider difference.
The original question specifically asked for Unix but multiple answers have touched on Windows, and as a result there is misleading information on windows. The default timer resolution on windows is 15.6ms you can verify here.
Using a slightly modified script from cod3monk3y I can show that windows timer resolution is ~15milliseconds by default. I'm using a tool available here to modify the resolution.
Script:
import time
# measure the smallest time delta by spinning until the time changes
def measure():
t0 = time.time()
t1 = t0
while t1 == t0:
t1 = time.time()
return t1-t0
samples = [measure() for i in range(30)]
for s in samples:
print(f'time delta: {s:.4f} seconds')
These results were gathered on windows 10 pro 64-bit running python 3.7 64-bit.
Because my keyboard has an O key.
It does not have a T or an O key.
I suspect most people are similarly lazy and use O when they mean T because it's easier to type.
Private Sub CommandButton1_Click()
Dim Z As Long
Dim Cellidx As Range
Dim NextRow As Long
Dim Rng As Range
Dim SrcWks As Worksheet
Dim DataWks As Worksheet
Z = 1
Set SrcWks = Worksheets("Sheet1")
Set DataWks = Worksheets("Sheet2")
Set Rng = EntryWks.Range("B6:ad6")
NextRow = DataWks.UsedRange.Rows.Count
NextRow = IIf(NextRow = 1, 1, NextRow + 1)
For Each RA In Rng.Areas
For Each Cellidx In RA
Z = Z + 1
DataWks.Cells(NextRow, Z) = Cellidx
Next Cellidx
Next RA
End Sub
Alternatively
Worksheets("Sheet2").Range("P2").Value = Worksheets("Sheet1").Range("L10")
This is a CopynPaste - Method
Sub CopyDataToPlan()
Dim LDate As String
Dim LColumn As Integer
Dim LFound As Boolean
On Error GoTo Err_Execute
'Retrieve date value to search for
LDate = Sheets("Rolling Plan").Range("B4").Value
Sheets("Plan").Select
'Start at column B
LColumn = 2
LFound = False
While LFound = False
'Encountered blank cell in row 2, terminate search
If Len(Cells(2, LColumn)) = 0 Then
MsgBox "No matching date was found."
Exit Sub
'Found match in row 2
ElseIf Cells(2, LColumn) = LDate Then
'Select values to copy from "Rolling Plan" sheet
Sheets("Rolling Plan").Select
Range("B5:H6").Select
Selection.Copy
'Paste onto "Plan" sheet
Sheets("Plan").Select
Cells(3, LColumn).Select
Selection.PasteSpecial Paste:=xlValues, Operation:=xlNone, SkipBlanks:= _
False, Transpose:=False
LFound = True
MsgBox "The data has been successfully copied."
'Continue searching
Else
LColumn = LColumn + 1
End If
Wend
Exit Sub
Err_Execute:
MsgBox "An error occurred."
End Sub
And there might be some methods doing that in Excel.
Uses .each()
, .replace()
, .html()
. Tested with jQuery 1.11 and 3.2.
In the above example, reads the 'keyword' to be highlighted and appends span tag with the 'highlight' class. The text 'keyword' is highlighted for all selected classes in the .each()
.
HTML
<body>
<label name="lblKeyword" id="lblKeyword" class="highlight">keyword</label>
<p class="filename">keyword</p>
<p class="content">keyword</p>
<p class="system"><i>keyword</i></p>
</body>
JS
$(document).ready(function() {
var keyWord = $("#lblKeyword").text();
var replaceD = "<span class='highlight'>" + keyWord + "</span>";
$(".system, .filename, .content").each(function() {
var text = $(this).text();
text = text.replace(keyWord, replaceD);
$(this).html(text);
});
});
CSS
.highlight {
background-color: yellow;
}
I know this one is pretty old, but I encountered an issue recently with having to do multiple replacements to make a file name safe. First, in the latest .NET string.Replace function null is the equivalent to empty character. Having said that, what is missing from .Net is a simple replace all that will replace any character in an array with the desired character. Please feel free to reference the code below (runs in LinqPad for testing).
// LinqPad .ReplaceAll and SafeFileName
void Main()
{
("a:B:C").Replace(":", "_").Dump(); // can only replace 1 character for one character => a_B_C
("a:B:C").Replace(":", null).Dump(); // null replaces with empty => aBC
("a:B*C").Replace(":", null).Replace("*",null).Dump(); // Have to chain for multiples
// Need a ReplaceAll, so I don't have to chain calls
("abc/123.txt").SafeFileName().Dump();
("abc/1/2/3.txt").SafeFileName().Dump();
("a:bc/1/2/3.txt").SafeFileName().Dump();
("a:bc/1/2/3.txt").SafeFileName('_').Dump();
//("abc/123").SafeFileName(':').Dump(); // Throws exception as expected
}
static class StringExtensions
{
public static string SafeFileName(this string value, char? replacement = null)
{
return value.ReplaceAll(replacement, ':','*','?','"','<','>', '|', '/', '\\');
}
public static string ReplaceAll(this string value, char? replacement, params char[] charsToGo){
if(replacement.HasValue == false){
return string.Join("", value.AsEnumerable().Where(x => charsToGo.Contains(x) == false));
}
else{
if(charsToGo.Contains(replacement.Value)){
throw new ArgumentException(string.Format("Replacement '{0}' is invalid. ", replacement), "replacement");
}
return string.Join("", value.AsEnumerable().Select(x => charsToGo.Contains(x) == true ? replacement : x));
}
}
}
Try this:
package example.spin.spinnerexample;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Spinner;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity implements AdapterView.OnItemSelectedListener{
String[] bankNames={"BOI","SBI","HDFC","PNB","OBC"};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Getting the instance of Spinner and applying OnItemSelectedListener on it
Spinner spin = (Spinner) findViewById(R.id.simpleSpinner);
spin.setOnItemSelectedListener(this);
//Creating the ArrayAdapter instance having the bank name list
ArrayAdapter aa = new ArrayAdapter(this,android.R.layout.simple_spinner_item,bankNames);
aa.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
//Setting the ArrayAdapter data on the Spinner
spin.setAdapter(aa);
}
//Performing action onItemSelected and onNothing selected
@Override
public void onItemSelected(AdapterView<?> arg0, View arg1, int position,long id) {
Toast.makeText(getApplicationContext(), bankNames[position], Toast.LENGTH_LONG).show();
}
@Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
}
activity_main.xml:-
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context=".MainActivity">
<Spinner
android:id="@+id/simpleSpinner"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_marginTop="100dp" />
</RelativeLayout>
In german VS-Environments(here 2015): Optionen/Umgebung/Tastatur. (english: options/environment/keyboard). Show Commands With "GeheZuKlammer" (english: "GoToBracket"). Set your own Shortcut.
The docker logs
command will show you the output a container is generating when you don't run it interactively. This is likely to include the error message.
docker logs --tail 50 --follow --timestamps mediawiki_web_1
You can also run a fresh container in the foreground with docker run -ti <your_wiki_image>
to see what that does. You may need to map some config from your docker-compose
yml to the docker
command.
I would guess that attaching to the media wiki process caused a crash which has corrupted something in your data.
Struggled with this issue for some time before figuring it out.
I'm using High Sierra (10.13.6)
Uninstalled and re-installed node and nvm multiple times - using the installer.pkg
, HomeBrew
, and then using the command line. IMO, the command line works the best.
I followed these steps:
1. Ran npm config ls -l
2. Checked that the value for globalconfig
was $<installpath>/.nvm/versions/node/v12.16.3/etc/npmrc
But when I tried to get to this path in the Terminal, it gave me No such file or directory
So I
3. created the folder etc
, created the npmrc
file and added this line in it.
registry = "https://registry.npmjs.org/"
I do not have the ~/.npmrc
file in my $HOME
Then
4. I re-ran the npm install
command.
Note that this still threw the rollbackFailedOptional: verb npm-session
error, but this time it completed, though with a different error.
You could try these steps and see if it works.
For those who are curious, it threw a Response timeout while trying to fetch https://registry.npmjs.org/<package> (over 30000ms)
error, so I added the timeout = "60000"
to the /etc/npmrc
file (as found on another Stackoverflow thread), and tried again. This worked for me.
Hope this helps!
You can use jquery for this:
$('body').bind('copy paste',function(e) {
e.preventDefault(); return false;
});
Using jQuery bind()
and specififying your desired eventTypes
.
Java does not provide a construct that will assign of multiple values to an existing array's elements. The initializer syntaxes can ONLY be used when creation a new array object. This can be at the point of declaration, or later on. But either way, the initializer is initializing a new array object, not updating an existing one.
To do this in Windows CLI environment, the best way I can find is to use the mode command and parse the output.
function getTerminalSizeOnWindows() {
$output = array();
$size = array('width'=>0,'height'=>0);
exec('mode',$output);
foreach($output as $line) {
$matches = array();
$w = preg_match('/^\s*columns\:?\s*(\d+)\s*$/i',$line,$matches);
if($w) {
$size['width'] = intval($matches[1]);
} else {
$h = preg_match('/^\s*lines\:?\s*(\d+)\s*$/i',$line,$matches);
if($h) {
$size['height'] = intval($matches[1]);
}
}
if($size['width'] AND $size['height']) {
break;
}
}
return $size;
}
I hope it's useful!
NOTE: The height returned is the number of lines in the buffer, it is not the number of lines that are visible within the window. Any better options out there?
For 1. topic (Target Unreachable, identifier 'bean' resolved to null);
I checked valuable answers the @BalusC and the other sharers but I exceed the this problem like this on my scenario. After the creating a new xhtml with different name and creating bean class with different name then I wrote (not copy-paste) the codes step by step to the new bean class and new xhtml file.
set width attribute as: width: fit-content
I'm not sure exactly what you want, but I think it's along the lines of:
SELECT `Item`, `qty`-`BAL_QTY` as `qty` FROM ((SELECT Item, SUM(`QTY`) as qty FROM `master_table` GROUP BY `ITEM`) as A NATURAL JOIN `stock_table`) as B
Its better to access the count with the laravels count method
$count = Model::where('status','=','1')->count();
or
$count = Model::count();
The long boring solution, which is not involved with CLI, you can manually navigate to:
your local repo folder ? .git folder (hidden) ? config file
then choose your text editor to open it and look for url located under the [remote "origin"] section.
It works fine, Ex :
$.ajax({
url: "http://localhost:11141/Search/BasicSearchContent?ContentTitle=" + "?????",
type: 'GET',
cache: false,
success: function(result) {
// alert(jQuery.dataType);
if (result) {
// var dd = JSON.parse(result);
alert(result[0].Id)
}
},
error: function() {
alert("No");
}
});
Finally, you need to use this statement ...
result[0].Whatever
There are several problems here:
The newdata
argument of predict()
needs a predictor variable. You should thus pass it values for Coupon
, instead of Total
, which is the response variable in your model.
The predictor variable needs to be passed in as a named column in a data frame, so that
predict()
knows what the numbers its been handed represent. (The need for this becomes clear when you consider more complicated models, having more than one predictor variable).
For this to work, your original call should pass df
in through the data
argument, rather than using it directly in your formula. (This way, the name of the column in newdata
will be able to match the name on the RHS of the formula).
With those changes incorporated, this will work:
model <- lm(Total ~ Coupon, data=df)
new <- data.frame(Coupon = df$Coupon)
predict(model, newdata = new, interval="confidence")
if string.startswith('"'):
string = string[1:]
if string.endswith('"'):
string = string[:-1]
When you are using second approach you are initializing arraylist with its predefined values. Like generally we do ArrayList listofStrings = new ArrayList<>(); Let's say you have an array with values, now you want to convert this array into arraylist.
you need to first get the list from the array using Arrays utils. Because the ArrayList is concrete type that implement List interface. It is not guaranteed that method asList, will return this type of implementation.
List<String> listofOptions = (List<String>) Arrays.asList(options);
then you can user constructoru of an arraylist to instantiate with predefined values.
ArrayList<String> arrlistofOptions = new ArrayList<String>(list);
So your second approach is working that you have passed values which will intantiate arraylist with the list elements.
More over
ArrayList that is returned from Arrays.asList is not an actual arraylist, it is just a wrapper which doesnt allows any modification in the list. If you try to add or remove over Arrays.asList it will give you
UnsupportedOperationException
Use any examples that don't insert each element one at a time, one insertion is most efficient
$('.element').html( '<span>' + array.join('</span><span>')+'</span>');
This is probably what you need:
$('div').html();
This says get the div
and return all the contents inside it. See more here: http://api.jquery.com/html/
If you had many div
s on the page and needed to target just one, you could set an id
on the div
and call it like so
$('#whatever').html();
where whatever is the id
EDIT
Now that you have clarified your question re this being a string, here is a way to do it with vanilla js:
var l = x.length;
var y = x.indexOf('<div>');
var s = x.slice(y,l);
alert(s);
div
occursPlease refer below code, You can manage multiple status code with different type JSON
public async Task<HttpResponseMessage> GetAsync()
{
try
{
using (var entities = new DbEntities())
{
var resourceModelList = entities.Resources.Select(r=> new ResourceModel{Build Your Resource Model}).ToList();
if (resourceModelList.Count == 0)
{
return this.Request.CreateResponse<string>(HttpStatusCode.NotFound, "No resources found.");
}
return this.Request.CreateResponse<List<ResourceModel>>(HttpStatusCode.OK, resourceModelList, "application/json");
}
}
catch (Exception ex)
{
return this.Request.CreateResponse<string>(HttpStatusCode.InternalServerError, "Something went wrong.");
}
}
Instead of WorksheetFunction.Vlookup
, you can use Application.Vlookup
. If you set a Variant
equal to this it returns Error 2042 if no match is found. You can then test the variant - cellNum
in this case - with IsError
:
Sub test()
Dim ws As Worksheet: Set ws = Sheets("2012")
Dim rngLook As Range: Set rngLook = ws.Range("A:M")
Dim currName As String
Dim cellNum As Variant
'within a loop
currName = "Example"
cellNum = Application.VLookup(currName, rngLook, 13, False)
If IsError(cellNum) Then
MsgBox "no match"
Else
MsgBox cellNum
End If
End Sub
The Application
versions of the VLOOKUP
and MATCH
functions allow you to test for errors without raising the error. If you use the WorksheetFunction
version, you need convoluted error handling that re-routes your code to an error handler, returns to the next statement to evaluate, etc. With the Application
functions, you can avoid that mess.
The above could be further simplified using the IIF
function. This method is not always appropriate (e.g., if you have to do more/different procedure based on the If/Then
) but in the case of this where you are simply trying to determinie what prompt to display in the MsgBox, it should work:
cellNum = Application.VLookup(currName, rngLook, 13, False)
MsgBox IIF(IsError(cellNum),"no match", cellNum)
Consider those methods instead of On Error ...
statements. They are both easier to read and maintain -- few things are more confusing than trying to follow a bunch of GoTo
and Resume
statements.
Are'nt you creating the pdf file but not actually writing the byte array back? Therefore you cannot open the PDF.
out = new FileOutputStream("D:/ABC_XYZ/1.pdf");
out.Write(b, 0, b.Length);
out.Position = 0;
out.Close();
This is in addition to correctly reading in the PDF to byte array.
Just make sure that your HTML file is encoded with UTF-8 and that your web server sends a HTTP header with that charset, then you just can write that character directly into your HTMl file.
http://www.w3.org/International/O-HTTP-charset
If you can't use UTF-8 for some reason, you can look up the codes in a unicode list such as http://en.wikipedia.org/wiki/List_of_Unicode_characters and use ꯍ
where ABCD is the hexcode from that list (U+ABCD).
For windows user, make sure to closely look at this section.
RewriteRule ^properties$ /property_available.php/$1 [NC,QSA]
As said in Apache documentation :
The mod_rewrite module uses a rule-based rewriting engine, based on a PCRE regular-expression parser, to rewrite requested URLs on the fly.
So ^properties$
means Apache will only look for URL that has exact match with properties
.
You might want to try this code.
RewriteRule properties /property_available.php/$1 [NC,QSA]
So Apache will see the URL that has properties
and rewrite it to /property_available.php/
Just combine them. I think this should work but it's untested:
p <- ggplot(visual1, aes(ISSUE_DATE,COUNTED)) + geom_point() +
geom_smooth(fill="blue", colour="darkblue", size=1)
p <- p + geom_point(data=visual2, aes(ISSUE_DATE,COUNTED)) +
geom_smooth(data=visual2, fill="red", colour="red", size=1)
print(p)
1.Concatenate the string (space between each string)
Code Snippet :
<?php
$txt1 = "Sachin";
$txt2 = "Tendulkar";
$result = $txt1.$txt2 ;
echo $result. "\n";
?>
Output: SachinTendulkar
2.Concatenate the string where space exists
Code Snippet :
<?php
$txt1 = "Sachin";
$txt2 = "Tendulkar";
$result = $txt1." ".$txt2;
echo $result. "\n";
?>
Output : Sachin Tendulkar
- Concatenate the string using printf function.
Code Snippet :
<?php
$data1 = "Sachin";
$data2 = "Tendulkar";
printf("%s%s\n",$data1, $data2);
printf("%s %s\n",$data1, $data2);
?>
Output:
SachinTendulkar
Sachin Tendulkar
Just re-posting answer by oleynikd because it's simple and neat
Bundle bundle = ActivityOptionsCompat.makeCustomAnimation(getContext(),
android.R.anim.fade_in, android.R.anim.fade_out).toBundle();
startActivity(intent, bundle);
Ubuntu 16.04 64bit. I got the problem for apparently no reasons. The night before I watched a movie on my VideoLan instance, that night I would like to watch another one with VideoLan. VLC just didn't want to run because of the error into the question. I google a bit and I found the solution it solved my problem: from now on, VLC is runnable just like before. The solution is this comand:
sudo ln -sf /usr/lib/x86_64-linux-gnu/qt5/plugins/platforms/ /usr/bin/
I am not able to explain what are its consequencies, but I know it creates some missing symbolic link.
Well i am trying to open a .vbs within a batch file without having to click open but the answer to this question is ...
SET APPDATA=%CD%
start (your file here without the brackets with a .vbs if it is a vbd file)
My solution, after trying EVERYTHING:
Bad deployment, an old PrecompiledApp.config was hanging around my deploy location, and making everything not work.
My final settings that worked:
Nothing changes in the web.config - this means no special handlers for routing. Here's my snapshot of the sections a lot of other posts reference. I'm using FluorineFX, so I do have that handler added, but I did not need any others:
<system.web>
<compilation debug="true" targetFramework="4.0" />
<authentication mode="None"/>
<pages validateRequest="false" controlRenderingCompatibilityVersion="3.5" clientIDMode="AutoID"/>
<httpRuntime requestPathInvalidCharacters=""/>
<httpModules>
<add name="FluorineGateway" type="FluorineFx.FluorineGateway, FluorineFx"/>
</httpModules>
</system.web>
<system.webServer>
<!-- Modules for IIS 7.0 Integrated mode -->
<modules>
<add name="FluorineGateway" type="FluorineFx.FluorineGateway, FluorineFx" />
</modules>
<!-- Disable detection of IIS 6.0 / Classic mode ASP.NET configuration -->
<validation validateIntegratedModeConfiguration="false" />
</system.webServer>
Global.ashx: (only method of any note)
void Application_Start(object sender, EventArgs e) {
// Register routes...
System.Web.Routing.Route echoRoute = new System.Web.Routing.Route(
"{*message}",
//the default value for the message
new System.Web.Routing.RouteValueDictionary() { { "message", "" } },
//any regular expression restrictions (i.e. @"[^\d].{4,}" means "does not start with number, at least 4 chars
new System.Web.Routing.RouteValueDictionary() { { "message", @"[^\d].{4,}" } },
new TestRoute.Handlers.PassthroughRouteHandler()
);
System.Web.Routing.RouteTable.Routes.Add(echoRoute);
}
PassthroughRouteHandler.cs - this achieved an automatic conversion from http://andrew.arace.info/stackoverflow to http://andrew.arace.info/#stackoverflow which would then be handled by the default.aspx:
public class PassthroughRouteHandler : IRouteHandler {
public IHttpHandler GetHttpHandler(RequestContext requestContext) {
HttpContext.Current.Items["IncomingMessage"] = requestContext.RouteData.Values["message"];
requestContext.HttpContext.Response.Redirect("#" + HttpContext.Current.Items["IncomingMessage"], true);
return null;
}
}
You can use these to factor out code common to all tests in the test suite.
If you have a lot of repeated code in your tests, you can make them shorter by moving this code to setUp/tearDown.
You might use this for creating test data (e.g. setting up fakes/mocks), or stubbing out functions with fakes.
If you're doing integration testing, you can use check environmental pre-conditions in setUp, and skip the test if something isn't set up properly.
For example:
class TurretTest(unittest.TestCase):
def setUp(self):
self.turret_factory = TurretFactory()
self.turret = self.turret_factory.CreateTurret()
def test_turret_is_on_by_default(self):
self.assertEquals(True, self.turret.is_on())
def test_turret_turns_can_be_turned_off(self):
self.turret.turn_off()
self.assertEquals(False, self.turret.is_on())
inelegant (but effective) way: use percentages
#horizontal-style {
width: 100%;
}
li {
width: 20%;
}
This only works with the 5 <li>
example. For more or less, modify your percentage accordingly. If you have other <li>
s on your page, you can always assign these particular ones a class of "menu-li" so that only they are affected.
What i do in child fragment:
@Override
public void onDetach() {
super.onDetach();
ParentFragment pf = (ParentFragment) this.getParentFragment();
pf.onResume();
}
And then override onResume on ParentFragment
Use string literal operator if C++14 (operator ""s
)
using namespace std::string_literals;
throw std::exception("Could not load config file '"s + configfile + "'"s);
or define your own if in C++11. For instance
std::string operator ""_s(const char * str, std::size_t len) {
return std::string(str, str + len);
}
Your throw statement will then look like this
throw std::exception("Could not load config file '"_s + configfile + "'"_s);
which looks nice and clean.
Look at java.lang.BigDecimal, may solve your problem.
http://docs.oracle.com/javase/7/docs/api/java/math/BigDecimal.html
Use ToString()
with this format:
12345.678901.ToString("0.0000"); // outputs 12345.6789
12345.0.ToString("0.0000"); // outputs 12345.0000
Put as much zero as necessary at the end of the format.
DECLARE @x int=1
declare @exit bit=1
WHILE @x<=len('123c') AND @exit=1
BEGIN
IF ascii(SUBSTRING('123c',@x,1)) BETWEEN 48 AND 57
BEGIN
set @x=@x+1
END
ELSE
BEGIN
SET @exit=0
PRINT 'string is not all numeric -:('
END
END
I think for REST, you just have to make a decision on the behavior for that particular system in which case, I think the "right" answer would be one of a couple answers given here. If you want the request to stop and behave as if the client made a mistake that it needs to fix before continuing, then use 409. If the conflict really isn't that important and want to keep the request going, then respond by redirecting the client to the entity that was found. I think proper REST APIs should be redirecting (or at least providing the location header) to the GET endpoint for that resource following a POST anyway, so this behavior would give a consistent experience.
EDIT: It's also worth noting that you should consider a PUT since you're providing the ID. Then the behavior is simple: "I don't care what's there right now, put this thing there." Meaning, if nothing is there, it'll be created; if something is there it'll be replaced. I think a POST is more appropriate when the server manages that ID. Separating the two concepts basically tells you how to deal with it (i.e. PUT is idempotent so it should always work so long as the payload validates, POST always creates, so if there is a collision of IDs, then a 409 would describe that conflict).
Broadcast Receivers timeout after 10 seconds. Possibly your doing an asynchronous call (wrong) from a broadcast receiver and 4.3 actually detects it.
Update the master branch, which you need to do regardless.
Then, one of:
Rebase the old branch against the master branch. Solve the merge conflicts during rebase, and the result will be an up-to-date branch that merges cleanly against master.
Merge your branch into master, and resolve the merge conflicts.
Merge master into your branch, and resolve the merge conflicts. Then, merging from your branch into master should be clean.
None of these is better than the other, they just have different trade-off patterns.
I would use the rebase approach, which gives cleaner overall results to later readers, in my opinion, but that is nothing aside from personal taste.
To rebase and keep the branch you would:
git checkout <branch> && git rebase <target>
In your case, check out the old branch, then
git rebase master
to get it rebuilt against master.
self.close() does not work, are you sure you closing a window and not a script generated popup ?
you guys might want to look at this : https://bugzilla.mozilla.org/show_bug.cgi?id=183697
SELECTION SORT
Assume that there is array of numbers written in a particular/random fashion and lets say we are to arrange in increasing order..so, take one number at a time and replace them with the smallest no. available in the list. by doing this step we'll ultimately get our desired result.
INSERTION SORT
Keeping the similar assumption in mind but the only difference is that this time we are selecting one number at a time and inserting it in the presorted part, that reduced the comparisons and hence is more efficient.
Besides the way suggested in the "possible duplicate", the other main way of getting around this problem is for the array itself (or at least a template of one) to be supplied by the caller, who will hopefully know the concrete type and can thus safely create the array.
This is the way methods like ArrayList.toArray(T[])
are implemented. I'd suggest you take a look at that method for inspiration. Better yet, you should probably be using that method anyway as others have noted.
There are now official instructions from joyent (primary nodejs backer). For Ubuntu:
sudo apt-get purge nodejs npm
curl -sL https://deb.nodesource.com/setup | sudo bash -
sudo apt-get install -y nodejs
For other unix distributions, osx and windows see the link. Note this will install both node and npm.
It is not mandatory to write that. It worked fine for me without (%matplotlib
) magic function.
I am using Sypder compiler, one that comes with in Anaconda.
Dictionary does not support duplicate keys- So you will get the last key i.e.a=16
but not the first key a=15
>>>qs = [{u'a': 15L, u'b': 9L, u'a': 16L}]
>>>qs
>>>[{u'a': 16L, u'b': 9L}]
>>>result_list = [int(v) for k,v in qs[0].items()]
>>>result_list
>>>[16, 9]
I got this problem when I try to clone a git repo in Linux machine.
the following URL is working for me in windows
http://[email protected]/scm/project/swamy-main.git
whereas the following URL works in Linux machine and it has https in URL
https://[email protected]/scm/project/swamy-main.git
In v.2.x.x , we can use align
and justify
. We have below options for setup the horizontal and vertical alignment.
PROPS align
: 'start','center','end','baseline','stretch'
PRPS justify
: 'start','center','end','space-around','space-between'
<v-container fill-height fluid>
<v-row align="center"
justify="center">
<v-col></v-col>
</v-row>
</v-container>
For more details please refer this vuetify grid-system and you could check here with working codepen demo.
You could use align-center
for layout
and fill-height
for container.
Demo with v1.x.x
new Vue({
el: '#app'
})
_x000D_
.bg{
background: gray;
color: #fff;
font-size: 18px;
}
_x000D_
<link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/vuetify.min.css" rel="stylesheet" />
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/vuetify.min.js"></script>
<div id="app">
<v-app>
<v-container bg fill-height grid-list-md text-xs-center>
<v-layout row wrap align-center>
<v-flex>
Hello I am center to vertically using "align-center".
</v-flex>
</v-layout>
</v-container>
</v-app>
</div>
_x000D_
My solution if your ng-grid depend of element parent(div, layout) :
directive
myapp.directive('sizeelement', function ($window) {
return{
scope:true,
priority: 0,
link: function (scope, element) {
scope.$watch(function(){return $(element).height(); }, function(newValue, oldValue) {
scope.height=$(element).height();
});
}}
})
sample html
<div class="portlet box grey" style="height: 100%" sizeelement>
<div class="portlet-title">
<h4><i class="icon-list"></i>Articles</h4>
</div>
<div class="portlet-body" style="height:{{height-34}}px">
<div class="gridStyle" ng-grid="gridOrderLine" ="min-height: 250px;"></div>
</div>
</div>
height-34 : 34 is fix height of my title div, you can fix other height.
It is easy directive but it work fine.
My case it solved i was using
@Html.DropDownList(model => model.TypeId ...)
using
@Html.DropDownListFor(model => model.TypeId ...)
will solve it
In addition to configuration changes on your WWW server to handle the new subdomain, your code would need to be making changes to your DNS records. So, unless you're running your own BIND (or similar), you'll need to figure out how to access your name server provider's configuration. If they don't offer some sort of API, this might get tricky.
Update: yes, I would check with your registrar if they're also providing the name server service (as is often the case). I've never explored this option before but I suspect most of the consumer registrars do not. I Googled for GoDaddy APIs and GoDaddy DNS APIs but wasn't able to turn anything up, so I guess the best option would be to check out the online help with your provider, and if that doesn't answer the question, get a hold of their support staff.
First, it usually does not matter that much in practice. Most hash functions are "good enough".
But if you really care, you should know that it is a research subject by itself. There are thousand of papers about that. You can still get a PhD today by studying & designing hashing algorithms.
Your second hash function might be slightly better, because it probably should separate the string "ab"
from the string "ba"
. On the other hand, it is probably less quick than the first hash function. It may, or may not, be relevant for your application.
I'll guess that hash functions used for genome strings are quite different than those used to hash family names in telephone databases. Perhaps even some string hash functions are better suited for German, than for English or French words.
Many software libraries give you good enough hash functions, e.g. Qt has qhash, and C++11 has std::hash in <functional>
, Glib has several hash functions in C, and POCO has some hash function.
I quite often have hashing functions involving primes (see Bézout's identity) and xor, like e.g.
#define A 54059 /* a prime */
#define B 76963 /* another prime */
#define C 86969 /* yet another prime */
#define FIRSTH 37 /* also prime */
unsigned hash_str(const char* s)
{
unsigned h = FIRSTH;
while (*s) {
h = (h * A) ^ (s[0] * B);
s++;
}
return h; // or return h % C;
}
But I don't claim to be an hash expert. Of course, the values of A
, B
, C
, FIRSTH
should preferably be primes, but you could have chosen other prime numbers.
Look at some MD5 implementation to get a feeling of what hash functions can be.
Most good books on algorithmics have at least a whole chapter dedicated to hashing. Start with wikipages on hash function & hash table.
I am currently using the Google API to retrieve the location that the user enters in the form/ input. I'm also using an angular function that showing the current location and suggests a city name pin code etc...
- add google API index.html.
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?key=xxxxxxxx&libraries=geometry,places"></script>
- add id in input box to get string & charcters.
<input id="autocomplete" type="text"(keydown)="checkAddress($event.target.value)">
- and create function on your component.ts file.
import these file
import * as _ from 'lodash';
declare var google: any;
checkAddress(value) {
if (!value) {
this.model.location = _.cloneDeep(value);
this.rfpForm.controls['location'].setValue(this.model.location);
}
}
initLocationAutocomplete() {
let autocomplete, place;
const getLocation = () => {
place = autocomplete.getPlace();
if (place && (place.formatted_address || place.name)) {
// if you want set value in your form controls like this
this.model.location = _.cloneDeep(place.formatted_address || place.name);
// YourFormName.controls['location'].setValue(this.model.location);
// YourFormName.controls['location']['_touched'] = true;
}
};
autocomplete = new google.maps.places.Autocomplete((document.getElementById('autocomplete')), { types: ['geocode'] });
autocomplete.addListener('place_changed', getLocation);
}
Gmap writes inline style position to relative to the div. Overwrite that with :
google.maps.event.addListener(map, 'tilesloaded', function(){
document.getElementById('maps').style.position = 'static';
document.getElementById('maps').style.background = 'none';
});
Hope it helps.
In your JSON format, it do not have starting JSON object
Like :
{
"info" : <!-- this is starting JSON object -->
{
"caller":"getPoiById",
"results":
{
"indexForPhone":0,
"indexForEmail":"NULL",
.
.
}
}
}
Above Json starts with info
as JSON object. So while executing :
JSONObject json = new JSONObject(result); // create JSON obj from string
JSONObject json2 = json.getJSONObject("info"); // this will return correct
Now, we can access result
field :
JSONObject jsonResult = json2.getJSONObject("results");
test = json2.getString("name"); // returns "Marina Rasche Werft GmbH & Co. KG"
I think this was missing and so the problem was solved while we use JSONTokener
like answer of yours.
Your answer is very fine. Just i think i add this information so i answered
Thank you
Extension method based on Linq
public static void DeleteRows(this DataTable dt, Func<DataRow, bool> predicate)
{
foreach (var row in dt.Rows.Cast<DataRow>().Where(predicate).ToList())
row.Delete();
}
Then use:
DataTable dt = GetSomeData();
dt.DeleteRows(r => r.Field<double>("Amount") > 123.12 && r.Field<string>("ABC") == "XYZ");
One thing to note is that ngModel is required for ngOptions to work... note the ng-model="blah"
which is saying "set $scope.blah to the selected value".
Try this:
<select ng-model="blah" ng-options="item.ID as item.Title for item in items"></select>
Here's more from AngularJS's documentation (if you haven't seen it):
for array data sources:
- label for value in array
- select as label for value in array
- label group by group for value in array = select as label group by group for value in array
for object data sources:
- label for (key , value) in object
- select as label for (key , value) in object
- label group by group for (key, value) in object
- select as label group by group for (key, value) in object
For some clarification on option tag values in AngularJS:
When you use ng-options
, the values of option tags written out by ng-options will always be the index of the array item the option tag relates to. This is because AngularJS actually allows you to select entire objects with select controls, and not just primitive types. For example:
app.controller('MainCtrl', function($scope) {
$scope.items = [
{ id: 1, name: 'foo' },
{ id: 2, name: 'bar' },
{ id: 3, name: 'blah' }
];
});
<div ng-controller="MainCtrl">
<select ng-model="selectedItem" ng-options="item as item.name for item in items"></select>
<pre>{{selectedItem | json}}</pre>
</div>
The above will allow you to select an entire object into $scope.selectedItem
directly. The point is, with AngularJS, you don't need to worry about what's in your option tag. Let AngularJS handle that; you should only care about what's in your model in your scope.
Here is a plunker demonstrating the behavior above, and showing the HTML written out
Dealing with the default option:
There are a few things I've failed to mention above relating to the default option.
Selecting the first option and removing the empty option:
You can do this by adding a simple ng-init
that sets the model (from ng-model
) to the first element in the items your repeating in ng-options
:
<select ng-init="foo = foo || items[0]" ng-model="foo" ng-options="item as item.name for item in items"></select>
Note: This could get a little crazy if foo
happens to be initialized properly to something "falsy". In that case, you'll want to handle the initialization of foo
in your controller, most likely.
Customizing the default option:
This is a little different; here all you need to do is add an option tag as a child of your select, with an empty value attribute, then customize its inner text:
<select ng-model="foo" ng-options="item as item.name for item in items">
<option value="">Nothing selected</option>
</select>
Note: In this case the "empty" option will stay there even after you select a different option. This isn't the case for the default behavior of selects under AngularJS.
A customized default option that hides after a selection is made:
If you wanted your customized default option to go away after you select a value, you can add an ng-hide attribute to your default option:
<select ng-model="foo" ng-options="item as item.name for item in items">
<option value="" ng-if="foo">Select something to remove me.</option>
</select>
On your machine* run 'Set-Item WSMan:\localhost\Client\TrustedHosts -Value "$ipaddress"
*Machine from where you are running PSSession
The work by @JosephStyons and @Digs is great! I used parts of their work to create a new function for SQL Server 2016 and newer. This one also handles suffixes, as well as prefixes.
CREATE FUNCTION [dbo].[NameParser]
(
@name nvarchar(100)
)
RETURNS TABLE
AS
RETURN (
WITH prep AS (
SELECT
original = @name,
cleanName = REPLACE(REPLACE(REPLACE(REPLACE(LTRIM(RTRIM(@name)),' ',' '),' ',' '), '.', ''), ',', '')
)
SELECT
prep.original,
aux.prefix,
firstName.firstName,
middleName.middleName,
lastName.lastName,
aux.suffix
FROM
prep
CROSS APPLY (
SELECT
prefix =
CASE
WHEN LEFT(prep.cleanName, 3) IN ('MR ', 'MS ', 'DR ', 'FR ')
THEN LEFT(prep.cleanName, 2)
WHEN LEFT(prep.cleanName, 4) IN ('MRS ', 'LRD ', 'SIR ')
THEN LEFT(prep.cleanName, 3)
WHEN LEFT(prep.cleanName, 5) IN ('LORD ', 'LADY ', 'MISS ', 'PROF ')
THEN LEFT(prep.cleanName, 4)
ELSE ''
END,
suffix =
CASE
WHEN RIGHT(prep.cleanName, 3) IN (' JR', ' SR', ' II', ' IV')
THEN RIGHT(prep.cleanName, 2)
WHEN RIGHT(prep.cleanName, 4) IN (' III', ' ESQ')
THEN RIGHT(prep.cleanName, 3)
ELSE ''
END
) aux
CROSS APPLY (
SELECT
baseName = LTRIM(RTRIM(SUBSTRING(prep.cleanName, LEN(aux.prefix) + 1, LEN(prep.cleanName) - LEN(aux.prefix) - LEN(aux.suffix)))),
numParts = (SELECT COUNT(1) FROM STRING_SPLIT(LTRIM(RTRIM(SUBSTRING(prep.cleanName, LEN(aux.prefix) + 1, LEN(prep.cleanName) - LEN(aux.prefix) - LEN(aux.suffix)))), ' '))
) core
CROSS APPLY (
SELECT
firstName =
CASE
WHEN core.numParts <= 1 THEN core.baseName
ELSE LEFT(core.baseName, CHARINDEX(' ', core.baseName, 1) - 1)
END
) firstName
CROSS APPLY (
SELECT
remainder =
CASE
WHEN core.numParts <= 1 THEN ''
ELSE LTRIM(SUBSTRING(core.baseName, LEN(firstName.firstName) + 1, 999999))
END
) work1
CROSS APPLY (
SELECT
middleName =
CASE
WHEN core.numParts <= 2 THEN ''
ELSE LEFT(work1.remainder, CHARINDEX(' ', work1.remainder, 1) - 1)
END
) middleName
CROSS APPLY (
SELECT
lastName =
CASE
WHEN core.numParts <= 1 THEN ''
ELSE LTRIM(SUBSTRING(work1.remainder, LEN(middleName.middleName) + 1, 999999))
END
) lastName
)
GO
SELECT * FROM dbo.NameParser('Madonna')
SELECT * FROM dbo.NameParser('Will Smith')
SELECT * FROM dbo.NameParser('Neil Degrasse Tyson')
SELECT * FROM dbo.NameParser('Dr. Neil Degrasse Tyson')
SELECT * FROM dbo.NameParser('Mr. Hyde')
SELECT * FROM dbo.NameParser('Mrs. Thurston Howell, III')
php.ini
fileFor xampp, you can get it @ C:\xampp\php
memory_limit
post_max_size
upload_max_filesize
This works for me at runtime too:
UltraPictureBox1.Image = My.Resources.MyPicture
No strings involved and if I change the name it is automatically updated by refactoring.
In onclik function replace first line with this line u will definitely get right result.
if (passw1.getText().toString().equalsIgnoreCase("1234") && passw2.getText().toString().equalsIgnoreCase("1234")){
It depends. If you want to distinguish between no parameter passed in at all, and an empty string passed in, you could use None.
It is so simple in HTML5
<input type="search">
This will do your job!
I just ran into this problem with WAMP and the phpMyAdmin that comes with it. To remove the database and make the error go away. I went into C:\wamp\bin\mysql\mysql5.5.24\data\
and deleted the folder for the database in question.
Then I refreshed the page at phpMyAdmin, and the database was gone.
Here is a simple way to define those constants, and I'm pretty sure it's portable:
const double inf = 1.0/0.0;
const double nan = 0.0/0.0;
When I run this code:
printf("inf = %f\n", inf);
printf("-inf = %f\n", -inf);
printf("nan = %f\n", nan);
printf("-nan = %f\n", -nan);
I get:
inf = inf
-inf = -inf
nan = -nan
-nan = nan
spoulson has it nearly right, but you need to create a List<string>
from string[]
first. Actually a List<int>
would be better if uid is also int
. List<T>
supports Contains()
. Doing uid.ToString().Contains(string[])
would imply that the uid as a string contains all of the values of the array as a substring??? Even if you did write the extension method the sense of it would be wrong.
[EDIT]
Unless you changed it around and wrote it for string[]
as Mitch Wheat demonstrates, then you'd just be able to skip the conversion step.
[ENDEDIT]
Here is what you want, if you don't do the extension method (unless you already have the collection of potential uids as ints -- then just use List<int>()
instead). This uses the chained method syntax, which I think is cleaner, and
does the conversion to int to ensure that the query can be used with more providers.
var uids = arrayofuids.Select(id => int.Parse(id)).ToList();
var selected = table.Where(t => uids.Contains(t.uid));
from PIL import Image
image_file = Image.open("convert_image.png") # open colour image
image_file = image_file.convert('1') # convert image to black and white
image_file.save('result.png')
yields
At the beginning with the usepackage
definitions include:
\usepackage{placeins}
And before and after add:
\FloatBarrier
\begin{table}[h]
\begin{tabular}{llll}
....
\end{tabular}
\end{table}
\FloatBarrier
This places the table exactly where you want in the text.
Here is a section of my .vimrc
:
"insert and remove comments in visual and normal mode
vmap ,ic :s/^/#/g<CR>:let @/ = ""<CR>
map ,ic :s/^/#/g<CR>:let @/ = ""<CR>
vmap ,rc :s/^#//g<CR>:let @/ = ""<CR>
map ,rc :s/^#//g<CR>:let @/ = ""<CR>
In normal and in visual mode, this lets me press ,ic to insert comments and,rc to remove comments.
Check your servers error log, typically /var/log/apache2/error.log
.
SELECT *
FROM table
WHERE some_id = ANY(ARRAY[1, 2])
or ANSI
-compatible:
SELECT *
FROM table
WHERE some_id IN (1, 2)
The ANY
syntax is preferred because the array as a whole can be passed in a bound variable:
SELECT *
FROM table
WHERE some_id = ANY(?::INT[])
You would need to pass a string representation of the array: {1,2}
Import mplot3d whole to use "projection = '3d'".
Insert the command below in top of your script. It should run fine.
from mpl_toolkits import mplot3d
Chances are, you'll have cut
as well. If so:
[me@home]$ echo "pid: 1234" | cut -d" " -f2
1234
CSS:
.container {
position: relative;
width: 500px;
}
.container div {
height: 300px;
}
.column-left {
width: 33%;
left: 0;
background: #00F;
position: absolute;
}
.column-center {
width: 34%;
background: #933;
margin-left: 33%;
position: absolute;
}
.column-right {
width: 33%;
right: 0;
position: absolute;
background: #999;
}
HTML:
<div class="container">
<div class="column-center">Column center</div>
<div class="column-left">Column left</div>
<div class="column-right">Column right</div>
</div>
Here is the Demo : http://jsfiddle.net/nyitsol/f0dv3q3z/
There is a numpy built-in function to help with that.
import numpy as np
>>> a = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9])
>>> b = np.array([3,4,7])
>>> c = np.setdiff1d(a,b)
>>> c
array([1, 2, 5, 6, 8, 9])
Another solution might look like this,
char arr[] = "mom";
std::cout << "hi " << std::string(arr);
which avoids using an extra variable.
This has been working for me:
If you try uploading the new file as a war file, with tomcat still running, it will attempt to expand it before it is all there. It will fail. Having failed, it will not try again. Thus, uploading a www file, then renaming it, allows the whole war file to be present before tomcat notices it.
Hint, don't forget to check that the war file's owner is tomcat (Use chown)
Bootstrap 4:
<div class="w-100"></div>
Source: https://v4-alpha.getbootstrap.com/layout/grid/#equal-width-multi-row
The Microsoft Program Maintenance Utility (NMAKE.EXE) is a tool that builds projects based on commands contained in a description file.
start cmd /k "your cmd command1"
start cmd /k "your cmd command2"
It works in Windows server2012 while I use these command in one batch file.
A nice single-line trick to avoid early variable expansion is to use cmd /c echo ^%time^%
cmd /c echo ^%time^% & dir /s somelongcommand & cmd /c echo ^%time^%
// Regex - Check Singapore valid mobile numbers
public static boolean isSingaporeMobileNo(String str) {
Pattern mobNO = Pattern.compile("^(((0|((\\+)?65([- ])?))|((\\((\\+)?65\\)([- ])?)))?[8-9]\\d{7})?$");
Matcher matcher = mobNO.matcher(str);
if (matcher.find()) {
return true;
} else {
return false;
}
}
BeautifulSoup(text, features="html.parser").text
For the people who were seeking deep info in my answer, sorry.
I'll explain it.
Beautifulsoup is a widely use python package that helps the user (developer) to interact with HTML within python.
The above like just take all the HTML text (text
) and cast it to Beautifulsoup object - that means behind the sense its parses everything up (Every HTML tag within the given text)
Once done so, we just request all the text from within the HTML object.
//defines an array of 280 pointers (1120 or 2240 bytes)
int *pointer1 [280];
//defines a pointer (4 or 8 bytes depending on 32/64 bits platform)
int (*pointer2)[280]; //pointer to an array of 280 integers
int (*pointer3)[100][280]; //pointer to an 2D array of 100*280 integers
Using pointer2
or pointer3
produce the same binary except manipulations as ++pointer2
as pointed out by WhozCraig.
I recommend using typedef
(producing same binary code as above pointer3
)
typedef int myType[100][280];
myType *pointer3;
Note: Since C++11, you can also use keyword using
instead of typedef
using myType = int[100][280];
myType *pointer3;
in your example:
myType *pointer; // pointer creation
pointer = &tab1; // assignation
(*pointer)[5][12] = 517; // set (write)
int myint = (*pointer)[5][12]; // get (read)
Note: If the array tab1
is used within a function body => this array will be placed within the call stack memory. But the stack size is limited. Using arrays bigger than the free memory stack produces a stack overflow crash.
The full snippet is online-compilable at gcc.godbolt.org
int main()
{
//defines an array of 280 pointers (1120 or 2240 bytes)
int *pointer1 [280];
static_assert( sizeof(pointer1) == 2240, "" );
//defines a pointer (4 or 8 bytes depending on 32/64 bits platform)
int (*pointer2)[280]; //pointer to an array of 280 integers
int (*pointer3)[100][280]; //pointer to an 2D array of 100*280 integers
static_assert( sizeof(pointer2) == 8, "" );
static_assert( sizeof(pointer3) == 8, "" );
// Use 'typedef' (or 'using' if you use a modern C++ compiler)
typedef int myType[100][280];
//using myType = int[100][280];
int tab1[100][280];
myType *pointer; // pointer creation
pointer = &tab1; // assignation
(*pointer)[5][12] = 517; // set (write)
int myint = (*pointer)[5][12]; // get (read)
return myint;
}
You (and KMulligan) are misunderstanding _ViewStart
pages.
_ViewStart
will always execute, before your page starts.
It is intended to be used to initialize properties (such as Layout
); it generally should not contain markup. (Since there is no way to override it).
The correct pattern is to make a separate layout page which calls RenderBody
, and set the Layout
property to point to this page in _ViewStart
.
You can then change Layout
in your content pages, and the changes will take effect.
If you want truly "cryptographically strong" randomness, then you need a strong entropy source. /dev/random
is slow because it has to wait for system events to gather entropy (disk reads, network packets, mouse movement, key presses, etc.).
A faster solution is a hardware random number generator. You may already have one built-in to your motherboard; check out the hw_random documentation for instructions on figuring out if you have it, and how to use it. The rng-tools package includes a daemon which will feed hardware generated entropy into /dev/random
.
If a HRNG is not available on your system, and you are willing to sacrifice entropy strength for performance, you will want to seed a good PRNG with data from /dev/random
, and let the PRNG do the bulk of the work. There are several NIST-approved PRNG's listed in SP800-90 which are straightforward to implement.
Run the code either in onload event, either just before you close body
tag.
You try to find an element wich is not there at the moment you do it.
Below is extension method to check for null if you want to sort on child property of a keySelector.
public static IOrderedEnumerable<T> NullableOrderBy<T>(this IEnumerable<T> list, Func<T, object> parentKeySelector, Func<T, object> childKeySelector)
{
return list.OrderBy(v => parentKeySelector(v) != null ? 0 : 1).ThenBy(childKeySelector);
}
And simple use it like:
var sortedList = list.NullableOrderBy(x => x.someObject, y => y.someObject?.someProperty);
NSString * varyingString = ...;
NSString * cat = [NSString stringWithFormat:@"%s%@%@",
"first part of string",
varyingString,
@"third part of string"];
or simply -[NSString stringByAppendingString:]
public static String[] textSort(String[] words) {
for (int i = 0; i < words.length; i++) {
for (int j = i + 1; j < words.length; j++) {
if (words[i].compareTo(words[j]) > 0) {
String temp = words[i];
words[i] = words[j];
words[j] = temp;
}
}
}
return words;
}
I had to implement a year diff function which works similarly to sybase datediff. In that case the real year difference is counted, not the rounded day difference. So if there are two dates separated by one day, the year difference can be 1 (see select datediff(year, '20141231', '20150101')
).
If the year diff has to be counted this way then use:
EXTRACT(YEAR FROM date_to) - EXTRACT(YEAR FROM date_from)
Just for the log the (almost) complete datediff function:
CREATE OR REPLACE FUNCTION datediff (datepart IN VARCHAR2, date_from IN DATE, date_to IN DATE)
RETURN NUMBER
AS
diff NUMBER;
BEGIN
diff := CASE datepart
WHEN 'day' THEN TRUNC(date_to,'DD') - TRUNC(date_from, 'DD')
WHEN 'week' THEN (TRUNC(date_to,'DAY') - TRUNC(date_from, 'DAY')) / 7
WHEN 'month' THEN MONTHS_BETWEEN(TRUNC(date_to, 'MONTH'), TRUNC(date_from, 'MONTH'))
WHEN 'year' THEN EXTRACT(YEAR FROM date_to) - EXTRACT(YEAR FROM date_from)
END;
RETURN diff;
END;";
With version 3 of the Google Maps API, the easiest way to do this may be by grabbing a custom icon set, like the one that Benjamin Keen has created here:
http://www.benjaminkeen.com/?p=105
If you put all of those icons at the same place as your map page, you can colorize a Marker simply by using the appropriate icon option when creating it:
var beachMarker = new google.maps.Marker({
position: myLatLng,
map: map,
icon: 'brown_markerA.png'
});
This is super-easy, and is the approach I'm using for the project I'm working on currently.
Which would you rather write and maintain?
ASP.NET MVC
public class TweetsController : Controller {
// GET: /Tweets/
[HttpGet]
public ActionResult Index() {
return Json(Twitter.GetTweets(), JsonRequestBehavior.AllowGet);
}
}
ASP.NET Web API
public class TweetsController : ApiController {
// GET: /Api/Tweets/
public List<Tweet> Get() {
return Twitter.GetTweets();
}
}
import numpy as np
# any two python array as two points
a = [0, 0]
b = [3, 4]
You first change list to numpy array and do like this: print(np.linalg.norm(np.array(a) - np.array(b)))
. Second method directly from python list as: print(np.linalg.norm(np.subtract(a,b)))
I just want to share the fact that my apk file was saved to my app "Data" directory and that I needed to change the permissions on the apk file to be world readable in order to allow it to be installed that way, otherwise the system was throwing "Parse error: There is a Problem Parsing the Package"; so using solution from @Horaceman that makes:
File file = new File(dir, "App.apk");
file.setReadable(true, false);
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(Uri.fromFile(file), "application/vnd.android.package-archive");
startActivity(intent);
A solution using assignment expressions (added in Python 3.8):
def is_sorted(seq):
seq_iter = iter(seq)
cur = next(seq_iter, None)
return all((prev := cur) <= (cur := nxt) for nxt in seq_iter)
z = list(range(10))
print(z)
print(is_sorted(z))
import random
random.shuffle(z)
print(z)
print(is_sorted(z))
z = []
print(z)
print(is_sorted(z))
Gives:
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
True
[1, 7, 5, 9, 4, 0, 8, 3, 2, 6]
False
[]
True
is_numeric would accept "-0.5e+12" as a valid ID.
object.__del__(self)
is called when the instance is about to be destroyed.
>>> class Test:
... def __del__(self):
... print "deleted"
...
>>> test = Test()
>>> del test
deleted
Object is not deleted unless all of its references are removed(As quoted by ethan)
Also, From Python official doc reference:
del x doesn’t directly call x.del() — the former decrements the reference count for x by one, and the latter is only called when x‘s reference count reaches zero
Another solution is to use a state and lifecycle hooks in the routed component and a search statement in the to
property of the <Link />
component. The search parameters can later be accessed via new URLSearchParams()
;
<Link
key={id}
to={{
pathname: this.props.match.url + '/' + foo,
search: '?foo=' + foo
}} />
<Route path="/details/:foo" component={DetailsPage}/>
export default class DetailsPage extends Component {
state = {
foo: ''
}
componentDidMount () {
this.parseQueryParams();
}
componentDidUpdate() {
this.parseQueryParams();
}
parseQueryParams () {
const query = new URLSearchParams(this.props.location.search);
for (let param of query.entries()) {
if (this.state.foo!== param[1]) {
this.setState({foo: param[1]});
}
}
}
render() {
return(
<div>
<h2>{this.state.foo}</h2>
</div>
)
}
}
You can scale the image with pygame.transform.scale
:
import pygame
picture = pygame.image.load(filename)
picture = pygame.transform.scale(picture, (1280, 720))
You can then get the bounding rectangle of picture
with
rect = picture.get_rect()
and move the picture with
rect = rect.move((x, y))
screen.blit(picture, rect)
where screen
was set with something like
screen = pygame.display.set_mode((1600, 900))
To allow your widgets to adjust to various screen sizes, you could make the display resizable:
import os
import pygame
from pygame.locals import *
pygame.init()
screen = pygame.display.set_mode((500, 500), HWSURFACE | DOUBLEBUF | RESIZABLE)
pic = pygame.image.load("image.png")
screen.blit(pygame.transform.scale(pic, (500, 500)), (0, 0))
pygame.display.flip()
while True:
pygame.event.pump()
event = pygame.event.wait()
if event.type == QUIT:
pygame.display.quit()
elif event.type == VIDEORESIZE:
screen = pygame.display.set_mode(
event.dict['size'], HWSURFACE | DOUBLEBUF | RESIZABLE)
screen.blit(pygame.transform.scale(pic, event.dict['size']), (0, 0))
pygame.display.flip()
To expand on the accepted answer, I just wanted to provide another reason why real
? user
+ sys
.
Keep in mind that real
represents actual elapsed time, while user
and sys
values represent CPU execution time. As a result, on a multicore system, the user
and/or sys
time (as well as their sum) can actually exceed the real time. For example, on a Java app I'm running for class I get this set of values:
real 1m47.363s
user 2m41.318s
sys 0m4.013s
yes - take a look at setInterval
and setTimeout
for executing code at certain times. setInterval would be the one to use to execute code periodically.
See a demo and answer here for usage
We can use input data to pass it as a parameter in the HTML file w use ng-model to bind the value of input field.
<input type="text" placeholder="Enter your Email" ng-model="email" required>
<input type="text" placeholder="Enter your password " ng-model="password" required>
and in the js file w use $scope to access this data:
$scope.email="";
$scope.password="";
Controller function will be something like that:
var app = angular.module('myApp', []);
app.controller('assignController', function($scope, $http) {
$scope.email="";
$scope.password="";
$http({
method: "POST",
url: "http://localhost:3000/users/sign_in",
params: {email: $scope.email, password: $scope.password}
}).then(function mySuccess(response) {
// a string, or an object, carrying the response from the server.
$scope.myRes = response.data;
$scope.statuscode = response.status;
}, function myError(response) {
$scope.myRes = response.statusText;
});
});
Don't specify the column or value when inserting and the DEFAULT constaint's value will be substituted for the missing value.
I don't know how this would work in a single column table. I mean: it would, but it wouldn't be very useful.
ReportClass report = (ReportClass)Activator.CreateInstance(Type.GetType(reportClass));
why do u want to write a code like this? If you have a class 'ReportClass' is available, you can instantiate it directly as shown below.
ReportClass report = new ReportClass();
The code ReportClass report = (ReportClass)Activator.CreateInstance(Type.GetType(reportClass));
is used when you dont have the necessary class available, but you want to instantiate and or or invoke a method dynamically.
I mean it is useful when u know the assembly but while writing the code you dont have the class ReportClass
available.
You have done it backwards, it should be:
amount = invest(amount,top_company(5,year,year+1),year)
I found python in 1988 and fell in love with it. Our group at work had been dissolved and we were looking for other jobs on site, so I had a couple of months to play around doing whatever I wanted to. I spent the time profitably learning and using python. I suggest you spend time thinking up and writing utilities and various useful tools. I've got 200-300 in my python tools library now (can't even remember them all). I learned python from Guido's tutorial, which is a good place to start (a C programmer will feel right at home).
python is also a great tool for making models -- physical, math, stochastic, etc. Use numpy and scipy. It also wouldn't hurt to learn some GUI stuff -- I picked up wxPython and learned it, as I had some experience using wxWidgets in C++. wxPython has some impressive demo stuff!
I was getting the same issue with a different application,
Faulting application name: javaw.exe, version: 8.0.51.16, time stamp: 0x55763d32
Faulting module name: mscorwks.dll, version: 2.0.50727.5485, time stamp: 0x53a11d6c
Exception code: 0xc0000005
Fault offset: 0x0000000000501090
Faulting process id: 0x2960
Faulting application start time: 0x01d0c39a93c695f2
Faulting application path: C:\Program Files\Java\jre1.8.0_51\bin\javaw.exe
Faulting module path:C:\Windows\Microsoft.NET\Framework64\v2.0.50727\mscorwks.dll
I was using the The Enhanced Mitigation Experience Toolkit (EMET) from Microsoft and I found by disabling the EMET features on javaw.exe in my case as this was the faulting application, it enabled my application to run successfully. Make sure you don't have any similar software with security protections on memory.
+ theme(plot.title = element_text(size=22))
Here is the full set of things you can change in element_text
:
element_text(family = NULL, face = NULL, colour = NULL, size = NULL,
hjust = NULL, vjust = NULL, angle = NULL, lineheight = NULL,
color = NULL)
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");
This is the correct way:
To execute code that will only be available to the index page, we could use this syntax:
$(document).on('pageinit', "#index", function() {
...
});
I would use a single Context class inheriting from IdentityDbContext. This way you can have the context be aware of any relations between your classes and the IdentityUser and Roles of the IdentityDbContext. There is very little overhead in the IdentityDbContext, it is basically a regular DbContext with two DbSets. One for the users and one for the roles.
For gradle
compile('org.xxx:xxx:1.0-SNAPSHOT'){
exclude module: 'log4j'
exclude module: 'slf4j-log4j12'
}
There's a lot more to abstract classes than default method implementations (such as private state), but as of Java 8, whenever you have the choice of either, you should go with the defender (aka. default
) method in the interface.
The constraint on the default method is that it can be implemented only in the terms of calls to other interface methods, with no reference to a particular implementation's state. So the main use case is higher-level and convenience methods.
The good thing about this new feature is that, where before you were forced to use an abstract class for the convenience methods, thus constraining the implementor to single inheritance, now you can have a really clean design with just the interface and a minimum of implementation effort forced on the programmer.
The original motivation to introduce default
methods to Java 8 was the desire to extend the Collections Framework interfaces with lambda-oriented methods without breaking any existing implementations. Although this is more relevant to the authors of public libraries, you may find the same feature useful in your project as well. You've got one centralized place where to add new convenience and you don't have to rely on how the rest of the type hierarchy looks.
class Globals {
static String ouch = "I'm global.."
}
println Globals.ouch
What are you using to compile this? If there's an undefined reference error, usually it's because the .o file (which gets created from the .cpp file) doesn't exist and your compiler/build system is not able to link it.
Also, in your card.cpp, the function should be Card::Card()
instead of void Card
. The Card::
is scoping; it means that your Card()
function is a member of the Card class (which it obviously is, since it's the constructor for that class). Without this, void Card is just a free function. Similarly,
void Card(Card::Rank rank, Card::Suit suit)
should be
Card::Card(Card::Rank rank, Card::Suit suit)
Also, in deck.cpp, you are saying #include "Deck.h"
even though you referred to it as deck.h. The includes are case sensitive.
import urllib2
import time
max_attempts = 80
attempts = 0
sleeptime = 10 #in seconds, no reason to continuously try if network is down
#while true: #Possibly Dangerous
while attempts < max_attempts:
time.sleep(sleeptime)
try:
response = urllib2.urlopen("http://example.com", timeout = 5)
content = response.read()
f = open( "local/index.html", 'w' )
f.write( content )
f.close()
break
except urllib2.URLError as e:
attempts += 1
print type(e)
echo ABSPATH;
// This shows the absolute path of WordPress
ABSPATH
is a constant defined in the wp-config.php file.
Scott gives a good example of how to do it, but the question is why would you want to? If you need to do a find-and-replace on a specific string, you could also try doing a mysqldump of your database, do a find-and-replace in an editor, then re-load the database.
Maybe if you gave some background on what you are trying to achieve, others might be able to provide better answers.
One way which I'm currently using measures the spread of edges in the image. Look for this paper:
@ARTICLE{Marziliano04perceptualblur,
author = {Pina Marziliano and Frederic Dufaux and Stefan Winkler and Touradj Ebrahimi},
title = {Perceptual blur and ringing metrics: Application to JPEG2000,” Signal Process},
journal = {Image Commun},
year = {2004},
pages = {163--172} }
It's usually behind a paywall but I've seen some free copies around. Basically, they locate vertical edges in an image, and then measure how wide those edges are. Averaging the width gives the final blur estimation result for the image. Wider edges correspond to blurry images, and vice versa.
This problem belongs to the field of no-reference image quality estimation. If you look it up on Google Scholar, you'll get plenty of useful references.
EDIT
Here's a plot of the blur estimates obtained for the 5 images in nikie's post. Higher values correspond to greater blur. I used a fixed-size 11x11 Gaussian filter and varied the standard deviation (using imagemagick's convert
command to obtain the blurred images).
If you compare images of different sizes, don't forget to normalize by the image width, since larger images will have wider edges.
Finally, a significant problem is distinguishing between artistic blur and undesired blur (caused by focus miss, compression, relative motion of the subject to the camera), but that is beyond simple approaches like this one. For an example of artistic blur, have a look at the Lenna image: Lenna's reflection in the mirror is blurry, but her face is perfectly in focus. This contributes to a higher blur estimate for the Lenna image.
I had this issue in xcode 6 and there is a way to resolve the resize conflicts. If you select your view, at the bottom you will see an icon that looks like |-Δ-|. If you click on it, you're project will resize for different devices.
Well one of the option is to goto your workspace, your project folder, then bin copy and paste the log4j properites file. it would be better to paste the file also in source folder.
Now you may want to know from where to get this file, download smslib, then extract it, then smslib->misc->log4j sample configuration -> log4j here you go.
This what helped,me so just wanted to know.
By default Mysql store and return ‘date’ data type values in “YYYY/MM/DD” format. So if we want to display date in different format then we have to format date values as per our requirement in scripting language
And by the way what is the column data type and in which format you are storing the value.
This worked for me, just use the escape
'%\_%'
Use this
//*[@id='popover-search']/div/div/ul/li[1]/a/span[contains(text(),'Some text')]
OR
//*[@id='popover-search']/div/div/ul/li[1]/a/span[contains(.,'Some text')]
The problem is, os.path.join
doesn't take a list
as argument, it has to be separate arguments.
This is where *
, the 'splat' operator comes into play...
I can do
>>> s = "c:/,home,foo,bar,some.txt".split(",")
>>> os.path.join(*s)
'c:/home\\foo\\bar\\some.txt'
My Attempt ( JsFiddle)
Javascript
$(document).ready(function () {
$('#buttons input[type=button]').on('click', function () {
var qty = $(this).data('quantity');
var price = $('#totalPrice').text();
$('#count').val(price * qty);
});
});
Html
Product price:$500
<br>Total price: $<span id='totalPrice'>500</span>
<br>
<div id='buttons'>
<input id='qty2' type="button" data-quantity='2' value="2
Qty">
<input id='qty2' type="button" class="mnozstvi_sleva" data-quantity='4' value="4
Qty">
</div>
<br>Total
<input type="text" id="count" value="1">
The host is either down or very slow to respond. If it's slow to respond, you can try increasing the timeout via the connection_timeout
option or via the default_socket_timeout
setting and see if that reduces the failures.
http://www.php.net/manual/en/soapclient.soapclient.php
http://www.php.net/manual/en/filesystem.configuration.php#ini.default-socket-timeout
You can also include error handling as zanlok pointed out to retry a few times. If you have users actually waiting on these SOAP calls then you'll want to queue them up and process them in the background and notify the user when they're finished.
I found the answer.
Cast integer to string:
myOldIntValue|string
Cast string to integer:
myOldStrValue|int
_x000D_
table tbody_x000D_
{_x000D_
border:1px solid red;_x000D_
}_x000D_
table td_x000D_
{_x000D_
background:yellow;_x000D_
_x000D_
border-bottom:1px solid green;_x000D_
_x000D_
_x000D_
}_x000D_
.tr0{_x000D_
line-height:0;_x000D_
}_x000D_
.tr0 td{_x000D_
background:red;_x000D_
}
_x000D_
<table>_x000D_
<tbody>_x000D_
<tr><td>test</td></tr>_x000D_
<tr><td>test</td></tr> _x000D_
<tr class="tr0"><td></td></tr>_x000D_
</tbody>_x000D_
</table>
_x000D_
I've found two ways that work regardless of the date settings.
On my pc, date/t returns 2009-05-27
You can either access the registry and read the regional settings (HKEY_CURRENT_USER\Control Panel\International)
Or use a vbscript. This is the ugly batch file/vbscript hybrid I created some time ago....
@Echo Off
set rnd=%Random%
set randfilename=x%rnd%.vbs
::create temp vbscript file
Echo Dim DayofWeek(7) > %temp%\%randfilename%
Echo DayofWeek(1)="Sun" >> %temp%\%randfilename%
Echo DayofWeek(2)="Mon" >> %temp%\%randfilename%
Echo DayofWeek(3)="Tue" >> %temp%\%randfilename%
Echo DayofWeek(4)="Wed" >> %temp%\%randfilename%
Echo DayofWeek(5)="Thu" >> %temp%\%randfilename%
Echo DayofWeek(6)="Fri" >> %temp%\%randfilename%
Echo DayofWeek(7)="Sat" >> %temp%\%randfilename%
Echo DayofWeek(0)=DayofWeek(Weekday(now)) >> %temp%\%randfilename%
Echo Mon=Left(MonthName(Month(now),1),3) >> %temp%\%randfilename%
Echo MonNumeric=right ( "00" ^& Month(now) , 2) >> %temp%\%randfilename%
Echo wscript.echo ( Year(Now) ^& " " ^& MonNumeric ^& " " ^& Mon ^& " " _ >> %temp%\%randfilename%
Echo ^& right("00" ^& Day(now),2) ^& " "^& dayofweek(0) ^& " "^& _ >> %temp%\%randfilename%
Echo right("00" ^& Hour(now),2)) _ >> %temp%\%randfilename%
Echo ^&":"^& Right("00" ^& Minute(now),2) ^&":"^& Right("00" ^& Second(Now),2) >> %temp%\%randfilename%
::set the output into vars
if "%1" == "" FOR /f "usebackq tokens=1,2,3,4,5,6" %%A in (`start /wait /b cscript //nologo %temp%\%randfilename%`) do Set Y2KYear=%%A& Set MonthNumeric=%%B& Set Month=%%C& Set Day=%%D& Set DayofWeek=%%E& Set Time=%%F
set year=%y2kyear:~2,2%
::cleanup
del %temp%\%randfilename%
It's not pretty, but it works.
I tried this, but it is not possible to remove "Watch on YouTube" icon. Following solution of mine does not remove the icon itself but "blocks" the mouse hover so that watch on YouTube is not click-able. I added a div over icon, so no mouseover will be affected for that logo.
<div class="holder">
<div class="frame" id="player" style="height 350"></div>
<div class="bar" id="bottom-layer">.</div>
</div>
Where frame is my embedded player. include following to your css file
.holder{
position:relative;
width:640px;
height:350px;
}
.frame{
width: 100%;
height:100%;
}
.bar{
position:absolute;
bottom:0;
right:0;
width:100%;
height:40px;
}
This is not full solution but helps you if you are bothered with users' getting full youtube url.
Command mvnw
uses Maven that is by default downloaded to ~/.m2/wrapper
on the first use.
URL with Maven is specified in each project at .mvn/wrapper/maven-wrapper.properties
:
distributionUrl=https://repo1.maven.org/maven2/org/apache/maven/apache-maven/3.3.9/apache-maven-3.3.9-bin.zip
To update or change Maven version invoke the following (remember about --non-recursive
for multi-module projects):
./mvnw io.takari:maven:wrapper -Dmaven=3.3.9
or just modify .mvn/wrapper/maven-wrapper.properties
manually.
To generate wrapper from scratch using Maven (you need to have it already in PATH
run:
mvn io.takari:maven:wrapper -Dmaven=3.3.9
I'd use standard javascript:
for (var m in myMap){
for (var i=0;i<myMap[m].length;i++){
... do something with myMap[m][i] ...
}
}
Note the different ways of treating objects and arrays.
Remove the directory ~/.gradle/caches/. It's OK to do this while Android Studio is opened. (Refer pm installing wrong package name) Press "Sync project with Gradle files" icon on Android Studio Run the project and the remote path will be correct.
Refer answer @ Android Studio gets package name wrong when running .apk
There is a new cross plateform (java) and open source tool, that enable you to do that, just checkout https://bytecodeviewer.com
=========
EDIT: As of April 2017, there is a new open source tool developed by google, that is meant to do just what we have been looking for => https://github.com/google/android-classyshark
Although the top answers are correct, I personally like to work with attached properties to enable the solution to be applied to any UIElement
, especially when the Window
is not aware of the element that should be focused. In my experience I often see a composition of several view models and user controls, where the window is often nothing more that the root container.
public sealed class AttachedProperties
{
// Define the key gesture type converter
[System.ComponentModel.TypeConverter(typeof(System.Windows.Input.KeyGestureConverter))]
public static KeyGesture GetFocusShortcut(DependencyObject dependencyObject)
{
return (KeyGesture)dependencyObject?.GetValue(FocusShortcutProperty);
}
public static void SetFocusShortcut(DependencyObject dependencyObject, KeyGesture value)
{
dependencyObject?.SetValue(FocusShortcutProperty, value);
}
/// <summary>
/// Enables window-wide focus shortcut for an <see cref="UIElement"/>.
/// </summary>
// Using a DependencyProperty as the backing store for FocusShortcut. This enables animation, styling, binding, etc...
public static readonly DependencyProperty FocusShortcutProperty =
DependencyProperty.RegisterAttached("FocusShortcut", typeof(KeyGesture), typeof(AttachedProperties), new FrameworkPropertyMetadata(null, FrameworkPropertyMetadataOptions.None, new PropertyChangedCallback(OnFocusShortcutChanged)));
private static void OnFocusShortcutChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
if (!(d is UIElement element) || e.NewValue == e.OldValue)
return;
var window = FindParentWindow(d);
if (window == null)
return;
var gesture = GetFocusShortcut(d);
if (gesture == null)
{
// Remove previous added input binding.
for (int i = 0; i < window.InputBindings.Count; i++)
{
if (window.InputBindings[i].Gesture == e.OldValue && window.InputBindings[i].Command is FocusElementCommand)
window.InputBindings.RemoveAt(i--);
}
}
else
{
// Add new input binding with the dedicated FocusElementCommand.
// see: https://gist.github.com/shuebner20/349d044ed5236a7f2568cb17f3ed713d
var command = new FocusElementCommand(element);
window.InputBindings.Add(new InputBinding(command, gesture));
}
}
}
With this attached property you can define a focus shortcut for any UIElement. It will automatically register the input binding at the window containing the element.
<TextBox x:Name="SearchTextBox"
Text={Binding Path=SearchText}
local:AttachedProperties.FocusShortcutKey="Ctrl+Q"/>
The full sample including the FocusElementCommand implementation is available as gist: https://gist.github.com/shuebner20/c6a5191be23da549d5004ee56bcc352d
Disclaimer: You may use this code everywhere and free of charge. Please keep in mind, that this is a sample that is not suitable for heavy usage. For example, there is no garbage collection of removed elements because the Command will hold a strong reference to the element.
Simple install
pip3 install PyQt5==5.9.2
It works for me.
The github project JavaScript-Load-Image provides a complete solution to the EXIF orientation problem, correctly rotating/mirroring images for all 8 exif orientations. See the online demo of javascript exif orientation
The image is drawn onto an HTML5 canvas. Its correct rendering is implemented in js/load-image-orientation.js through canvas operations.
Hope this saves somebody else some time, and teaches the search engines about this open source gem :)
If you call a new window UI statement in an existing thread, it throws an error. Instead of that create a new thread inside the main thread and write the window UI statement in the new child thread.
One can catch that you may change it through windows registry key
(SQLEXPRESS instance):
"Software\Microsoft\Microsoft SQL Server\SQLEXPRESS\LoginMode" = 2
... and restart service
The Location
property has type Point
which is a struct.
Instead of trying to modify the existing Point
, try assigning a new Point
object:
this.balancePanel.Location = new Point(
this.optionsPanel.Location.X,
this.balancePanel.Location.Y
);
Previous answers are correct but here is one more way of doing this and some tips:
Option #1 Go to you Jenkins job and search for "add build step" and then just copy and paste your script there
Option #2 Go to Jenkins and do the same again "add build step" but this time put the fully qualified path for your script in there example : ./usr/somewhere/helloWorld.sh
things to watch for /tips:
Could be due to the TCP protocol turned off.
How to check/enable: https://dba.stackexchange.com/questions/11377/cannot-connect-to-ms-sql-2008-r2-by-dbvisualizer-native-sspi-library-not-loade/144097#144097
You can directly apply slice()
to the variable. StackBlitz Demo
<li *ngFor="let item of list.slice(0, 10);">
{{item.text}}
</li>
Try:
range(x1,x2+1)
That is a list in Python 2.x and behaves mostly like a list in Python 3.x. If you are running Python 3 and need a list that you can modify, then use:
list(range(x1,x2+1))
You are very close; currently you compare the row[2]
with integer 0
, make the comparison with the string "0"
. When you read the data from a file, it is a string and not an integer, so that is why your integer check fails currently:
row[2]!="0":
Also, you can use the with
keyword to make the current code slightly more pythonic so that the lines in your code are reduced and you can omit the .close
statements:
import csv
with open('first.csv', 'rb') as inp, open('first_edit.csv', 'wb') as out:
writer = csv.writer(out)
for row in csv.reader(inp):
if row[2] != "0":
writer.writerow(row)
Note that input
is a Python builtin, so I've used another variable name instead.
Edit: The values in your csv file's rows are comma and space separated; In a normal csv, they would be simply comma separated and a check against "0"
would work, so you can either use strip(row[2]) != 0
, or check against " 0"
.
The better solution would be to correct the csv format, but in case you want to persist with the current one, the following will work with your given csv file format:
$ cat test.py
import csv
with open('first.csv', 'rb') as inp, open('first_edit.csv', 'wb') as out:
writer = csv.writer(out)
for row in csv.reader(inp):
if row[2] != " 0":
writer.writerow(row)
$ cat first.csv
6.5, 5.4, 0, 320
6.5, 5.4, 1, 320
$ python test.py
$ cat first_edit.csv
6.5, 5.4, 1, 320
It sounds as you really just want to track the changes made to the model, not to actually keep an untracked model in memory. May I suggest an alternative approach wich will remove the problem entirely?
EF will automticallly track changes for you. How about making use of that built in logic?
Ovverride SaveChanges()
in your DbContext
.
public override int SaveChanges()
{
foreach (var entry in ChangeTracker.Entries<Client>())
{
if (entry.State == EntityState.Modified)
{
// Get the changed values.
var modifiedProps = ObjectStateManager.GetObjectStateEntry(entry.EntityKey).GetModifiedProperties();
var currentValues = ObjectStateManager.GetObjectStateEntry(entry.EntityKey).CurrentValues;
foreach (var propName in modifiedProps)
{
var newValue = currentValues[propName];
//log changes
}
}
}
return base.SaveChanges();
}
Good examples can be found here:
Entity Framework 6: audit/track changes
Implementing Audit Log / Change History with MVC & Entity Framework
EDIT:
Client
can easily be changed to an interface. Let's say ITrackableEntity
. This way you can centralize the logic and automatically log all changes to all entities that implement a specific interface. The interface itself doesn't have any specific properties.
public override int SaveChanges()
{
foreach (var entry in ChangeTracker.Entries<ITrackableClient>())
{
if (entry.State == EntityState.Modified)
{
// Same code as example above.
}
}
return base.SaveChanges();
}
Also, take a look at eranga's great suggestion to subscribe instead of actually overriding SaveChanges().
Assuming that your original dataset is similar to the one you created (i.e. with NA
as character
. You could specify na.strings
while reading the data using read.table
. But, I guess NAs would be detected automatically.
The price
column is factor
which needs to be converted to numeric
class. When you use as.numeric
, all the non-numeric elements (i.e. "NA"
, FALSE) gets coerced to NA
) with a warning.
library(dplyr)
df %>%
mutate(price=as.numeric(as.character(price))) %>%
group_by(company, year, product) %>%
summarise(total.count=n(),
count=sum(is.na(price)),
avg.price=mean(price,na.rm=TRUE),
max.price=max(price, na.rm=TRUE))
I am using the same dataset
(except the ...
row) that was showed.
df = tbl_df(data.frame(company=c("Acme", "Meca", "Emca", "Acme", "Meca","Emca"),
year=c("2011", "2010", "2009", "2011", "2010", "2013"), product=c("Wrench", "Hammer",
"Sonic Screwdriver", "Fairy Dust", "Kindness", "Helping Hand"), price=c("5.67",
"7.12", "12.99", "10.99", "NA",FALSE)))
Check Safari developer reference on Touch class.
According to this, pageX/Y should be available - maybe you should check spelling? make sure it's pageX
and not PageX
When I create a root class, whose methods I defined using the arrow functions. When inheriting and overwriting the original function I noticed the same issue.
class C {
x = () => 1;
};
class CC extends C {
x = (foo) => super.x() + foo;
};
let add = new CC;
console.log(add.x(4));
this is solved by defining the method of the parent class without arrow functions
class C {
x() {
return 1;
};
};
class CC extends C {
x = foo => super.x() + foo;
};
let add = new CC;
console.log(add.x(4));
Note, that Dijkstra works even for negative weights, if the Graph has no negative cycles, i.e. cycles whose summed up weight is less than zero.
Of course one might ask, why in the example made by templatetypedef Dijkstra fails even though there are no negative cycles, infact not even cycles. That is because he is using another stop criterion, that holds the algorithm as soon as the target node is reached (or all nodes have been settled once, he did not specify that exactly). In a graph without negative weights this works fine.
If one is using the alternative stop criterion, which stops the algorithm when the priority-queue (heap) runs empty (this stop criterion was also used in the question), then dijkstra will find the correct distance even for graphs with negative weights but without negative cycles.
However, in this case, the asymptotic time bound of dijkstra for graphs without negative cycles is lost. This is because a previously settled node can be reinserted into the heap when a better distance is found due to negative weights. This property is called label correcting.
import sys
sys.stdout = open('stdout.txt', 'w')
Alternatively, in python 3.6+, you can generate Unicode superscript and copy paste that in your code:
ax1.set_ylabel('Rate (min?¹)')
Similar approach to @Samuel-bergström:
@font-face {_x000D_
font-family: 'FontAwesome';_x000D_
//src: url('@{fa-font-path}/fontawesome-webfont.eot?v=@{fa-version}');_x000D_
src: _x000D_
//url('@{fa-font-path}/fontawesome-webfont.eot?#iefix&v=@{fa-version}') format('embedded-opentype'),_x000D_
//url('@{fa-font-path}/fontawesome-webfont.woff2?v=@{fa-version}') format('woff2'),_x000D_
url('@{fa-font-path}/fontawesomeregular.woff?v=@{fa-version}') format('woff'),_x000D_
url('@{fa-font-path}/fontawesomeregular.ttf?v=@{fa-version}') format('truetype'),_x000D_
url('@{fa-font-path}/fontawesomeregular.svg?v=@{fa-version}#fontawesomeregular') format('svg');_x000D_
// src: url('@{fa-font-path}/FontAwesome.otf') format('opentype'); // used when developing fonts_x000D_
font-weight: normal;_x000D_
font-style: normal;_x000D_
}
_x000D_
I know it may be 'controversial' to comment out other file types, but happy to hear how to generate .eot or .otf files in the comments.
and finally, as Samuel mentions, update your CSS/LESS with:
.fa-XXX:before { content: "\f501"; }
I imagine setting float:left for the dialog will work. Presumably the dialog is absolutely positioned by the plugin, in which case its position will be determined by this, but the side-effect of float - making elements only as wide as they need to be to hold content - will still take effect.
This should work if you just put a rule like
.myDialog {float:left}
in your stylesheet, though you may need to set it using jQuery
Given your edit i assume you have the class name as a string and want to instantiate the class? Just use a dictionary as a dispatcher.
class Foo(object):
pass
class Bar(object):
pass
dispatch_dict = {"Foo": Foo, "Bar": Bar}
dispatch_dict["Foo"]() # returns an instance of Foo
This is an oversimplification of the many variants of these design patterns, but this is how I like to think about the differences between the two.
MVC
MVP
To put breakpoints in your code, double click in the left margin on the line you want execution to stop on. You may alternatively put your cursor in this line and then press Shift+Ctrl+B.
To control execution use the Step Into, Step Over and Step Return buttons. They have the shortcuts F5, F6 and F7 respectively.
To allow execution to continue normally or until it hits the next breakpoint, hit the Resume button or F8.
On a rooted device, the correct solution is this:
Open cmd
Change your directory and go into 'Platform tools'
Type 'adb shell'
su
Press 'Allow' on device
chmod 777 /data /data/data /data/data/*
Open DDMS view in Eclipse/IntelliJ and from there open 'FileExplorer' to get your desired file
The original solution worked, but the chmod would return unknown directory. Changing the chmod command to /data/data/* gave access to all subfolders in the data directory from DDMS in Intellij. I assume the same solution is true for Eclipse DDMS.
UPDATE So, what I've found is strange. I'm running a Nexus 6 using DDMS in IntelliJ (Android Device Monitor). I have built a little starter app. Said app saves data to a .csv file in data/data/com.example.myapp/files
When I first started to try to access this file on my Nexus 6, I found that I have to root the device.. I could see the data folder, but trying to open it would not work. As mentioned online in other places, the expand + would vanish then reappear shortly thereafter (note, there are solutions on the web that claim to allow access to these folders without rooting, I didn't find them till too late, and I'm not sure if I prefer not to root anyway ((I'd rather be able to do it manually than rely on an app or command prompt to give me my solutions))). I rooted my 6 and tried DDMS again.
At this point, it showed me the data folder and I could expand the folder and see the com. directories, but I could not open any of them. That is when I discovered the above solution. The initial instructions would not work on this part:
chmod 777 /data /data/data /data/data/com.application.pacakage /data/data/com.application.pacakage/*
That is when I tried the solution I posted:
chmod 777 /data /data/data /data/data/*
That solution seemed to work, but only on certain folders. I now could expand my myapp folder, but could not expand the files directory in it.
At this point, I played around for a while then figured why not just try it on the directory I need rather than trying these wildcard entries.
chmod 777 /data /data/data /data/data/com.example.myapp/*
Followed by:
chmod 777 /data /data/data /data/data/com.example.myapp/files
These commands allowed me to expand and view the files in my app's directory to confirm that the .csv was being saved correctly.
Hope this helps someone. I struggled with this for hours!
(to compound on this a tad further, oddly enough, the permissions did not pass to the .csv file that passed to the files directory. my files directory permissions read drwxrwxrwx and my log.csv file permissions read -rw-rw---- .. just fyi)
The funny thing is that NSNumber converts to string automatically if it becomes a part of a string. I don't think it is documented. Try these:
NSLog(@"My integer NSNumber:%@",[NSNumber numberWithInt:184]);
NSLog(@"My float NSNumber:%@",[NSNumber numberWithFloat:12.23f]);
NSLog(@"My bool(YES) NSNumber:%@",[NSNumber numberWithBool:YES]);
NSLog(@"My bool(NO) NSNumber:%@",[NSNumber numberWithBool:NO]);
NSString *myStringWithNumbers = [NSString stringWithFormat:@"Int:%@, Float:%@ Bool:%@",[NSNumber numberWithInt:132],[NSNumber numberWithFloat:-4.823f],[NSNumber numberWithBool:YES]];
NSLog(@"%@",myStringWithNumbers);
It will print:
My integer NSNumber:184
My float NSNumber:12.23
My bool(YES) NSNumber:1
My bool(NO) NSNumber:0
Int:132, Float:-4.823 Bool:1
Works on both Mac and iOS
This one does not work:
NSString *myNSNumber2 = [NSNumber numberWithFloat:-34512.23f];
If you want to round to the nearest int:
int rounded = (int)Math.Round(precise, 0);
You can also use:
int rounded = Convert.ToInt32(precise);
Which will use Math.Round(x, 0);
to round and cast for you. It looks neater but is slightly less clear IMO.
If you want to round up:
int roundedUp = (int)Math.Ceiling(precise);
This solution worked for me.
Add these lines in your Manifest application tag
android:largeHeap="true"
android:hardwareAccelerated="false"
Example
So, if we had a child element with an id of "child-element" and we wanted to get it's left/top position relative to a parent element, say a div that had a class of "item-parent", we'd use this code.
var position = $("#child-element").offsetRelative("div.item-parent");
alert('left: '+position.left+', top: '+position.top);
Plugin Finally, for the actual plugin (with a few notes expalaining what's going on):
// offsetRelative (or, if you prefer, positionRelative)
(function($){
$.fn.offsetRelative = function(top){
var $this = $(this);
var $parent = $this.offsetParent();
var offset = $this.position();
if(!top) return offset; // Didn't pass a 'top' element
else if($parent.get(0).tagName == "BODY") return offset; // Reached top of document
else if($(top,$parent).length) return offset; // Parent element contains the 'top' element we want the offset to be relative to
else if($parent[0] == $(top)[0]) return offset; // Reached the 'top' element we want the offset to be relative to
else { // Get parent's relative offset
var parent_offset = $parent.offsetRelative(top);
offset.top += parent_offset.top;
offset.left += parent_offset.left;
return offset;
}
};
$.fn.positionRelative = function(top){
return $(this).offsetRelative(top);
};
}(jQuery));
Note : You can Use this on mouseClick or mouseover Event
$(this).offsetRelative("div.item-parent");
This worked for me.
onkeydown="return !(event.keyCode==13)"
<form id="form1" runat="server" onkeydown="return !(event.keyCode==13)">
</form>
Did you try to specify resource only in context.xml
<Resource name="jdbc/PollDatasource" auth="Container" type="javax.sql.DataSource"
driverClassName="org.apache.derby.jdbc.EmbeddedDriver"
url="jdbc:derby://localhost:1527/poll_database;create=true"
username="suhail" password="suhail"
maxActive="20" maxIdle="10" maxWait="-1" />
and remove <resource-ref>
section from web.xml
?
In one project I've seen configuration without <resource-ref>
section in web.xml
and it worked.
It's an educated guess, but I think <resource-ref>
declaration of JNDI
resource named jdbc/PollDatasource
in web.xml
may override declaration of resource with same name in context.xml
and the declaration in web.xml
is missing both driverClassName
and url
hence the NPEs for that properties.
Sometimes, you only need this code.
httpClient.DefaultRequestHeaders.Add("token", token);
Be aware that the new version (5) of font awesome uses "fas"
or "fab"
instead of "fa"
prefix.
Quoted from their website:
The fa prefix has been deprecated in version 5. The new default is the fas solid style and the fab style for brands.
This is why my fonts were showing blank squares. Now fixed.
Example code:
<a class="nav-link" href="//www.facebook.com/xxx" target="_blank"><i class="fab fa-facebook-f"></i></a>
You may have different sets of checkboxes on the same form. Here is a solution that selects/unselects checkboxes by class name, using vanilla javascript function document.getElementsByClassName
The Select All button
<input type='checkbox' id='select_all_invoices' onclick="selectAll()"> Select All
Some of the checkboxes to select
<input type='checkbox' class='check_invoice' id='check_123' name='check_123' value='321' />
<input type='checkbox' class='check_invoice' id='check_456' name='check_456' value='852' />
The javascript
function selectAll() {
var blnChecked = document.getElementById("select_all_invoices").checked;
var check_invoices = document.getElementsByClassName("check_invoice");
var intLength = check_invoices.length;
for(var i = 0; i < intLength; i++) {
var check_invoice = check_invoices[i];
check_invoice.checked = blnChecked;
}
}
Try this:
CREATE PROCEDURE MyProc @excludedlist integer_list_tbltype READONLY AS
SELECT * FROM A WHERE ID NOT IN (@excludedlist)
And then call it like this:
DECLARE @ExcludedList integer_list_tbltype
INSERT @ExcludedList(n) VALUES(3, 4, 22)
exec MyProc @ExcludedList
Because abstract mehods always need implementation by subclass.But if you make any method to static then overriding is not possible for this method
Example
abstract class foo {
abstract static void bar2();
}
class Bar extends foo {
//in this if you override foo class static method then it will give error
}
For me this problem started with upgrading react-native. The upgrade was necessary to add 64-bit support.
Before:
--------
Environment:
Node: 10.15.0
npm: 6.9.0
Watchman: 4.9.0
Xcode: Not Found
Android Studio: 3.4 AI-183.6156.11.34.5692245
Packages: (wanted => installed)
react: 16.0.0-alpha.12 => 16.0.0-alpha.12
react-native: ~0.55.2 => 0.55.4
react-native-cli: 2.0.1
After:
------
info
React Native Environment Info:
Binaries:
Node: 10.15.0
npm: 6.9.0
Watchman: 4.9.0
SDKs:
Android SDK:
API Levels: 23, 26, 27, 28
Build Tools: 27.0.3, 28.0.3
System Images: android-28 | Google APIs Intel x86 Atom
IDEs:
Android Studio: 3.4 AI-183.6156.11.34.5692245
Xcode: /undefined - /usr/bin/xcodebuild
npmPackages:
react: ^16.8.6 => 16.9.0
react-native: 0.59.9 => 0.59.9
npmGlobalPackages:
create-react-native-app: 2.0.2
react-native-cli: 2.0.1
Also, One important change that I made for the upgrade was in ../android/build/build.gradle
android {
...
defaultConfig {
...
targetSdkVersion 28
...
}
...
}
I had to change the targetSdkVersion from 27 to 28 following warning when I tried to upload the build(.apk) to goole play console. Little did i realise that this was the root cause of the above error for me. Immediatly answers by @tom and @tinmarfrutos made absolute sense.
I solved the problem by adding android:usesCleartextTraffic="true" to my android/app/src/debug/AndroidManifest.xml
If you are using annotations, may be you need to use @Mock instead of @InjectMocks. Because @InjectMocks works as @Spy and @Mock together. And @Spy keeps track of recently executed methods and you may feel that incorrect data is returned/subbed.
We can also use -
$('#x').prop('scrollHeight') <!-- Height -->
$('#x').prop('scrollWidth') <!-- Width -->
here is my solution:
$(el).on('touchstart', function(e) {
var link = $(e.target.parentNode).closest('a')
if(link.length > 0) {
window.location.href = link.attr('href');
}
});
Here's a bit more detail to expand on Hooked's answer. When I first read that answer, I missed the instruction to call clf()
instead of creating a new figure. clf()
on its own doesn't help if you then go and create another figure.
Here's a trivial example that causes the warning:
from matplotlib import pyplot as plt, patches
import os
def main():
path = 'figures'
for i in range(21):
_fig, ax = plt.subplots()
x = range(3*i)
y = [n*n for n in x]
ax.add_patch(patches.Rectangle(xy=(i, 1), width=i, height=10))
plt.step(x, y, linewidth=2, where='mid')
figname = 'fig_{}.png'.format(i)
dest = os.path.join(path, figname)
plt.savefig(dest) # write image to file
plt.clf()
print('Done.')
main()
To avoid the warning, I have to pull the call to subplots()
outside the loop. In order to keep seeing the rectangles, I need to switch clf()
to cla()
. That clears the axis without removing the axis itself.
from matplotlib import pyplot as plt, patches
import os
def main():
path = 'figures'
_fig, ax = plt.subplots()
for i in range(21):
x = range(3*i)
y = [n*n for n in x]
ax.add_patch(patches.Rectangle(xy=(i, 1), width=i, height=10))
plt.step(x, y, linewidth=2, where='mid')
figname = 'fig_{}.png'.format(i)
dest = os.path.join(path, figname)
plt.savefig(dest) # write image to file
plt.cla()
print('Done.')
main()
If you're generating plots in batches, you might have to use both cla()
and close()
. I ran into a problem where a batch could have more than 20 plots without complaining, but it would complain after 20 batches. I fixed that by using cla()
after each plot, and close()
after each batch.
from matplotlib import pyplot as plt, patches
import os
def main():
for i in range(21):
print('Batch {}'.format(i))
make_plots('figures')
print('Done.')
def make_plots(path):
fig, ax = plt.subplots()
for i in range(21):
x = range(3 * i)
y = [n * n for n in x]
ax.add_patch(patches.Rectangle(xy=(i, 1), width=i, height=10))
plt.step(x, y, linewidth=2, where='mid')
figname = 'fig_{}.png'.format(i)
dest = os.path.join(path, figname)
plt.savefig(dest) # write image to file
plt.cla()
plt.close(fig)
main()
I measured the performance to see if it was worth reusing the figure within a batch, and this little sample program slowed from 41s to 49s (20% slower) when I just called close()
after every plot.
We can use the core java stuff alone to read the CVS file column by column. Here is the sample code I have wrote for my requirement. I believe that it will help for some one.
BufferedReader br = new BufferedReader(new FileReader(csvFile));
String line = EMPTY;
int lineNumber = 0;
int productURIIndex = -1;
int marketURIIndex = -1;
int ingredientURIIndex = -1;
int companyURIIndex = -1;
// read comma separated file line by line
while ((line = br.readLine()) != null) {
lineNumber++;
// use comma as line separator
String[] splitStr = line.split(COMMA);
int splittedStringLen = splitStr.length;
// get the product title and uri column index by reading csv header
// line
if (lineNumber == 1) {
for (int i = 0; i < splittedStringLen; i++) {
if (splitStr[i].equals(PRODUCTURI_TITLE)) {
productURIIndex = i;
System.out.println("product_uri index:" + productURIIndex);
}
if (splitStr[i].equals(MARKETURI_TITLE)) {
marketURIIndex = i;
System.out.println("marketURIIndex:" + marketURIIndex);
}
if (splitStr[i].equals(COMPANYURI_TITLE)) {
companyURIIndex = i;
System.out.println("companyURIIndex:" + companyURIIndex);
}
if (splitStr[i].equals(INGREDIENTURI_TITLE)) {
ingredientURIIndex = i;
System.out.println("ingredientURIIndex:" + ingredientURIIndex);
}
}
} else {
if (splitStr != null) {
String conditionString = EMPTY;
// avoiding arrayindexoutboundexception when the line
// contains only ,,,,,,,,,,,,,
for (String s : splitStr) {
conditionString = s;
}
if (!conditionString.equals(EMPTY)) {
if (productURIIndex != -1) {
productCVSUriList.add(splitStr[productURIIndex]);
}
if (companyURIIndex != -1) {
companyCVSUriList.add(splitStr[companyURIIndex]);
}
if (marketURIIndex != -1) {
marketCVSUriList.add(splitStr[marketURIIndex]);
}
if (ingredientURIIndex != -1) {
ingredientCVSUriList.add(splitStr[ingredientURIIndex]);
}
}
}
}