i've written a function that extract numbers from string:
int SnirElgabsi::GetNumberFromCString(CString src, CString str, int length) {
// get startIndex
int startIndex = src.Find(str) + CString(str).GetLength();
// cut the string
CString toreturn = src.Mid(startIndex, length);
// convert to number
return _wtoi(toreturn); // atoi(toreturn)
}
Usage:
CString str = _T("digit:1, number:102");
int digit = GetNumberFromCString(str, _T("digit:"), 1);
int number = GetNumberFromCString(str, _T("number:"), 3);
I found this brilliant solution here, it uses the simple logic NAN!=NAN. https://www.codespeedy.com/check-if-a-given-string-is-nan-in-python/
Using above example you can simply do the following. This should work on different type of objects as it simply utilize the fact that NAN is not equal to NAN.
import numpy as np
s = pd.Series(['apple', np.nan, 'banana'])
s.apply(lambda x: x!=x)
out[252]
0 False
1 True
2 False
dtype: bool
2015-03-30: Edited - Missing information has been added
To retrieve the current directory you can use the dynamic %cd%
variable that holds the current active directory
set "curpath=%cd%"
This generates a value with a ending backslash for the root directory, and without a backslash for the rest of directories. You can force and ending backslash for any directory with
for %%a in ("%cd%\") do set "curpath=%%~fa"
Or you can use another dynamic variable: %__CD__%
that will return the current active directory with an ending backslash.
Also, remember the %cd%
variable can have a value directly assigned. In this case, the value returned will not be the current directory, but the assigned value. You can prevent this with a reference to the current directory
for %%a in (".\") do set "curpath=%%~fa"
Up to windows XP, the %__CD__%
variable has the same behaviour. It can be overwritten by the user, but at least from windows 7 (i can't test it on Vista), any change to the %__CD__%
is allowed but when the variable is read, the changed value is ignored and the correct current active directory is retrieved (note: the changed value is still visible using the set
command).
BUT all the previous codes will return the current active directory, not the directory where the batch file is stored.
set "curpath=%~dp0"
It will return the directory where the batch file is stored, with an ending backslash.
BUT this will fail if in the batch file the shift
command has been used
shift
echo %~dp0
As the arguments to the batch file has been shifted, the %0
reference to the current batch file is lost.
To prevent this, you can retrieve the reference to the batch file before any shifting, or change the syntax to shift /1
to ensure the shift operation will start at the first argument, not affecting the reference to the batch file. If you can not use any of this options, you can retrieve the reference to the current batch file in a call to a subroutine
@echo off
setlocal enableextensions
rem Destroy batch file reference
shift
echo batch folder is "%~dp0"
rem Call the subroutine to get the batch folder
call :getBatchFolder batchFolder
echo batch folder is "%batchFolder%"
exit /b
:getBatchFolder returnVar
set "%~1=%~dp0" & exit /b
This approach can also be necessary if when invoked the batch file name is quoted and a full reference is not used (read here).
If You are using source control. vim temp files are quite useless.
So You might want to configure vim not to create them.
Just edit Your ~/.vimrc and add these lines:
set nobackup
set noswapfile
I believe this should be the way this is done...
public void function(String [] array){
....
}
And the calling will be done like...
public void test(){
String[] stringArray = {"a","b","c","d","e","f","g","h","t","k","k","k","l","k"};
function(stringArray);
}
In this case what you can do is : Go in developer options on the device Uncheck "USB Debugging" then check it again A confirmation box should then appear DvxWifiScan
You can give a try to django-import-export. It has nice admin integration, changes preview, can create, update, delete objects.
http://code.google.com/p/monad-tutorial/ is a work in progress to address exactly this question.
Here I came up with universal method to navigate from any place to root.
You create a new Class file with this class, so that it's accessible from anywhere in your project:
import UIKit
class SharedControllers
{
static func navigateToRoot(viewController: UIViewController)
{
var nc = viewController.navigationController
// If this is a normal view with NavigationController, then we just pop to root.
if nc != nil
{
nc?.popToRootViewControllerAnimated(true)
return
}
// Most likely we are in Modal view, so we will need to search for a view with NavigationController.
let vc = viewController.presentingViewController
if nc == nil
{
nc = viewController.presentingViewController?.navigationController
}
if nc == nil
{
nc = viewController.parentViewController?.navigationController
}
if vc is UINavigationController && nc == nil
{
nc = vc as? UINavigationController
}
if nc != nil
{
viewController.dismissViewControllerAnimated(false, completion:
{
nc?.popToRootViewControllerAnimated(true)
})
}
}
}
Usage from anywhere in your project:
{
...
SharedControllers.navigateToRoot(self)
...
}
Try This: It is working for me
ng generate component componentName --module=app.module
It is a 32bit declaration. If you type at the top of an assembly file the statement [bits 32], then you don't need to type DWORD PTR. So for example:
[bits 32]
.
.
and [ebp-4], 0
For anybody interested in Titanium i must say that they don't have a very good documentation some classes, properties, methods are missing. But a lot is "documented" in their sample app the KitchenSink so it is not THAT bad.
The ternary operator ? :
is to return a value, don't use it when you want to use if
for flow control.
if (compareChar(curChar, toChar("0"))) getButtons().get(i).setText("§");
would work good enough.
https://docs.oracle.com/javase/tutorial/java/nutsandbolts/operators.html
There is a better why to determine type of an image. with exif_imagetype
If you use this function, you can tell image's real extension.
with this function filename's extension is completely irrelevant, which is good.
function setHeaderContentType(string $filePath): void
{
$numberToContentTypeMap = [
'1' => 'image/gif',
'2' => 'image/jpeg',
'3' => 'image/png',
'6' => 'image/bmp',
'17' => 'image/ico'
];
$contentType = $numberToContentTypeMap[exif_imagetype($filePath)] ?? null;
if ($contentType === null) {
throw new Exception('Unable to determine content type of file.');
}
header("Content-type: $contentType");
}
You can add more types from the link.
Hope it helps.
Follow the following steps:
JSON.stringify(temp1)
.Make sure you installed the nuget package Microsoft.AspNet.Identity.Owin
. Then add System.Net.Http
namespace.
With Java 8
, allow you doing something more elegant like this:
int[][] foo = new int[][] {
new int[] { 1, 2, 3 },
new int[] { 1, 2, 3, 4},
};
int length = Arrays.stream(array).max(Comparator.comparingInt(ArrayUtils::getLength)).get().length
I ran into the same error that BornToCode first identified in the comments of the original solution. Being unfamiliar with Excel and VBA it took me a second to figure out how to implement tiQU's solution. So I'm posting it as a "For Dummies" solution below
Sub Sample()
Dim Ie As Object
Set Ie = CreateObject("InternetExplorer.Application")
With Ie
.Visible = False
.Navigate "about:blank"
.document.body.InnerHTML = Sheets("Sheet1").Range("I2").Value
'update to the cell that contains HTML you want converted
.ExecWB 17, 0
'Select all contents in browser
.ExecWB 12, 2
'Copy them
ActiveSheet.Paste Destination:=Sheets("Sheet1").Range("J2")
'update to cell you want converted HTML pasted in
.Quit
End With
End Sub
To get the text of the selected option
$("#your_select :selected").text();
To get the value of the selected option
$("#your_select").val();
You can set any pointer to NULL
, though NULL
is simply defined as 0 in C++:
myObject *foo = NULL;
Also note that NULL
is defined if you include standard headers, but is not built into the language itself. If NULL
is undefined, you can use 0 instead, or include this:
#ifndef NULL
#define NULL 0
#endif
As an aside, if you really want to set an object, not a pointer, to NULL
, you can read about the Null Object Pattern.
I'm very sorry for necro-threading but I wanted to provide a solution without converting the integer to a string. Also I wanted to work with more computer-like thinking so that's why the answer from Chris Mueller wasn't good enough for me.
So without further ado,
import math
def count_number(number):
counter = 0
counter_number = number
while counter_number > 0:
counter_number //= 10
counter += 1
return counter
def digit_selector(number, selected_digit, total):
total_counter = total
calculated_select = total_counter - selected_digit
number_selected = int(number / math.pow(10, calculated_select))
while number_selected > 10:
number_selected -= 10
return number_selected
def main():
x = 1548731588
total_digits = count_number(x)
digit_2 = digit_selector(x, 2, total_digits)
return print(digit_2)
if __name__ == '__main__':
main()
which will print:
5
Hopefully someone else might need this specific kind of code. Would love to have feedback on this aswell!
This should find any digit in a integer.
Flaws:
Works pretty ok but if you use this for long numbers then it'll take more and more time. I think that it would be possible to see if there are multiple thousands etc and then substract those from number_selected but that's maybe for another time ;)
Usage:
You need every line from 1-21. Then you can call first count_number to make it count your integer.
x = 1548731588
total_digits = count_number(x)
Then read/use the digit_selector function as follows:
digit_selector('insert your integer here', 'which digit do you want to have? (starting from the most left digit as 1)', 'How many digits are there in total?')
If we have 1234567890, and we need 4 selected, that is the 4th digit counting from left so we type '4'.
We know how many digits there are due to using total_digits. So that's pretty easy.
Hope that explains everything!
Han
PS: Special thanks for CodeVsColor for providing the count_number function. I used this link: https://www.codevscolor.com/count-number-digits-number-python to help me make the digit_selector work.
Very common use in jQuery is to distinguish jQuery objects stored in variables from other variables.
For example, I would define:
var $email = $("#email"); // refers to the jQuery object representation of the dom object
var email_field = $("#email").get(0); // refers to the dom object itself
I find this to be very helpful in writing jQuery code and makes it easy to see jQuery objects which have a different set of properties.
Hide php warnings in file
error_reporting(0);
i also got the same problem by copying the controller code from another controller, then i solve the problem by removing the space before php tag
<?php
git pull --rebase --autostash
-r, --rebase[=false|true|merges|preserve|interactive] When true, rebase the current branch on top of the upstream branch after fetching. If there is a remote-tracking branch corresponding to the upstream
--autostash, --no-autostash Before starting rebase, stash local modifications away if needed, and apply the stash entry when done
I do not know why this is not answered yet, but solution, as you can see is simple. All answers here suggest same: to delete/save your local changes and apply upstream, then (if you save
) apply your local changes on top.
What git pull --rebase --autostash
does step-by-step:
1. your local changes saved by `--autostash`
2. your local commits saved by `--rebase`
3. commits from upstream applied to your branch
4. your local commits are restored on top of upstream
5. your local changes are restored to working directory
My case (probably yours too):
I have local changes (changes at working directory):
When I try to pull remote changes I get error:
This changes do not intersect with local changes:
So when I pull --rebase --autostash
local changes saved and applied without any problem automatically
Let's fit the model:
> library(ISwR)
> fit <- lm(metabolic.rate ~ body.weight, rmr)
> summary(fit)
Call:
lm(formula = metabolic.rate ~ body.weight, data = rmr)
Residuals:
Min 1Q Median 3Q Max
-245.74 -113.99 -32.05 104.96 484.81
Coefficients:
Estimate Std. Error t value Pr(>|t|)
(Intercept) 811.2267 76.9755 10.539 2.29e-13 ***
body.weight 7.0595 0.9776 7.221 7.03e-09 ***
---
Signif. codes: 0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1
Residual standard error: 157.9 on 42 degrees of freedom
Multiple R-squared: 0.5539, Adjusted R-squared: 0.5433
F-statistic: 52.15 on 1 and 42 DF, p-value: 7.025e-09
The 95% confidence interval for the slope is the estimated coefficient (7.0595) ± two standard errors (0.9776).
This can be computed using confint
:
> confint(fit, 'body.weight', level=0.95)
2.5 % 97.5 %
body.weight 5.086656 9.0324
$ which pip
or
$ pip -V
execute this command into your terminal. It should display the location of executable file eg. /usr/local/bin/pip and the second command will display the version if the pip is installed correctly.
Try this one, if null set 0 or something
return command.ExecuteScalar() == DBNull.Value ? 0 : (double)command.ExecuteScalar();
You can use:
File.WriteAllBytes("Foo.txt", arrBytes); // Requires System.IO
If you have an enumerable and not an array, you can use:
File.WriteAllBytes("Foo.txt", arrBytes.ToArray()); // Requires System.Linq
You can do by maintaining the state as below:
$('#user_button').on('click',function(){
if($(this).attr('data-click-state') == 1) {
$(this).attr('data-click-state', 0);
$(this).css('background-color', 'red')
}
else {
$(this).attr('data-click-state', 1);
$(this).css('background-color', 'orange')
}
});
The solution I prefer is to mix arrays and ostream like this:
std::ostream& operator<<(std::ostream& lhs, WeekEnum e) {
static const std::array<std::string, 7> WEEK_STRINGS = {"Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday" };
return os << WEEK_STRINGS[statuc_cast<WeekEnum>(e)]
}
cout << "Today is " << WeekEnum::Monday;
I also suggest to use enum class instead of Enum
For Mysql:
SELECT t.user,
(SELECT GROUP_CONCAT( t1.department ) FROM table_name t1 WHERE t1.user = t.user)department
FROM table_name t
GROUP BY t.user
LIMIT 0 , 30
According to vnportnoy the syntax
GenSet<Integer> intSet[] = new GenSet[3];
creates an array of null references, to be filled as
for (int i = 0; i < 3; i++)
{
intSet[i] = new GenSet<Integer>();
}
which is type safe.
var element = document.getElementById(element_id);
element.className += " " + newClassName;
Voilà. This will work on pretty much every browser ever. The leading space is important, because the className
property treats the css classes like a single string, which ought to match the class
attribute on HTML elements (where multiple classes must be separated by spaces).
Incidentally, you're going to be better off using a Javascript library like prototype or jQuery, which have methods to do this, as well as functions that can first check if an element already has a class assigned.
In prototype, for instance:
// Prototype automatically checks that the element doesn't already have the class
$(element_id).addClassName(newClassName);
See how much nicer that is?!
They are parts of the Observer design pattern. Usually one or more obervers get informed about changes in one observable. It's a notifcation that "something" happened, where you as a programmer can define what "something" means.
When using this pattern, you decouple the both entities from each another - the observers become pluggable.
If you are only looking to point to a different location for you identity file, the you can modify your ~/.ssh/config file with the following entry:
IdentityFile ~/.foo/identity
man ssh_config
to find other config options.
You can turn the axes off by following the advice in Veedrac's comment (linking to here) with one small modification.
Rather than using plt.axis('off')
you should use ax.axis('off')
where ax
is a matplotlib.axes
object. To do this for your code you simple need to add axarr[0,0].axis('off')
and so on for each of your subplots.
The code below shows the result (I've removed the prune_matrix
part because I don't have access to that function, in the future please submit fully working code.)
import matplotlib.pyplot as plt
import matplotlib.image as mpimg
import matplotlib.cm as cm
img = mpimg.imread("stewie.jpg")
f, axarr = plt.subplots(2, 2)
axarr[0,0].imshow(img, cmap = cm.Greys_r)
axarr[0,0].set_title("Rank = 512")
axarr[0,0].axis('off')
axarr[0,1].imshow(img, cmap = cm.Greys_r)
axarr[0,1].set_title("Rank = %s" % 128)
axarr[0,1].axis('off')
axarr[1,0].imshow(img, cmap = cm.Greys_r)
axarr[1,0].set_title("Rank = %s" % 32)
axarr[1,0].axis('off')
axarr[1,1].imshow(img, cmap = cm.Greys_r)
axarr[1,1].set_title("Rank = %s" % 16)
axarr[1,1].axis('off')
plt.show()
Note: To turn off only the x or y axis you can use set_visible()
e.g.:
axarr[0,0].xaxis.set_visible(False) # Hide only x axis
There is no performance difference between importing the package or using the fully qualified class name. The import directive is not converted to Java byte code, consequently there is no effect on runtime performance. The only difference is that it saves you time in case you are using the imported class multiple times. This is a good read here
As others have pointed out modulus is based on remainder system.
I think an easier way to think about modulus is what remains after a dividend (number to be divided) has been fully divided by a divisor. So if we think about 5%7, when you divide 5 by 7, 7 can go into 5 only 0 times and when you subtract 0 (7*0) from 5 (just like we learnt back in elementary school), then the remainder would be 5 ( the mod). See the illustration below.
0
______
7) 5
__-0____
5
With the same logic, -5 mod 7 will be -5 ( only 0 7s can go in -5 and -5-0*7 = -5). With the same token -5 mod -7 will also be -5. A few more interesting cases:
5 mod (-3) = 2 i.e. 5 - (-3*-1)
(-5) mod (-3) = -2 i.e. -5 - (-3*1) = -5+3
Whenever you want to use ant thread safe version of ant collection object,take help of java.util.concurrent.* package. It has almost all concurrent version of unsynchronized collection objects. eg: for ArrayList, you have java.util.concurrent.CopyOnWriteArrayList
You can do Collections.synchronizedCollection(any collection object),but remember this classical synchr. technique is expensive and comes with performence overhead. java.util.concurrent.* package is less expensive and manage the performance in better way by using mechanisms like
copy-on-write,compare-and-swap,Lock,snapshot iterators,etc.
So,Prefer something from java.util.concurrent.* package
Its all about layout you want to draw. You can create custom class inheriting from UICollectionViewFlowLayout. Currently there is not any direct method to set columns. If you want to achieve this kind of functionality you need to do it manually. You need to handle it in your custom flow layout class.
Now question will arise how you will do it? If you dont want to disturb cell frame you can adjust
collectionView:layout:minimumInteritemSpacingForSectionAtIndex:
collectionView:layout:minimumLineSpacingForSectionAtIndex:
Another way is provide you own positions of cells. By overriding below two methods, which will get called during your layout formation.
- (NSArray*)layoutAttributesForElementsInRect:(CGRect)rect
- (UICollectionViewLayoutAttributes *)layoutAttributesForItemAtIndexPath:(NSIndexPath *)path
UICollectionViewLayoutAttributes is class which will deal with cell position, frame, Zindex etc
private OutputStream outputStream;
private InputStream inStream;
private void init() throws IOException {
BluetoothAdapter blueAdapter = BluetoothAdapter.getDefaultAdapter();
if (blueAdapter != null) {
if (blueAdapter.isEnabled()) {
Set<BluetoothDevice> bondedDevices = blueAdapter.getBondedDevices();
if(bondedDevices.size() > 0) {
Object[] devices = (Object []) bondedDevices.toArray();
BluetoothDevice device = (BluetoothDevice) devices[position];
ParcelUuid[] uuids = device.getUuids();
BluetoothSocket socket = device.createRfcommSocketToServiceRecord(uuids[0].getUuid());
socket.connect();
outputStream = socket.getOutputStream();
inStream = socket.getInputStream();
}
Log.e("error", "No appropriate paired devices.");
} else {
Log.e("error", "Bluetooth is disabled.");
}
}
}
public void write(String s) throws IOException {
outputStream.write(s.getBytes());
}
public void run() {
final int BUFFER_SIZE = 1024;
byte[] buffer = new byte[BUFFER_SIZE];
int bytes = 0;
int b = BUFFER_SIZE;
while (true) {
try {
bytes = inStream.read(buffer, bytes, BUFFER_SIZE - bytes);
} catch (IOException e) {
e.printStackTrace();
}
}
}
um why not just set an image to the bottom layer and forgo all the annoyances
<img src='yourmom.png' style='position:fixed;top:0px;left:0px;width:100%;height:100%;z-index:-1;'>
None of these solutions has helped me in my Electron App.
My solution (workaround):
npm install jquery
In your index.js
file:
var jQuery = $ = require('jquery');
In your .js
files write yours jQuery functions in this way:
jQuery(document).ready(function() {
I was executing a get request an also want to see just the response and nothing else, seems like magic is done with -silent,-s option.
From the curl man page:
-s, --silent Silent or quiet mode. Don't show progress meter or error messages. Makes Curl mute. It will still output the data you ask for, potentially even to the terminal/stdout unless you redirect it.
Below the examples:
curl -s "http://host:8080/some/resource"
curl -silent "http://host:8080/some/resource"
Using custom headers
curl -s -H "Accept: application/json" "http://host:8080/some/resource")
Using POST method with a header
curl -s -X POST -H "Content-Type: application/json" "http://host:8080/some/resource") -d '{ "myBean": {"property": "value"}}'
You can also customize the output for specific values with -w, below the options I use to get just response codes of the curl:
curl -s -o /dev/null -w "%{http_code}" "http://host:8080/some/resource"
For checking the version of scikit-learn in shell script, if you have pip installed, you can try this command
pip freeze | grep scikit-learn
scikit-learn==0.17.1
Hope it helps!
I've also had this problem from a service reference that was out of date, even with the server & client on the same machine. Running 'Update Service Reference' will generally fix it if this is the issue.
I got this resolved in angular with (click) = "someFuncionName()"
in the .html file for the specific component.
The StringBuilder.Append()
method is much better than using the +
operator. But I've found that, when executing 1000 concatenations or less, String.Join()
is even more efficient than StringBuilder
.
StringBuilder sb = new StringBuilder();
sb.Append(someString);
The only problem with String.Join
is that you have to concatenate the strings with a common delimiter.
Edit: as @ryanversaw pointed out, you can make the delimiter string.Empty
.
string key = String.Join("_", new String[]
{ "Customers_Contacts", customerID, database, SessionID });
var a = 10;
myFunction();
function myFunction(){
a = 20;
}
alert("Value of 'a' outside the function " + a); //outputs 20
Note: I post this answer if someone in the future face the same problem as me. For me the following line wasn't enought:
android:configChanges="orientation"
When I rotated the screen, the method `onConfigurationChanged(Configuration newConfig) did't get called.
Solution: I also had to add "screenSize" even if the problem had to do with the orientation. So in the AndroidManifest.xml - file, add this:
android:configChanges="keyboardHidden|orientation|screenSize"
Then implement the method onConfigurationChanged(Configuration newConfig)
This "bug" is actually the new normal behavior of Apache 2.4. In my case, I had a very specific rule to deny access to any folder or file with name starting with ".", so I had to set an exception for a particular public folder that requires such odd name.
For the record my particular Rewrite rule is:
RewriteRule "(?!\.trusted)(^|/)\." - [F]
This rule [F]obits everything starting with "." but .trusted
, thanks to the magic of regex "?!" negation.
When I had to solve this problem, I created a hard-coded data dictionary to map between numbers and their associated words. For example, the following might represent a few entries in the dictionary:
{1, "one"}
{2, "two"}
{30, "thirty"}
You really only need to worry about mapping numbers in the 10^0 (1,2,3, etc.) and 10^1 (10,20,30) positions because once you get to 100, you simply have to know when to use words like hundred, thousand, million, etc. in combination with your map. For example, when you have a number like 3,240,123, you get: three million two hundred forty thousand one hundred twenty three.
After you build your map, you need to work through each digit in your number and figure out the appropriate nomenclature to go with it.
If you don't want to duplicate code, and like me you just want to show stats, in your view model, you could just pass in the models you want to get data from like so:
public class GameViewModel
{
public virtual Ship Ship { get; set; }
public virtual GamePlayer GamePlayer { get; set; }
}
Then, in your controller just run your queries on the respective models, pass them to the view model and return it, example:
GameViewModel PlayerStats = new GameViewModel();
GamePlayer currentPlayer = (from c in db.GamePlayer [more queries]).FirstOrDefault();
[code to check if results]
//pass current player into custom view model
PlayerStats.GamePlayer = currentPlayer;
Like I said, you should only really do this if you want to display stats from the relevant tables, and there's no other part of the CRUD process happening, for security reasons other people have mentioned above.
This doesn't work on android native browser to click "hidden input (file) element":
$('a#swaswararedirectlink')[0].click();
But this works:
$("#input-file").show();
$("#input-file")[0].click();
$("#input-file").hide();
<style type="text/css">
p.boldpara {font-weight:bold;}
</style>
</head>
<body>
<p class="boldpara">Stack overflow is good site for developers. I really like this site </p>
</body>
</html>
jQuery $.extend(obj1, obj2)
would merge 2 objects for you, but you should really be using an array.
var alertsObj = {
1: {app:'helloworld','message'},
2: {app:'helloagain',message:'another message'}
};
var alertArr = [
{app:'helloworld','message'},
{app:'helloagain',message:'another message'}
];
var newAlert = {app:'new',message:'message'};
$.extend(alertsObj, newAlert);
alertArr.push(newAlert);
From version 1.9 Easier and official way of getting json
from django.http import JsonResponse
from django.forms.models import model_to_dict
return JsonResponse( model_to_dict(modelinstance) )
You can install the .whl file, using pip install filename
. Though to use it in this form, it should be in the same directory as your command line, otherwise specify the complete filename, along with its address like pip install C:\Some\PAth\filename
.
Also make sure the .whl file is of the same platform as you are using, do a python -V
to find out which version of Python you are running and if it is win32 or 64, install the correct version according to it.
Try setting startDate
to the current date. For example:
$('.date-pick').datePicker({startDate:'01/01/1996'});
I was wondering why nobody suggested the extremely handy Type comparison table. It answers every question about the common functions and compare operators.
A snippet:
Expression | empty($x)
----------------+--------
$x = ""; | true
$x = null | true
var $x; | true
$x is undefined | true
$x = array(); | true
$x = false; | true
$x = true; | false
$x = 1; | false
$x = 42; | false
$x = 0; | true
$x = -1; | false
$x = "1"; | false
$x = "0"; | true
$x = "-1"; | false
$x = "php"; | false
$x = "true"; | false
$x = "false"; | false
Along other cheatsheets, I always keep a hardcopy of this table on my desk in case I'm not sure
I think it's r+
, not rw
. I'm just a starter, and that's what I've seen in the documentation.
just use echo'd javascript to rid the URL of any variables with a self-submitting, blank form:
<?
if (isset($_GET['your_var'])){
//blah blah blah code
echo "<script type='text/javascript'>unsetter();</script>";
?>
Then make this javascript function:
function unsetter() {
$('<form id = "unset" name = "unset" METHOD="GET"><input type="submit"></form>').appendTo('body');
$( "#unset" ).submit();
}
I resolved the issue via this command
pg_ctl -D /usr/local/var/postgres start
At times, you might get this error
pg_ctl: another server might be running; trying to start server anyway
So, try running the following command and then run the first command given above.
pg_ctl -D /usr/local/var/postgres stop
As stated by @Dugini, some config entries have been removed. Maximal:
webdriver.DesiredCapabilities.FIREFOX['proxy'] = {
"httpProxy":PROXY,
"ftpProxy":PROXY,
"sslProxy":PROXY,
"noProxy":[],
"proxyType":"MANUAL"
}
Do you mean something like this? JSFiddle
Attribute used:
margin-left: 50px;
Please forgive me for adding yet another version to this already long list. I looked at every answer and decided that I really wanted a version with just one parameter in the signature. I also added some argument checking to benefit from early failure with sensible info in case of unexpected input.
@SuppressWarnings("unchecked")
public static <T> T[] concat(T[]... inputArrays) {
if(inputArrays.length < 2) {
throw new IllegalArgumentException("inputArrays must contain at least 2 arrays");
}
for(int i = 0; i < inputArrays.length; i++) {
if(inputArrays[i] == null) {
throw new IllegalArgumentException("inputArrays[" + i + "] is null");
}
}
int totalLength = 0;
for(T[] array : inputArrays) {
totalLength += array.length;
}
T[] result = (T[]) Array.newInstance(inputArrays[0].getClass().getComponentType(), totalLength);
int offset = 0;
for(T[] array : inputArrays) {
System.arraycopy(array, 0, result, offset, array.length);
offset += array.length;
}
return result;
}
For plain Javascript, try the following:
window.onload = function() {
document.getElementById("TextBoxName").focus();
};
GraphQL query format was designed in order to allow:
However, according to GraphQL documentation, you may create fragments in order to make selection sets more reusable:
# Only most used selection properties
fragment UserDetails on User {
id,
username
}
Then you could query all user details by:
FetchUsers {
users() {
...UserDetails
}
}
You can also add additional fields alongside your fragment:
FetchUserById($id: ID!) {
users(id: $id) {
...UserDetails
count
}
}
$('#hello').hide('slide', {direction: 'left'}, 1000);
requires the jQuery-ui library. See http://www.jqueryui.com
Margin is the spacing outside your element, just as padding is the spacing inside your element.
Setting the bottom margin indicates what distance you want below the current block. Setting a negative top margin indicates that you want negative spacing above your block. Negative spacing may in itself be a confusing concept, but just the way positive top margin pushes content down, a negative top margin pulls content up.
Finally after comparing all solution, I think starting from build.gradle
file can be convenient.
Gradle distribution has samples
folder with a lot of examples, and there is gradle init --type basic
comand see Chapter 47. Build Init Plugin. But they all needs some editing.
You can use template below as well, then run gradle initSourceFolders eclipse
/*
* Nodeclipse/Enide build.gradle template for basic Java project
* https://github.com/Nodeclipse/nodeclipse-1/blob/master/org.nodeclipse.enide.editors.gradle/docs/java/basic/build.gradle
* Initially asked on
* http://stackoverflow.com/questions/14017364/how-to-create-java-gradle-project
* Usage
* 1. create folder (or general Eclipse project) and put this file inside
* 2. run `gradle initSourceFolders eclipse` or `gradle initSourceFolders idea`
* @author Paul Verest;
* based on `gradle init --type basic`, that does not create source folders
*/
apply plugin: 'java'
apply plugin: 'eclipse'
apply plugin: 'idea'
task initSourceFolders { // add << before { to prevent executing during configuration phase
sourceSets*.java.srcDirs*.each { it.mkdirs() }
sourceSets*.resources.srcDirs*.each { it.mkdirs() }
}
task wrapper(type: Wrapper) {
gradleVersion = '1.11'
}
// In this section you declare where to find the dependencies of your project
repositories {
// Use Maven Central for resolving your dependencies.
// You can declare any Maven/Ivy/file repository here.
mavenCentral()
}
// In this section you declare the dependencies for your production and test code
dependencies {
//compile fileTree(dir: 'libs', include: '*.jar')
// The production code uses the SLF4J logging API at compile time
//compile 'org.slf4j:slf4j-api:1.7.5'
// Declare the dependency for your favourite test framework you want to use in your tests.
// TestNG is also supported by the Gradle Test task. Just change the
// testCompile dependency to testCompile 'org.testng:testng:6.8.1' and add
// 'test.useTestNG()' to your build script.
testCompile "junit:junit:4.11"
}
The result is like below.
That can be used without any Gradle plugin for Eclipse,
or with (Enide) Gradle for Eclipse, Jetty, Android alternative to Gradle Integration for Eclipse
I was using DataGrip (By Intellij Idea). and it was very easy copying data from one table (in a different database to another).
First, make sure you are connected with both DataSources in Data Grip.
Select Source Table and press F5 or (Right-click -> Select Copy Table to.)
This will show you a list of all tables (you can also search using a table name in the popup window). Just select your target and press OK.
DataGrip will handle everything else for you.
Check in the folder structure of the project the files within the /gradle/wrapper/ The gradle-wrapper.jar version should be the one specified in the gradle-wrapper.properties
graphics.h
appears to something once bundled with Borland and/or Turbo C++, in the 90's.
http://www.daniweb.com/software-development/cpp/threads/17709/88149#post88149
It's unlikely that you will find any support for that file with modern compiler. For other graphics libraries check the list of "related" questions (questions related to this one). E.g., "A Simple, 2d cross-platform graphics library for c or c++?".
instead of declaring as int i
declare it as Integer i
then we can do i=null;
Integer i;
i=null;
Use this to have multiple lines of text in UILabel
:
textLabel.lineBreakMode = NSLineBreakByWordWrapping;
textLabel.numberOfLines = 0;
Swift:
textLabel.lineBreakMode = .byWordWrapping
textLabel.numberOfLines = 0
Firefox Screenshots is a new tool that ships with Firefox. It is not a developer tool, it is aimed at end-users of the browser.
To take a screenshot, click on the page actions menu in the address bar, and click "take a screenshot". If you then click "Save full page", it will save the full page, scrolling for you.
(source: mozilla.net)
I'd go with the multiple resource files. It shouldn't be that hard to configure. In fact I recently answered a similar question on setting a global language based resource files in conjunction with form language resource files.
Localization in Visual Studio 2008
I would consider that the best approach at least for WinForm development.
The Java 7 Files utility type is useful for working with files:
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.io.IOException;
import java.util.*;
public class WriteReadUtf8 {
public static void main(String[] args) throws IOException {
List<String> lines = Arrays.asList("These", "are", "lines");
Path textFile = Paths.get("foo.txt");
Files.write(textFile, lines, StandardCharsets.UTF_8);
List<String> read = Files.readAllLines(textFile, StandardCharsets.UTF_8);
System.out.println(lines.equals(read));
}
}
The Java 8 version allows you to omit the Charset argument - the methods default to UTF-8.
In case you want to cast to a class and not just a string:
YourClass model = await request.Content.ReadAsAsync<YourClass>();
It can be as simple as:
default_data['item3'] = 3
As Chris' answer says, you can use update to add more than one item. An example:
default_data.update({'item4': 4, 'item5': 5})
Please see the documentation about dictionaries as data structures and dictionaries as built-in types.
@echo off
title Professional Hacker
color 02
:matrix
echo %random%%random%%random%%random%%random%%random%%random%%random%%random%%random%%random%%random%%random%%random%%random%%
echo %random%%random%%random%%random%%random%%random%%random%%random%%random%%random%%random%%random%%random%%random%%random%%
echo %random%%random%%random%%random%%random%%random%%random%%random%%random%%random%%random%%random%%random%%random%%random%%
echo %random%%random%%random%%random%%random%%random%%random%%random%%random%%random%%random%%random%%random%%random%%random%%
echo %random%%random%%random%%random%%random%%random%%random%%random%%random%%random%%random%%random%%random%%random%%random%%
echo %random%%random%%random%%random%%random%%random%%random%%random%%random%%random%%random%%random%%random%%random%%random%%
echo %random%%random%%random%%random%%random%%random%%random%%random%%random%%random%%random%%random%%random%%random%%random%%
echo %random%%random%%random%%random%%random%%random%%random%%random%%random%%random%%random%%random%%random%%random%%random%%
goto matrix
To solve the issue, you are using the z-index on the footer and header, but you forgot about the position, if a z-index is to be used, the element must have a position:
Add to your footer and header this CSS:
position: relative;
EDITED:
Also noticed that the background image on the #backstretch has a negative z-index, don't use that, some browsers get really weird...
Remove From the #backstretch:
z-index: -999999;
Read a little bit about Z-Index here!
If you have some image files, just upload them to a public folder on your Google Drive, copy its folder ID from the address bar (e.g. 0B0Gi4v5omoZUVXhCT2kta1l0ZG8) and paste it into a form at GDrives, then choose your own alias (e.g. myimgs) and voila! You can access the images one by one using e.g. http://gdriv.es/myimgs/myimage.jpg.
If you want to embed a whole folder on your website (in a frame), you can use one of the following URLs, replacing [folderID] with your own ID:
If you prefer to get the file list in XML or JSON, you can use YQL.
Note: You can use Google+ Photos to host ans embed your images as well.
If you want to remove EVERYTHING :
textarea {
border: none;
background-color: transparent;
resize: none;
outline: none;
}
Sounds like you don't want to resolve dns yourself (this might be the wrong nomenclature) dnspython appears to be a standalone dns client that will understandably ignore your operating system because its bypassing the operating system's utillities.
We can look at a shell utility named getent
to understand how the (debian 11 alike) operating system resolves dns for programs, this is likely the standard for all *nix like systems that use a socket implementation.
see man getent
's "hosts" section, which mentions the use of getaddrinfo
, which we can see as man getaddrinfo
and to use it in python, we have to extract some info from the data structures
.
import socket
def get_ipv4_by_hostname(hostname):
# see `man getent` `/ hosts `
# see `man getaddrinfo`
return list(
i # raw socket structure
[4] # internet protocol info
[0] # address
for i in
socket.getaddrinfo(
hostname,
0 # port, required
)
if i[0] is socket.AddressFamily.AF_INET # ipv4
# ignore duplicate addresses with other socket types
and i[1] is socket.SocketKind.SOCK_RAW
)
print(get_ipv4_by_hostname('localhost'))
print(get_ipv4_by_hostname('google.com'))
Try this
select to_char(SYSDATE,'Month') from dual;
for full name and try this
select to_char(SYSDATE,'Mon') from dual;
for abbreviation
you can find more option here:
You can use PowerShell to get the information you want.
(Get-Item C:\Path\To\MyFile.dll).VersionInfo
By default this will display ProductVersion and FileVersion But the full VERSIONINFO is available. I.e. to return Comments
(Get-Item C:\Path\To\MyFile.dll).VersionInfo.Comments
This worked for me,
image: {
width: 200,
height:220,
resizeMode: 'cover'
}
You can also set your resizeMode: 'contain'
. I defined the style for my network images as:
<Image
source={{uri:rowData.banner_path}}
style={{
width: 80,
height: 80,
marginRight: 10,
marginBottom: 12,
marginTop: 12}}
/>
If you are using flex, use it in all the components of parent View, else it is redundant with height: 200, width: 220
.
Try this :
SELECT CONVERT(varchar(2), GETDATE(), 101)
I use this css positioning for most of my vertical elements:
<div class="vertical-line" style="height: 250px;
width: 1px;
background-color: #81F781;
margin-left: 0px;
margin-top: -100px;
postion: absolute;
border-radius: 2px;">
</div>
Change the height and width to fit the page, or to make a horizontal line swap the height to width:
<div class="vertical-line" style="height: 250px;
width: 1px;
<div class="vertical-line" style="width: 250px;
height: 1px;
instead of a standard html line.
Sven Marnach's answer is pretty much it, but has one generality issue... It will fail if the list being printed doesn't just contain strings.
So, the more general answer to "How to print out a list with elements separated by newlines"...
print '\n'.join([ str(myelement) for myelement in mylist ])
Then again, the print function approach JBernardo points out is superior. If you can, using the print function instead of the print statement is almost always a good idea.
The shortest solution I know:
using(var memoryStream = new MemoryStream())
{
sourceStream.CopyTo(memoryStream);
return memoryStream.ToArray();
}
* {_x000D_
padding: 0;_x000D_
margin: 0;_x000D_
}_x000D_
html, body {_x000D_
height: 100%;_x000D_
}_x000D_
ul {_x000D_
height: 100%;_x000D_
}_x000D_
li {_x000D_
display: flex;_x000D_
justify-content: center;_x000D_
align-items:center;_x000D_
background: silver;_x000D_
width: 100%;_x000D_
height: 20%;_x000D_
}
_x000D_
<ul>_x000D_
<li>This is the text</li>_x000D_
</ul>
_x000D_
You can actually use CHAR
(length of hash) to define your datatype for MySQL because each hashing algorithm will always evaluate out to the same number of characters. For example, SHA1
always returns a 40-character hexadecimal number.
git config --global http.postBuffer 524288000
git config --global http.maxRequestBuffer 524288000
git config --global core.compression 0
As it's an issue we face more than often, below are the steps to resolve it.
Open the Git perspective. In the Git Repository view, go to on Branches ? Local ? master and right click ? Merge...
It should auto select Remote Tracking ? *origin/master. Press Merge.
Launch stage view in Eclipse.
Double click the files which initially showed conflict
In the conflict merge view, by selecting the left arrow for all the non-conflict + conflict changes from left to right, you can resolve all the conflicts.
Save the merged file.
Do a Team ? pull from Eclipse again.
You are all set :)
theutz' answer here is very good, I just want to add this:
If you let your mapping profile inherit from MapperConfigurationExpression
instead of Profile
, you can very simply add a test to verify your mapping setup, which is always handy:
[Fact]
public void MappingProfile_VerifyMappings()
{
var mappingProfile = new MappingProfile();
var config = new MapperConfiguration(mappingProfile);
var mapper = new Mapper(config);
(mapper as IMapper).ConfigurationProvider.AssertConfigurationIsValid();
}
Under the conditions stipulated in the question:
git init
,git add
operations,git commit
,If those preconditions are met, then the simplest way to undo the initial commit would be:
rm -fr .git
from the directory where you did git init
. You can then redo the git init
to recreate the Git repository, and redo the additions with whatever changes are sensible that you regretted not making the first time, and redo the initial commit.
DANGER! This removes the Git repository directory.
It removes the Git repository directory permanently and irrecoverably, unless you've got backups somewhere. Under the preconditions, you've nothing you want to keep in the repository, so you're not losing anything. All the files you added are still available in the working directories, assuming you have not modified them yet and have not deleted them, etc. However, doing this is safe only if you have nothing else in your repository at all. Under the circumstances described in the question 'commit repository first time — then regret it', it is safe. Very often, though, it is not safe.
It's also safe to do this to remove an unwanted cloned repository; it does no damage to the repository that it was cloned from. It throws away anything you've done in your copy, but doesn't affect the original repository otherwise.
Be careful, but it is safe and effective when the preconditions are met.
If you've done other things with your repository that you want preserved, then this is not the appropriate technique — your repository no longer meets the preconditions for this to be appropriate.
<?php
$args = array( 'post_type' => 'product', 'category' => 34, 'posts_per_page' => -1 );
$products = get_posts( $args );
?>
This should grab all the products you want, I may have the post type wrong though I can't quite remember what woo-commerce uses for the post type. It will return an array of products
CDATA
has no meaning at all in HTML.
CDATA
is an XML construct which sets a tag's contents that is normally #PCDATA - parsed character data, to be instead taken as #CDATA, that is, non-parsed character data. It is only relevant and valid in XHTML.
It is used in script
tags to avoid parsing <
and &
. In HTML, this is not needed, because in HTML, script
is already #CDATA.
Try this:
grep -i -A 10 "my_regex"
-A 10 means, print ten lines after match to "my_regex"
This is, in essence, what AJAX is for. Your page loads, and you add an event to an element. When the user causes the event to be triggered, say by clicking something, your Javascript uses the XMLHttpRequest object to send a request to a server.
After the server responds (presumably with output), another Javascript function/event gives you a place to work with that output, including simply sticking it into the page like any other piece of HTML.
You can do it "by hand" with plain Javascript , or you can use jQuery. Depending on the size of your project and particular situation, it may be more simple to just use plain Javascript .
In this very basic example, we send a request to myAjax.php
when the user clicks a link. The server will generate some content, in this case "hello world!". We will put into the HTML element with the id output
.
The javascript
// handles the click event for link 1, sends the query
function getOutput() {
getRequest(
'myAjax.php', // URL for the PHP file
drawOutput, // handle successful request
drawError // handle error
);
return false;
}
// handles drawing an error message
function drawError() {
var container = document.getElementById('output');
container.innerHTML = 'Bummer: there was an error!';
}
// handles the response, adds the html
function drawOutput(responseText) {
var container = document.getElementById('output');
container.innerHTML = responseText;
}
// helper function for cross-browser request object
function getRequest(url, success, error) {
var req = false;
try{
// most browsers
req = new XMLHttpRequest();
} catch (e){
// IE
try{
req = new ActiveXObject("Msxml2.XMLHTTP");
} catch(e) {
// try an older version
try{
req = new ActiveXObject("Microsoft.XMLHTTP");
} catch(e) {
return false;
}
}
}
if (!req) return false;
if (typeof success != 'function') success = function () {};
if (typeof error!= 'function') error = function () {};
req.onreadystatechange = function(){
if(req.readyState == 4) {
return req.status === 200 ?
success(req.responseText) : error(req.status);
}
}
req.open("GET", url, true);
req.send(null);
return req;
}
The HTML
<a href="#" onclick="return getOutput();"> test </a>
<div id="output">waiting for action</div>
The PHP
// file myAjax.php
<?php
echo 'hello world!';
?>
Try it out: http://jsfiddle.net/GRMule/m8CTk/
Arguably, that is a lot of Javascript code. You can shorten that up by tightening the blocks or using more terse logic operators, of course, but there's still a lot going on there. If you plan on doing a lot of this type of thing on your project, you might be better off with a javascript library.
Using the same HTML and PHP from above, this is your entire script (with jQuery included on the page). I've tightened up the code a little to be more consistent with jQuery's general style, but you get the idea:
// handles the click event, sends the query
function getOutput() {
$.ajax({
url:'myAjax.php',
complete: function (response) {
$('#output').html(response.responseText);
},
error: function () {
$('#output').html('Bummer: there was an error!');
}
});
return false;
}
Try it out: http://jsfiddle.net/GRMule/WQXXT/
Don't rush out for jQuery just yet: adding any library is still adding hundreds or thousands of lines of code to your project just as surely as if you had written them. Inside the jQuery library file, you'll find similar code to that in the first example, plus a whole lot more. That may be a good thing, it may not. Plan, and consider your project's current size and future possibility for expansion and the target environment or platform.
If this is all you need to do, write the plain javascript once and you're done.
Documentation
XMLHttpRequest
on MDN - https://developer.mozilla.org/en/XMLHttpRequestXMLHttpRequest
on MSDN - http://msdn.microsoft.com/en-us/library/ie/ms535874%28v=vs.85%29.aspxjQuery.ajax
- http://api.jquery.com/jQuery.ajax/I have created a demo for you.
Here is how your nested structure should be in Bootstrap 3:
<div class="form-group">
<label for="birthday" class="col-xs-2 control-label">Birthday</label>
<div class="col-xs-10">
<div class="form-inline">
<div class="form-group">
<input type="text" class="form-control" placeholder="year"/>
</div>
<div class="form-group">
<input type="text" class="form-control" placeholder="month"/>
</div>
<div class="form-group">
<input type="text" class="form-control" placeholder="day"/>
</div>
</div>
</div>
</div>
Notice how the whole form-inline
is nested within the col-xs-10
div containing the control of the horizontal form. In other terms, the whole form-inline
is the "control" of the birthday label in the main horizontal form.
Note that you will encounter a left and right margin problem by nesting the inline form within the horizontal form. To fix this, add this to your css:
.form-inline .form-group{
margin-left: 0;
margin-right: 0;
}
I went about it programmatically like this:
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.changeip_card_menu, menu);
for(int i = 0; i < menu.size(); i++) {
MenuItem item = menu.getItem(i);
SpannableString spanString = new SpannableString(menu.getItem(i).getTitle().toString());
spanString.setSpan(new ForegroundColorSpan(Color.BLACK), 0, spanString.length(), 0); //fix the color to white
item.setTitle(spanString);
}
return true;
}
The suggested technique above in Dave's answer is certainly a good design practice, and yes ultimately the required permission must be set in the AndroidManifest.xml file to access the external storage.
However, the Mono-esque way to add most (if not all, not sure) "manifest options" is through the attributes of the class implementing the activity (or service).
The Visual Studio Mono plugin automatically generates the manifest, so its best not to manually tamper with it (I'm sure there are cases where there is no other option).
For example:
[Activity(Label="MonoDroid App", MainLauncher=true, Permission="android.permission.WRITE_EXTERNAL_STORAGE")]
public class MonoActivity : Activity
{
protected override void OnCreate(Bundle bindle)
{
base.OnCreate(bindle);
}
}
Java generics uses type erasure. The bit in the angle brackets (<Integer>
and <String>
) gets removed, so you'd end up with two methods that have an identical signature (the add(Set)
you see in the error). That's not allowed because the runtime wouldn't know which to use for each case.
If Java ever gets reified generics, then you could do this, but that's probably unlikely now.
You can use file redirection to redirected the sorted output:
sort input-file > output_file
Or you can use the -o
, --output=FILE
option of sort to indicate the same input and output file:
sort -o file file
Without repeating the filename (with bash brace expansion)
sort -o file{,}
?? Note: A common mistake is to try to redirect the output to the same input file
(e.g. sort file > file
). This does not work as the shell is making the redirections (not the sort(1) program) and the input file (as being the output also) will be erased just before giving the sort(1) program the opportunity of reading it.
Of course, you may write a recursive algorithm in Batch that gives you exact control of what you do in every nested subdirectory:
@echo off
set mypath=
call :treeProcess
goto :eof
:treeProcess
setlocal
for %%f in (*.txt) do echo %mypath%%%f
for /D %%d in (*) do (
set mypath=%mypath%%%d\
cd %%d
call :treeProcess
cd ..
)
endlocal
exit /b
I have recently developed a simple library for PHP Enums: https://github.com/dnl-blkv/simple-php-enum
At the moment of writing this answer, it is still in pre-release stage, but already fully-functional, well-documented and published on Packagist.
This might be a handy option if you are looking for easy-to-implement enums similar to those of C/C++.
I prefer this :
<nav class="navbar">
<div class="hidden-xs hidden-sm" style="position: absolute;left: 50%;margin-left:-56px;width:112px" id="centered-div">
<!-- this element is on the center of the nav, visible only on -md and -lg -->
<a></a>
</div>
<div class="container-fluid">
<!-- ...things with your navbar... -->
<div class="visible-xs visible-sm">
<!-- this element will be hidden on -md and -lg -->
</div>
<!-- ...things with your navbar... -->
</div>
</nav>
The element is perfectly centered, and will be hidden on some screen sizes (there was no place left on -xs and -sm for me for example). I get the idea from Twitter's actual navbar
This is a little longer, but more versatile for cases where there are multiple, randomly placed, numbers in the string. Also, it requires no imports.
def getNumbers( input ):
# Collect Info
compile = ""
complete = []
for letter in input:
# If compiled string
if compile:
# If compiled and letter are same type, append letter
if compile.isdigit() == letter.isdigit():
compile += letter
# If compiled and letter are different types, append compiled string, and begin with letter
else:
complete.append( compile )
compile = letter
# If no compiled string, begin with letter
else:
compile = letter
# Append leftover compiled string
if compile:
complete.append( compile )
# Return numbers only
numbers = [ word for word in complete if word.isdigit() ]
return numbers
For Python 3:
>>> exec(open("helloworld.py").read())
Make sure that you're in the correct directory before running the command.
To run a file from a different directory, you can use the below command:
with open ("C:\\Users\\UserName\\SomeFolder\\helloworld.py", "r") as file:
exec(file.read())
You can use your exception message by:-
public class MyNullPointException extends NullPointerException {
private ExceptionCodes exceptionCodesCode;
public MyNullPointException(ExceptionCodes code) {
this.exceptionCodesCode=code;
}
@Override
public String getMessage() {
return exceptionCodesCode.getCode();
}
public class enum ExceptionCodes {
COULD_NOT_SAVE_RECORD ("cityId:001(could.not.save.record)"),
NULL_POINT_EXCEPTION_RECORD ("cityId:002(null.point.exception.record)"),
COULD_NOT_DELETE_RECORD ("cityId:003(could.not.delete.record)");
private String code;
private ExceptionCodes(String code) {
this.code = code;
}
public String getCode() {
return code;
}
}
You cannot use any of the existing lifecycle methods (componentDidMount
, componentDidUpdate
, componentWillUnmount
etc.) in a hook. They can only be used in class components. And with Hooks you can only use in functional components. The line below comes from the React doc:
If you’re familiar with React class lifecycle methods, you can think of
useEffect
Hook ascomponentDidMount
,componentDidUpdate
, andcomponentWillUnmount
combined.
suggest is, you can mimic these lifecycle method from class component in a functional components.
Code inside componentDidMount
run once when the component is mounted. useEffect
hook equivalent for this behaviour is
useEffect(() => {
// Your code here
}, []);
Notice the second parameter here (empty array). This will run only once.
Without the second parameter the useEffect
hook will be called on every render of the component which can be dangerous.
useEffect(() => {
// Your code here
});
componentWillUnmount
is use for cleanup (like removing event listeners, cancel the timer etc). Say you are adding a event listener in componentDidMount
and removing it in componentWillUnmount
as below.
componentDidMount() {
window.addEventListener('mousemove', () => {})
}
componentWillUnmount() {
window.removeEventListener('mousemove', () => {})
}
Hook equivalent of above code will be as follows
useEffect(() => {
window.addEventListener('mousemove', () => {});
// returned function will be called on component unmount
return () => {
window.removeEventListener('mousemove', () => {})
}
}, [])
console.log
has nothing to do with jQuery.
It logs a message to a debugging console, such as Firebug.
You need to use HttpContext.Current.Request.Cookies
, not Response.Cookies
.
Side note: cookies are copied to Request on Response.Cookies.Add
, which makes check on either of them to behave the same for newly added cookies. But incoming cookies are never reflected in Response
.
This behavior is documented in HttpResponse.Cookies property:
After you add a cookie by using the HttpResponse.Cookies collection, the cookie is immediately available in the HttpRequest.Cookies collection, even if the response has not been sent to the client.
Use the title
attribute, for example:
<div title="them's hoverin' words">hover me</div>
_x000D_
or:
<span title="them's hoverin' words">hover me</span>
_x000D_
Apache commons StringEscapeUtils.escapeEcmaScript(String)
returns a string with unicode characters escaped using the \u
notation.
"Art of Beer " -> "Art of Beer \u1F3A8 \u1F37A"
You have empty $_POST
. If your web-server wants see data in json-format you need to read the raw input and then parse it with JSON decode.
You need something like that:
$json = file_get_contents('php://input');
$obj = json_decode($json);
Also you have wrong code for testing JSON-communication...
CURLOPT_POSTFIELDS
tells curl
to encode your parameters as application/x-www-form-urlencoded
. You need JSON-string here.
UPDATE
Your php code for test page should be like that:
$data_string = json_encode($data);
$ch = curl_init('http://webservice.local/');
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-Type: application/json',
'Content-Length: ' . strlen($data_string))
);
$result = curl_exec($ch);
$result = json_decode($result);
var_dump($result);
Also on your web-service page you should remove one of the lines header('Content-type: application/json');
. It must be called only once.
The easiest way that I can see is delete node_modules
folder and execute npm install
.
/revive
ES6 Version using Class-y syntactic sugar
(slightly-modified: added start())
class Timer {_x000D_
constructor(callback, delay) {_x000D_
this.callback = callback_x000D_
this.remainingTime = delay_x000D_
this.startTime_x000D_
this.timerId_x000D_
}_x000D_
_x000D_
pause() {_x000D_
clearTimeout(this.timerId)_x000D_
this.remainingTime -= new Date() - this.startTime_x000D_
}_x000D_
_x000D_
resume() {_x000D_
this.startTime = new Date()_x000D_
clearTimeout(this.timerId)_x000D_
this.timerId = setTimeout(this.callback, this.remainingTime)_x000D_
}_x000D_
_x000D_
start() {_x000D_
this.timerId = setTimeout(this.callback, this.remainingTime)_x000D_
}_x000D_
}_x000D_
_x000D_
// supporting code_x000D_
const pauseButton = document.getElementById('timer-pause')_x000D_
const resumeButton = document.getElementById('timer-resume')_x000D_
const startButton = document.getElementById('timer-start')_x000D_
_x000D_
const timer = new Timer(() => {_x000D_
console.log('called');_x000D_
document.getElementById('change-me').classList.add('wow')_x000D_
}, 3000)_x000D_
_x000D_
pauseButton.addEventListener('click', timer.pause.bind(timer))_x000D_
resumeButton.addEventListener('click', timer.resume.bind(timer))_x000D_
startButton.addEventListener('click', timer.start.bind(timer))
_x000D_
<!doctype html>_x000D_
<html>_x000D_
<head>_x000D_
<title>Traditional HTML Document. ZZz...</title>_x000D_
<style type="text/css">_x000D_
.wow { color: blue; font-family: Tahoma, sans-serif; font-size: 1em; }_x000D_
</style>_x000D_
</head>_x000D_
<body>_x000D_
<h1>DOM & JavaScript</h1>_x000D_
_x000D_
<div id="change-me">I'm going to repaint my life, wait and see.</div>_x000D_
_x000D_
<button id="timer-start">Start!</button>_x000D_
<button id="timer-pause">Pause!</button>_x000D_
<button id="timer-resume">Resume!</button>_x000D_
</body>_x000D_
</html>
_x000D_
I found this here: https://port135.com/schannel-the-internal-error-state-is-10013-solved/
"Correct file permissions Correct the permissions on the c:\ProgramData\Microsoft\Crypto\RSA\MachineKeys folder:
Everyone Access: Special Applies to 'This folder only' Network Service Access: Read & Execute Applies to 'This folder, subfolders and files' Administrators Access: Full Control Applies to 'This folder, subfolder and files' System Access: Full control Applies to 'This folder, subfolder and Files' IUSR Access: Full Control Applies to 'This folder, subfolder and files' The internal error state is 10013 After these changes, restart the server. The 10013 errors should disappear."
Setting the android:scrollbarFadeDuration="0"
will do the trick.
Look at the WSGI reference implementation. You already have it in your Python libraries. It's quite simple.
var votevalue = $.map($(this).data('votevalue'), Number);
SELECT
FROM
JOINs
WHERE
GROUP By
HAVING
ORDER BY
i added
<android.support.v7.widget.Toolbar
...
android:translationZ="5dp"/>
in toolbar description and it works for me. Using 5.0+
use trim() method of javascript after all angularjs is also a javascript framework and it is not necessary to put $ to apply trim()
for example
var x="hello world";
x=x.trim()
@eric answer did the trick for me, you need to accept terms in the command you are setting i.e
"Cookie: oraclelicense=accept-securebackup-cookie"
so your final command looks thus
wget -c --header "Cookie: oraclelicense=accept-securebackup-cookie" http://download.oracle.com/otn-pub/java/jdk/8u131-b11/d54c1d3a095b4ff2b6607d096fa80163/jdk-8u131-linux-x64.tar.gz
You can decide to update the version by changing 8u131
to 8uXXX
. so long it is available in the repo.
You can also use web storage too if the app specs allows you that (it has support for IE8+).
It has 5M (most browsers) or 10M (IE) of memory at its disposal.
"Web Storage (Second Edition)" is the API and "HTML5 Local Storage" is a quick start.
Give the following command:
svn resolved <filename or directory that gives trouble>
(Thanks to @Jeremy Leipzig for this answer in a comment)
Call the super method:
Java:
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
}
@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
// TODO Add your menu entries here
super.onCreateOptionsMenu(menu, inflater);
}
Kotlin:
override fun void onCreate(savedInstanceState: Bundle) {
super.onCreate(savedInstanceState)
setHasOptionsMenu(true)
}
override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater) {
// TODO Add your menu entries here
super.onCreateOptionsMenu(menu, inflater)
}
Put log statements in the code to see if the method is not being called or if the menu is not being amended by your code.
Also ensure you are calling setHasOptionsMenu(boolean)
in onCreate(Bundle)
to notify the fragment that it should participate in options menu handling.
Strangely importing directly from $_SESSION not working but have to do this to make it work :
<?php
$phpVar = $_SESSION['var'];
?>
<script>
var variableValue= '<?php echo $phpVar; ?>';
var imported = document.createElement('script');
imported.src = './your/path/to.js';
document.head.appendChild(imported);
</script>
and in to.js
$(document).ready(function(){
alert(variableValue);
// rest of js file
For the sake of a complete solution to this problem (yes, I know that this post died long ago...) :
If you want a JSONObject
, then first get a String
from the result
:
String jsonString = EntityUtils.toString(response.getEntity());
Then you can get your JSONObject
:
JSONObject jsonObject = new JSONObject(jsonString);
I think is for prevent the browser's HTML parser from interpreting the <script>, and mainly the </script> as the closing tag of the actual script, however I don't think that using document.write is a excellent idea for evaluating script blocks, why don't use the DOM...
var newScript = document.createElement("script");
...
for date-time comparison, you can use valueOf
function of the moment which provides milliseconds of the date-time, which is best for comparison:
let date1 = moment('01-02-2020','DD-MM-YYYY').valueOf()_x000D_
let date2 = moment('11-11-2012','DD-MM-YYYY').valueOf()_x000D_
_x000D_
// alert((date1 > date2 ? 'date1' : 'date2') + " is greater..." )_x000D_
_x000D_
if (date1 > date2) {_x000D_
alert("date1 is greater..." )_x000D_
} else {_x000D_
alert("date2 is greater..." )_x000D_
}
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/moment.min.js"></script>
_x000D_
so first you have to remove the mongod.lock file by below command
sudo rm /var/lib/mongodb/mongod.lock
and then restart the mongo service by issuing below command
sudo service mongod restart
To concatenate strings, use the +
operator.
To insert data into a URI, encode it for URIs.
Bad:
var url = "http://localhost:8080/login?cid='username'&pwd='password'"
Good:
var url_safe_username = encodeURIComponent(username);
var url_safe_password = encodeURIComponent(password);
var url = "http://localhost:8080/login?cid=" + url_safe_username + "&pwd=" + url_safe_password;
The server will have to process the query string to make use of the data. You can't assign to arbitrary form fields.
… but don't trigger new windows or pass credentials in the URI (where they are exposed to over the shoulder attacks and may be logged).
PostgreSQL Create Database - Steps to create database in Postgres.
su - postgres
bash-4.1$ psql psql (12.1) Type "help" for help. postgres=#
CREATE DATABASE database_name;
Check for detailed information below: https://orahow.com/postgresql-create-database/
What do you intend to do with the overlay? If it's static, say, a simple box overlapping some content, just use absolute positioning with CSS. If it's dynamic (I believe this is called a lightbox), you can write some CSS-modifying jQuery code to show/hide the overlay on-demand.
this line should work for your 3 examples:
sed -r 's#\?(page)=([^&]*)&#/\1/\2#g' a.txt
-r
to save some escaping .test with your example (a.txt):
kent$ echo "?page=one&
?page=two&
?page=three&"|sed -r 's#\?(page)=([^&]*)&#/\1/\2#g'
/page/one
/page/two
/page/three
I created a file called test.py
and ran it on the interpreter. You may change what you want to, to test for sure how things is going on behind the scenes.
import dis
def func1():
matchesIterator = None
if matchesIterator:
print( "On if." );
def func2():
matchesIterator = None
if matchesIterator is not None:
print( "On if." );
print( "\nFunction 1" );
dis.dis(func1)
print( "\nFunction 2" );
dis.dis(func2)
This is the assembler difference:
Source:
>>> import importlib
>>> reload( test )
Function 1
6 0 LOAD_CONST 0 (None)
3 STORE_FAST 0 (matchesIterator)
8 6 LOAD_FAST 0 (matchesIterator)
9 POP_JUMP_IF_FALSE 20
10 12 LOAD_CONST 1 ('On if.')
15 PRINT_ITEM
16 PRINT_NEWLINE
17 JUMP_FORWARD 0 (to 20)
>> 20 LOAD_CONST 0 (None)
23 RETURN_VALUE
Function 2
14 0 LOAD_CONST 0 (None)
3 STORE_FAST 0 (matchesIterator)
16 6 LOAD_FAST 0 (matchesIterator)
9 LOAD_CONST 0 (None)
12 COMPARE_OP 9 (is not)
15 POP_JUMP_IF_FALSE 26
18 18 LOAD_CONST 1 ('On if.')
21 PRINT_ITEM
22 PRINT_NEWLINE
23 JUMP_FORWARD 0 (to 26)
>> 26 LOAD_CONST 0 (None)
29 RETURN_VALUE
<module 'test' from 'test.py'>
This stuff comes from ES file explorer
Just go into this app > settings
Then there is an option that says logging floating window, you just need to disable that and you will get rid of this infernal bubble for good
first pip install pillow
in command line Interface.
Images can be in jpg or png format. if you have 2 or more images and want to make in 1 pdf file.
Code:
from PIL import Image
image1 = Image.open(r'locationOfImage1\\Image1.png')
image2 = Image.open(r'locationOfImage2\\Image2.png')
image3 = Image.open(r'locationOfImage3\\Image3.png')
im1 = image1.convert('RGB')
im2 = image2.convert('RGB')
im3 = image3.convert('RGB')
imagelist = [im2,im3]
im1.save(r'locationWherePDFWillBeSaved\\CombinedPDF.pdf',save_all=True, append_images=imagelist)
I would recommend using Git Graph extension.
Converting java.util.Data
to java.sql.Data
will loose hour, minute and second. So if it is possible, I suggest you use java.sql.Timestamp
like this:
prepareStatement.setTimestamp(1, new Timestamp(utilDate.getTime()));
For more info, you can check this question.
I have 2.22 installed and this worked..
git stash pop --index 1
Assuming you alredy tried to "Add Reference..." as explained above and did not succeed, you can have a look here. They say you have to meet some prerequisites: - .NET 3.5 SP1 - Windows Installer 4.5
EDIT: According to this post it is a known issue.
And this could be the solution you're looking for :)
Well your jsonString is wrong.
String jsonString = "{\"stat\":{\"sdr\": \"aa:bb:cc:dd:ee:ff\",\"rcv\": \"aa:bb:cc:dd:ee:ff\",\"time\": \"UTC in millis\",\"type\": 1,\"subt\": 1,\"argv\": [{\"1\":2},{\"2\":3}]}}";
use this jsonString
and if you use the same JSONParser
and ContainerFactory
in the example you will see that it will be encoded/decoded.
Additionally if you want to print your string after stat
here it goes:
try{
Map json = (Map)parser.parse(jsonString, containerFactory);
Iterator iter = json.entrySet().iterator();
System.out.println("==iterate result==");
Object entry = json.get("stat");
System.out.println(entry);
}
And about the json libraries, there are a lot of them. Better you check this.
Please try this
error_reporting = E_ALL & ~E_NOTICE
in php.ini
This question was answered well at Can you encode CR/LF in into CSV files?.
Consider also reverse engineering multiple lines in Excel. To embed a newline in an Excel cell, press Alt+Enter. Then save the file as a .csv. You'll see that the double-quotes start on one line and each new line in the file is considered an embedded newline in the cell.
MATLAB's FOR loop is static in nature; you cannot modify the loop variable between iterations, unlike the for(initialization;condition;increment) loop structure in other languages. This means that the following code always prints 1, 2, 3, 4, 5 regardless of the value of B.
A = 1:5;
for i = A
A = B;
disp(i);
end
If you want to be able to respond to changes in the data structure during iterations, a WHILE loop may be more appropriate --- you'll be able to test the loop condition at every iteration, and set the value of the loop variable(s) as you wish:
n = 10;
f = n;
while n > 1
n = n-1;
f = f*n;
end
disp(['n! = ' num2str(f)])
Btw, the for-each loop in Java (and possibly other languages) produces unspecified behavior when the data structure is modified during iteration. If you need to modify the data structure, you should use an appropriate Iterator instance which allows the addition and removal of elements in the collection you are iterating. The good news is that MATLAB supports Java objects, so you can do something like this:
A = java.util.ArrayList();
A.add(1);
A.add(2);
A.add(3);
A.add(4);
A.add(5);
itr = A.listIterator();
while itr.hasNext()
k = itr.next();
disp(k);
% modify data structure while iterating
itr.remove();
itr.add(k);
end
If you have not committed any changes all you have to do is stash those changes and you will be back to the last working commit.
git stash
git stash clear
git clean
In regards to setting the logging.properties value
org.apache.tomcat.util.digester.Digester.level = SEVERE
... if you're running an embedded tomcat server in eclipse, the logging.properties
file used by default is the JDK default at %JAVA_HOME%/jre/lib/logging.properties
If you want to use a different logging.properties file (e.g. in the tomcat server's conf
directory), this needs to be set via the java.util.logging.config.file
system property. e.g. to use the logging properties defined in the file c:\java\apache-tomcat-7.0.54\conf\eclipse-logging.properties
, add this to the VM argument list:
-Djava.util.logging.config.file="c:\java\apache-tomcat-7.0.54\conf\eclipse-logging.properties"
(double-click on the server icon, click 'Open launch configuration', select the Arguments tab, then enter this in the 'VM arguments' text box)
You might also find it useful to add the VM argument
-Djava.util.logging.SimpleFormatter.format="%1$tc %4$s %3$s %5$s%n"
as well, which will then include the source logger name in the output, which should make it easier to determine which logger to throttle in the logging.properties file (as per http://docs.oracle.com/javase/7/docs/api/java/util/logging/SimpleFormatter.html )
We can also use Kotlin lambda
editText.setOnKeyListener { _, keyCode, keyEvent ->
if (keyEvent.action == KeyEvent.ACTION_DOWN && keyCode == KeyEvent.KEYCODE_ENTER) {
Log.d("Android view component", "Enter button was pressed")
return@setOnKeyListener true
}
return@setOnKeyListener false
}
This jQuery plugin gives you a pre-made way of selection/caret manipulation.
With SSL/https and with CSRF_COOKIE_HTTPONLY = False, I still don't have csrftoken in the cookie, either using the getCookie(name) function proposed in django Doc or the jquery.cookie.js proposed by fivef.
Wtower summary is perfect and I thought it would work after removing CSRF_COOKIE_HTTPONLY from settings.py but it does'nt in https!
Why csrftoken is not visible in document.cookie???
Instead of getting
"django_language=fr; csrftoken=rDrGI5cp98MnooPIsygWIF76vuYTkDIt"
I get only
"django_language=fr"
WHY? Like SSL/https removes X-CSRFToken from headers I thought it was due to the proxy header params of Nginx but apparently not... Any idea?
Unlike django doc Notes, it seems impossible to work with csrf_token in cookies with https. The only way to pass csrftoken is through the DOM by using {% csrf_token %} in html and get it in jQuery by using
var csrftoken = $('input[name="csrfmiddlewaretoken"]').val();
It is then possible to pass it to ajax either by header (xhr.setRequestHeader), either by params.
Try to remove armv7s from project's "Valid architecture" to release from this issue for iOS 5.1 phone
Its simple, just make sure the data type in your columns are the same. For e.g. I faced the same error, that and an another error:
Error in
contrasts<-
(*tmp*
, value = contr.funs[1 + isOF[nn]]) : contrasts can be applied only to factors with 2 or more levels
So, I went back to my excel file or csv file, set a filter on the variable throwing me an error and checked if the distinct datatypes are the same. And... Oh! it had numbers and strings, so I converted numbers to string and it worked just fine for me.
No problem, first:
OR
Now that the mouse cursor is blinking on your first selection, using a few more Key Bindings (thanks for the ref j08691) you may:
In your example, you can simply replace null
with `nil and it will work fine.
require 'erb'
template = <<EOS
<% if (@objectname != nil) then %>
@objectname is not nil
<% else %>
@objectname is nil
<% end %>
EOS
@objectname = nil
ERB.new(template, nil, '>').result # => " @objectname is nil\n"
@objectname = 'some name'
ERB.new(template, nil, '>').result # => " @objectname is not nil\n"
Contrary to what the other poster said, you can see above that then
works fine in Ruby. It's not common, but it is fine.
#blank?
and #present?
have other implications. Specifically, if the object responds to #empty?
, they will check whether it is empty. If you go to http://api.rubyonrails.org/ and search for "blank?", you will see what objects it is defined on and how it works. Looking at the definition on Object, we see "An object is blank if it’s false, empty, or a whitespace string. For example, “”, “ ”, nil, [], and {} are all blank." You should make sure that this is what you want.
Also, nil is considered false, and anything other than false and nil is considered true. This means you can directly place the object in the if statement, so a more canonical way of writing the above would be
require 'erb'
template = <<EOS
<% if @objectname %>
@objectname is not nil
<% else %>
@objectname is nil
<% end %>
EOS
@objectname = nil
ERB.new(template, nil, '>').result # => " @objectname is nil\n"
@objectname = 'some name'
ERB.new(template, nil, '>').result # => " @objectname is not nil\n"
If you explicitly need to check nil
and not false
, you can use the #nil?
method, for which nil is the only object that will cause this to return true.
nil.nil? # => true
false.nil? # => false
Object.new.nil? # => false
In Python 3.9, a new removeprefix
method is being added:
>>> 'TestHook'.removeprefix('Test')
'Hook'
>>> 'BaseTestCase'.removeprefix('Test')
'BaseTestCase'
I assume you want lowercase the text. Solution is pretty simple:
ggVGu
Explanation:
JavaScript is Object-Based, not Object-Oriented. The difference is that Object-Based languages don't support proper inheritance, whereas Object-Oriented ones do.
There is a way to achieve 'normal' inheritance in JavaScript (Reference here), but the basic model is based on prototyping.
I did remove integrated security ... my goal is to log onto a sql server using a connection string WITH active directory username / password. When I do that it always fails. Does not matter the format ... sam company\user ... upn [email protected] ... basic username.
var obj = {name: 'Krishna', gender: 'male'};
angular.forEach(obj, function(value, key) {
console.log(key + ': ' + value);
});
yields the attributes of obj
with their respective values:
name: Krishna
gender: male
This should do the trick:
Combox1.SelectedIndex = Combox1.FindStringExact("test1")
Date td = new Date();
String b = new String("");
SimpleDateFormat format = new SimpleDateFormat("YYYY/MM/dd");
b = format.format(td);
out.println(b);
One way to do this is to set the maximum size in web.config as has already been stated above e.g.
<system.web>
<httpRuntime maxRequestLength="102400" />
</system.web>
then when you handle the upload event, check the size and if its over a specific amount, you can trap it e.g.
protected void btnUploadImage_OnClick(object sender, EventArgs e)
{
if (fil.FileBytes.Length > 51200)
{
TextBoxMsg.Text = "file size must be less than 50KB";
}
}
It seems like there may be a issue to dump numpy.int64 into json string in Python 3 and the python team already have a conversation about it. More details can be found here.
There is a workaround provided by Serhiy Storchaka. It works very well so I paste it here:
def convert(o):
if isinstance(o, numpy.int64): return int(o)
raise TypeError
json.dumps({'value': numpy.int64(42)}, default=convert)
background-size: contain;
suits me
self.navigationController != nil would mean it's in a navigation stack.
In order to handle the case that the current view controller is pushed while the navigation controller is presented modally, I have added some lines of code to check if the current view controller is the root controller in the navigation stack .
extension UIViewController {
var isModal: Bool {
if let index = navigationController?.viewControllers.firstIndex(of: self), index > 0 {
return false
} else if presentingViewController != nil {
return true
} else if let navigationController = navigationController, navigationController.presentingViewController?.presentedViewController == navigationController {
return true
} else if let tabBarController = tabBarController, tabBarController.presentingViewController is UITabBarController {
return true
} else {
return false
}
}
}
I don't know the answer for SQL Server but...
In MySQL save it as FLOAT( 10, 6 )
This is the official recommendation from the Google developer documentation.
CREATE TABLE `coords` (
`lat` FLOAT( 10, 6 ) NOT NULL ,
`lng` FLOAT( 10, 6 ) NOT NULL ,
) ENGINE = MYISAM ;
If the above doesn't work for you, try this:
.btn:focus {outline: none;box-shadow: none;border:2px solid transparent;}
As user1933897 pointed out, this might be specific to MacOS with Chrome.
I know it's been long but for anyone else encountering this issue, my problem is that I was looping through an array of arrays containing only one array. Like this:
// array snippet (returned from here)
} else {
callback([results])
}
And I was using the array like this
for(const result of results){
console.log(result.x)
}
As you can see, the array I wanted to iterate over was actually inside another array. removing the square brackets helped. Node JS and MySQL.
This just works:
$body = @{
"UserSessionId"="12345678"
"OptionalEmail"="[email protected]"
} | ConvertTo-Json
$header = @{
"Accept"="application/json"
"connectapitoken"="97fe6ab5b1a640909551e36a071ce9ed"
"Content-Type"="application/json"
}
Invoke-RestMethod -Uri "http://MyServer/WSVistaWebClient/RESTService.svc/member/search" -Method 'Post' -Body $body -Headers $header | ConvertTo-HTML
The URL approach will only work for small HTML fragements. The more solid approach is to generate an object URL from a blob and use it as a source of the dynamic iframe.
const html = '<html>...</html>';
const iframe = document.createElement('iframe');
const blob = new Blob([html], {type: 'text/html'});
iframe.src = window.URL.createObjectURL(blob);
document.body.appendChild(iframe);
make sure ,use this 404 route wrote on the bottom of the code.
syntax will be like
{
path: 'page-not-found',
component: PagenotfoundComponent
},
{
path: '**',
redirectTo: '/page-not-found'
},
Thank you
RewriteCond %{REQUEST_URI} foobar
RewriteRule .* index.php
/* The noConflict() method releases the hold on the $ shortcut identifier, so that other scripts can use it. */
var jq = $.noConflict();
(function($){
$('document').ready(function(){
$('button').click(function(){
alert($('.para').text());
})
})
})(jq);
Live view example on codepen that is easy to understand: http://codepen.io/kaushik/pen/QGjeJQ
These are timeout values enforced by JVM for TCP connection establishment and waiting on reading data from socket.
If the value is set to infinity, you will not wait forever. It simply means JVM doesn't have timeout and OS will be responsible for all the timeouts. However, the timeouts on OS may be really long. On some slow network, I've seen timeouts as long as 6 minutes.
Even if you set the timeout value for socket, it may not work if the timeout happens in the native code. We can reproduce the problem on Linux by connecting to a host blocked by firewall or unplugging the cable on switch.
The only safe approach to handle TCP timeout is to run the connection code in a different thread and interrupt the thread when it takes too long.
You can simply do this:
Name.objects.exclude(alias="").exclude(alias=None)
It's really just that simple. filter
is used to match and exclude
is to match everything but what it specifies. This would evaluate into SQL as NOT alias='' AND alias IS NOT NULL
.
Yes, you can access a form in the controller (as stated in the docs).
Except when your form is not defined in the controller scope and is defined in a child scope instead.
Basically, some angular directives, such as ng-if
, ng-repeat
or ng-include
, will create an isolated child scope. So will any custom directives with a scope: {}
property defined. Probably, your foundation components are also in your way.
I had the same problem when introducing a simple ng-if
around the <form>
tag.
See these for more info:
Note: I suggest you re-write your question. The answer to your question is yes but your problem is slightly different:
Can I access a form in a child scope from the controller?
To which the answer would simply be: no.
var myNode = document.getElementById("foo");
var fc = myNode.firstChild;
while( fc ) {
myNode.removeChild( fc );
fc = myNode.firstChild;
}
If there's any chance that you have jQuery affected descendants, then you must use some method that will clean up jQuery data.
$('#foo').empty();
The jQuery .empty()
method will ensure that any data that jQuery associated with elements being removed will be cleaned up.
If you simply use DOM
methods of removing the children, that data will remain.
A callback is commonly used in asynchronous programming, so you could create a method which handles the response from a web service. When you call the web service, you could pass the method to it so that when the web service responds, it call's the method you told it ... it "calls back".
In Java this can commonly be done through implementing an interface and passing an object (or an anonymous inner class) that implements it. You find this often with transactions and threading - such as the Futures API.
http://docs.oracle.com/javase/1.5.0/docs/api/java/util/concurrent/Future.html
as in javascript:
mydata.match(/'([^']+)'/)[1]
the actual regexp is: /'([^']+)'/
if you use the non greedy modifier (as per another post) it's like this:
mydata.match(/'(.*?)'/)[1]
it is cleaner.
Any mature enough SQL database should be able to execute that just as effectively as the equivalent JOIN
. Use whatever is more readable to you.
In my case, the problem was I was linking to debug python
& boost::Python
, which requires that the extension be FooLib_d.pyd
, not just FooLib.pyd
; renaming the file or updating CMakeLists.txt
properties fixed the error.
If so simple than many people think, me included :)
cd to Project Folder/src/package
there you should see yourClass.java then run javac yourClass.java
which will create yourClass.class then cd out of the src
folder and into the build
folder there you can run java package.youClass
I am using the Terminal on Mac or you can accomplish the same task using Command Prompt on windows
Scanner sc=new Scanner(System.in) ;
int p[][] = new int[n][] ;
for(int i=0 ; i<n ; i++)
{
int m = sc.nextInt() ; //Taking input from user in JAVA.
p[i]=new int[m] ; //Allocating memory block of 'm' int size block.
for(int j=0 ; j<m ; j++)
{
p[i][j]=sc.nextInt(); //Initializing 2D array block.
}
}
Wrong syntax. Here you are:
insert into user_by_category (game_category,customer_id) VALUES ('Goku','12');
or:
insert into user_by_category ("game_category","customer_id") VALUES ('Kakarot','12');
The second one is normally used for case-sensitive column names.
I know this thread is old, but just in case there's someone else having this issue. This is a trick I used without touching the CI db classes. Leave your debug on and in your error view file, throw an exception.
So in you db config, you have :
$db['default']['db_debug'] = true;
Then in your db error view file, mine is in application/errors/error_db.php
replace all content with the following:
<?php
$message = preg_replace('/(<\/?p>)+/', ' ', $message);
throw new Exception("Database error occured with message : {$message}");
?>
Since the view file will be called, the error will always get thrown as an exception, you may later add different views for different environment.
My fix was to create Platform in configuration manager in visual studio, and set to x64