Someone posted this link to the MDN in a comment, and I think it was very helpful. It describes things like ErrorTypes very thoroughly.
EvalError --- Creates an instance representing an error that occurs regarding the global function eval().
InternalError --- Creates an instance representing an error that occurs when an internal error in the JavaScript engine is thrown. E.g. "too much recursion".
RangeError --- Creates an instance representing an error that occurs when a numeric variable or parameter is outside of its valid range.
ReferenceError --- Creates an instance representing an error that occurs when de-referencing an invalid reference.
SyntaxError --- Creates an instance representing a syntax error that occurs while parsing code in eval().
TypeError --- Creates an instance representing an error that occurs when a variable or parameter is not of a valid type.
URIError --- Creates an instance representing an error that occurs when encodeURI() or decodeURI() are passed invalid parameters.
Update: In an effort to answer my own question, here is what I've been able to uncover so far. If anyone else out there has something, I'd still be interested to find out more.
Based on JSON Schema
Commercial (No endorsement intended or implied, may or may not meet requirement)
jQuery
YAML
See Also
Use this code to pass arraylist<customobj>
to anthother Activity
firstly serialize our contact bean
public class ContactBean implements Serializable {
//do intialization here
}
Now pass your arraylist
Intent intent = new Intent(this,name of activity.class);
contactBean=(ConactBean)_arraylist.get(position);
intent.putExtra("contactBeanObj",conactBean);
_activity.startActivity(intent);
An example:
to select all <a>
s with ID ending in _edit:
jQuery("a[id$=_edit]")
or
jQuery("a[id$='_edit']")
for(int index = 0; index < ((ViewGroup) viewGroup).getChildCount(); index++) {
View nextChild = ((ViewGroup) viewGroup).getChildAt(index);
}
Will that do?
You can simply put an a tag around the element:
<a href="http://google.com" target="_blank">
<button>My Button</button>
</a>
pgrep -f process_name > any_file_name
sed -i 's/^/kill /' any_file_name
chmod 777 any_file_name
./any_file_name
for example 'pgrep -f firefox' will grep the PID of running 'firefox' and will save this PID to a file called 'any_file_name'. 'sed' command will add the 'kill' in the beginning of the PID number in 'any_file_name' file. Third line will make 'any_file_name' file executable. Now forth line will kill the PID available in the file 'any_file_name'. Writing the above four lines in a file and executing that file can do the control-C. Working absolutely fine for me.
I'm sorry to say that to the best of my knowledge a pure PHP upload progress bar, or even a PHP/Javascript upload progress bar is not possible because of how PHP works. Your best bet is to use some form of Flash uploader.
AFAIK This is because your script is not executed until all the superglobals are populated, which includes $_FILES. By the time your PHP script gets called, the file is fully uploaded.
EDIT: This is no longer true. It was in 2010.
This has bitten me a second time so I thought might be worth mentioning. The line listen_addresses = '*' in the postgresql.conf is by default commented. Be sure to uncomment (remove the pound sign, # at the beginning) it after updating otherwise, remote connections will continue to be blocked.
Another option is to use jq
:
$ seq 10|jq -s add
55
-s
(--slurp
) reads the input lines into an array.
Didn't work for me, when I tried to use it in UITableViewController
on self.tableView
(iOS 4.1)
, after adding footerView
. It scrolls out of the borders, showing black screen.
Alternative solution:
CGFloat height = self.tableView.contentSize.height;
[self.tableView setTableFooterView: myFooterView];
[self.tableView reloadData];
CGFloat delta = self.tableView.contentSize.height - height;
CGPoint offset = [self.tableView contentOffset];
offset.y += delta;
[self.tableView setContentOffset: offset animated: YES];
There are lots of free tools that can do this.
I use PDFTK (a open source cross-platform command-line tool) for things like that.
You can check this
[Route("Report/MyReport")]
public IHttpActionResult GetReport()
{
string url = "https://localhost:44305/Templates/ReportPage.html";
System.Uri uri = new System.Uri(url);
return Redirect(uri);
}
Regarding os.linesep:
Here is an exact unedited Python 2.7.1 interpreter session on Windows:
Python 2.7.1 (r271:86832, Nov 27 2010, 18:30:46) [MSC v.1500 32 bit (Intel)] on
win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import os
>>> os.linesep
'\r\n'
>>> f = open('myfile','w')
>>> f.write('hi there\n')
>>> f.write('hi there' + os.linesep) # same result as previous line ?????????
>>> f.close()
>>> open('myfile', 'rb').read()
'hi there\r\nhi there\r\r\n'
>>>
On Windows:
As expected, os.linesep does NOT produce the same outcome as '\n'
. There is no way that it could produce the same outcome. 'hi there' + os.linesep
is equivalent to 'hi there\r\n'
, which is NOT equivalent to 'hi there\n'
.
It's this simple: use \n
which will be translated automatically to os.linesep. And it's been that simple ever since the first port of Python to Windows.
There is no point in using os.linesep on non-Windows systems, and it produces wrong results on Windows.
DO NOT USE os.linesep!
SELECT CAST(CAST(year AS varchar) + '/' + CAST(month AS varchar) + '/' + CAST(day as varchar) AS datetime) AS MyDateTime
FROM table
Found a Fix:
First ensure that printing is working from Report Manager (open a report in Report Manager and print from there).
If it works go to Step 3, if you received the same error you need to install the following patches on the Report Server.
KB954606 - Security Update for SQL Server SP2
ReportViewer 2005 SP1
http://www.microsoft.com/downloads/details.aspx?familyid=82833F27-081D-4B72-83EF-2836360A904D
Download and install the following update:
KB954607 - Security Update for SQL Server SP2
I also had the same problem.I fix this problem by editing Graphics of AVD. Tools > Androids > AVD Manager > Actions > Edit > Show Advance Settings > Graphics -> Software. I hope this solution help u!
These steps worked for me to increase the space on my windows VM:
Resize the VDI:
VBoxManage modifyhd Cloned.vdi --resize 45000
Run your cloned VM, go to Disk Management and extend the volume.
Setup JAVA_OPTS as a system variable with the following content:
JAVA_OPTS="-Xms256m -Xmx512m"
After that in a command prompt run the following commands:
SET JAVA_OPTS="-Xms256m -Xmx512m"
This can be explained as follows:
These values should be changed according to application requirements.
EDIT:
You can also try adding it through the Environment Properties menu which can be found at:
EDIT 2:
JAVA_OPTS is a system variable that stores various settings/configurations for your local Java Virtual Machine. By having JAVA_OPTS set as a system variable all applications running on top of the JVM will take their settings from this parameter.
To setup a system variable you have to complete the steps listed above from 1 to 4.
Above tools extract the jar. Also there are certain other tools and commands to extract the jar. But AFAIK you cant get the java code in case code has been obfuscated.
For VS2010:
SET VS90COMNTOOLS=%VS100COMNTOOLS%
For VS2012:
SET VS90COMNTOOLS=%VS110COMNTOOLS%
then Call:
pip install pyCrypto
For case-insensitive string search, use index
(or rindex
) in combination with fc
. This example expands on the answer by Eugene Yarmash:
use feature qw( fc );
my $str = "Abc";
my $substr = "aB";
print "found" if index( fc $str, fc $substr ) != -1;
# Prints: found
print "found" if rindex( fc $str, fc $substr ) != -1;
# Prints: found
$str = "Abc";
$substr = "bA";
print "found" if index( fc $str, fc $substr ) != -1;
# Prints nothing
print "found" if rindex( fc $str, fc $substr ) != -1;
# Prints nothing
Both index
and rindex
return -1
if the substring is not found.
And fc
returns a casefolded version of its string argument, and should be used here instead of the (more familiar) uc
or lc
. Remember to enable this function, for example with use feature qw( fc );
.
Your IDs are #1
, and cycle
just wants a number passed to it. You need to remove the #
before calling cycle
.
$('a.pagerlink').click(function() {
var id = $(this).attr('id');
$container.cycle(id.replace('#', ''));
return false;
});
Also, IDs shouldn't contain the #
character, it's invalid (numeric IDs are also invalid). I suggest changing the ID to something like pager_1
.
<a href="#" id="pager_1" class="pagerlink" >link</a>
$('a.pagerlink').click(function() {
var id = $(this).attr('id');
$container.cycle(id.replace('pager_', ''));
return false;
});
Listed are the steps that could rectify the error:
services.msc
and strike Enterora
start these services and wait!!orcl
) mysql
or whatever you are using and start coding.PI'm looking for a function that checks only if it's one of the Latin letters or a decimal number. Since char c = 255
, which in printable version is + and considered as a letter by Character.isLetter(c)
.
This function I think is what most developers are looking for:
private static boolean isLetterOrDigit(char c) {
return (c >= 'a' && c <= 'z') ||
(c >= 'A' && c <= 'Z') ||
(c >= '0' && c <= '9');
}
Alternative way to convert object to byte array:
TypeConverter objConverter = TypeDescriptor.GetConverter(objMsg.GetType());
byte[] data = (byte[])objConverter.ConvertTo(objMsg, typeof(byte[]));
**add the icon top button like this **
#copy_btn{_x000D_
align-items: center;_x000D_
position: absolute;_x000D_
width: 30px;_x000D_
height: 30px;_x000D_
background-color: Transparent;_x000D_
background-repeat:no-repeat;_x000D_
border: none;_x000D_
cursor:pointer;_x000D_
overflow: hidden;_x000D_
outline:none;_x000D_
}_x000D_
.icon_copy{_x000D_
position: absolute;_x000D_
padding: 0px;_x000D_
top:0;_x000D_
left: 0;_x000D_
width: 25px;_x000D_
height: 35px;_x000D_
_x000D_
}
_x000D_
<button id="copy_btn">_x000D_
_x000D_
<img class="icon_copy" src="./assest/copy.svg" alt="Copy Text">_x000D_
</button>
_x000D_
When using environment variables for volumes you need:
create .env file in the same folder which contains docker-compose.yaml
file
declare variable in the .env
file:
HOSTNAME=your_hostname
Change $hostname
to ${HOSTNAME}
at docker-compose.yaml
file
proxy:
hostname: ${HOSTNAME}
volumes:
- /mnt/data/logs/${HOSTNAME}:/logs
- /mnt/data/${HOSTNAME}:/data
Of course you can do that dynamically on each build like:
echo "HOSTNAME=your_hostname" > .env && sudo docker-compose up
while True:
...
means infinite loop.
The while statement is often used of a finite loop. But using the constant 'True' guarantees the repetition of the while statement without the need to control the loop (setting a boolean value inside the iteration for example), unless you want to break it.
In fact
True == (1 == 1)
Try this solution for the perfectly working
new YouTubeToHtml5();Useful sns.heatmap
api is here. Check out the parameters, there are a good number of them. Example:
import seaborn as sns
%matplotlib inline
idx= ['aaa','bbb','ccc','ddd','eee']
cols = list('ABCD')
df = DataFrame(abs(np.random.randn(5,4)), index=idx, columns=cols)
# _r reverses the normal order of the color map 'RdYlGn'
sns.heatmap(df, cmap='RdYlGn_r', linewidths=0.5, annot=True)
ActiveSheet.UsedRange.Rows.Count + ActiveSheet.UsedRange.Rows(1).Row -1
Short. Safe. Fast. Will return the last non-empty row even if there are blank lines on top of the sheet, or anywhere else. Works also for an empty sheet (Excel reports 1 used row on an empty sheet so the expression will be 1). Tested and working on Excel 2002 and Excel 2010.
If you are on SQL Server 2008 or later you can use the date datatype:
SELECT *
FROM [User] U
WHERE CAST(U.DateCreated as DATE) = '2014-02-07'
It should be noted that if date column is indexed then this will still utilise the index and is SARGable. This is a special case for dates and datetimes.
You can see that SQL Server actually turns this into a > and < clause:
I've just tried this on a large table, with a secondary index on the date column as per @kobik's comments and the index is still used, this is not the case for the examples that use BETWEEN or >= and <:
SELECT *
FROM [User] U
WHERE CAST(U.DateCreated as DATE) = '2016-07-05'
Just remove the .value
, like this:
function(arrayP){
for(var i = 0; i < arrayP.length; i++){
alert(arrayP[i]); //no .value here
}
}
Sure you can pass an array, but to get the element at that position, use only arrayName[index]
, the .value
would be getting the value
property off an object at that position in the array - which for things like strings, numbers, etc doesn't exist. For example, "myString".value
would also be undefined
.
To remove the license key:
In my case on a Windows 7 machine I could find this license key in C:\Users\you\.IntelliJIdea13\config\idea13.key
I got the Error even though i was catching the exception.
try {
bitmap = BitmapFactory.decodeStream(getAssets().open("kitten.jpg"));
} catch (IOException e) {
Log.e("blabla", "Error", e);
finish();
}
Issue was that the IOException wasn't imported
import java.io.IOException;
Why do I need the descriptor class?
It gives you extra control over how attributes work. If you're used to getters and setters in Java, for example, then it's Python's way of doing that. One advantage is that it looks to users just like an attribute (there's no change in syntax). So you can start with an ordinary attribute and then, when you need to do something fancy, switch to a descriptor.
An attribute is just a mutable value. A descriptor lets you execute arbitrary code when reading or setting (or deleting) a value. So you could imagine using it to map an attribute to a field in a database, for example – a kind of ORM.
Another use might be refusing to accept a new value by throwing an exception in __set__
– effectively making the "attribute" read only.
What is
instance
andowner
here? (in__get__
). What is the purpose of these parameters?
This is pretty subtle (and the reason I am writing a new answer here - I found this question while wondering the same thing and didn't find the existing answer that great).
A descriptor is defined on a class, but is typically called from an instance. When it's called from an instance both instance
and owner
are set (and you can work out owner
from instance
so it seems kinda pointless). But when called from a class, only owner
is set – which is why it's there.
This is only needed for __get__
because it's the only one that can be called on a class. If you set the class value you set the descriptor itself. Similarly for deletion. Which is why the owner
isn't needed there.
How would I call/use this example?
Well, here's a cool trick using similar classes:
class Celsius:
def __get__(self, instance, owner):
return 5 * (instance.fahrenheit - 32) / 9
def __set__(self, instance, value):
instance.fahrenheit = 32 + 9 * value / 5
class Temperature:
celsius = Celsius()
def __init__(self, initial_f):
self.fahrenheit = initial_f
t = Temperature(212)
print(t.celsius)
t.celsius = 0
print(t.fahrenheit)
(I'm using Python 3; for python 2 you need to make sure those divisions are / 5.0
and / 9.0
). That gives:
100.0
32.0
Now there are other, arguably better ways to achieve the same effect in python (e.g. if celsius were a property, which is the same basic mechanism but places all the source inside the Temperature class), but that shows what can be done...
Just came across the following solution:
http://www.mydailyhacks.org/2014/11/05/php-multifile-uploader-for-php-5-4-5-5/
it is a ready PHP Multi File Upload Script with an form where you can add multiple inputs and an AJAX progress bar. It should work directly after unpacking on the server...
You didn't mention the fancy indexing capabilities of dataframes, e.g.:
>>> df = pd.DataFrame({"class":[1,1,1,2,2], "value":[1,2,3,4,5]})
>>> df[df["class"]==1].sum()
class 3
value 6
dtype: int64
>>> df[df["class"]==1].sum()["value"]
6
>>> df[df["class"]==1].count()["value"]
3
You could replace df["class"]==1
by another condition.
Uninstall VirtualBox with uninstaller (it comes with dmg), then install VirtualBox again. This has solved that issue for me.
Code & detects ctrl+z
document.onkeyup = function(e) {
if(e.ctrlKey && e.keyCode == 90) {
// ctrl+z pressed
}
}
Merge - HEAD branch will generate a new commit, preserving the ancestry of each commit history. History can become polluted if merge commits are made by multiple people who work on the same branch in parallel.
Rebase - Re-writes the changes of one branch onto another without creating a new commit. The code history is simplified, linear and readable but it doesn't work with pull requests, because you can't see what minor changes someone made.
I would use git merge
when dealing with feature-based workflow or if I am not familiar with rebase. But, if I want a more a clean, linear history then git rebase
is more appropriate. For more details be sure to check out this merge or rebase article.
If you are using the Git Bash shell, you can use the following trick:
> webpage.html
This is actually the same as:
echo "" > webpage.html
Then, you can use git add webpage.html
to stage the file.
This function trims a string from left and right. Also it removes carriage returns from the string, an action which is not done by the LTRIM and RTRIM
IF OBJECT_ID(N'dbo.TRIM', N'FN') IS NOT NULL
DROP FUNCTION dbo.TRIM;
GO
CREATE FUNCTION dbo.TRIM (@STR NVARCHAR(MAX)) RETURNS NVARCHAR(MAX)
BEGIN
RETURN(LTRIM(RTRIM(REPLACE(REPLACE(@STR ,CHAR(10),''),CHAR(13),''))))
END;
GO
Somewhat more on the infrastructure side:
Python has much better integration with C++ (via things like Boost.Python, SIP, and Py++) than Ruby, where the options seem to be either write directly against the Ruby interpreter API (which you can do with Python as well, of course, but in both cases doing so is low level, tedious, and error prone) or use SWIG (which, while it works and definitely is great if you want to support many languages, isn't nearly as nice as Boost.Python or SIP if you are specifically looking to bind C++).
Python has a number of web application environments (Django, Pylons/Turbogears, web.py, probably at least half a dozen others), whereas Ruby (effectively) has one: Rails. (Other Ruby web frameworks do exist, but seemingly have a hard time getting much traction against Rails). Is this aspect good or bad? Hard to say, and probably quite subjective; I can easily imagine arguments that the Python situation is better and that the Ruby situation is better.
Culturally, the Python and Ruby communities seem somewhat different, but I can only hint at this as I don't have that much experience interacting with the Ruby community. I'm adding this mostly in the hopes that someone who has a lot of experience with both can amplify (or reject) this statement.
From official documentation :
To enable Google to crawl your app content and allow users to enter your app from search results, you must add intent filters for the relevant activities in your app manifest. These intent filters allow deep linking to the content in any of your activities. For example, the user might click on a deep link to view a page within a shopping app that describes a product offering that the user is searching for.
Using this link Enabling Deep Links for App Content you'll see how to use it.
And using this Test Your App Indexing Implementation how to test it.
The following XML snippet shows how you might specify an intent filter in your manifest for deep linking.
<activity
android:name="com.example.android.GizmosActivity"
android:label="@string/title_gizmos" >
<intent-filter android:label="@string/filter_title_viewgizmos">
<action android:name="android.intent.action.VIEW" />
<category android:name="android.intent.category.DEFAULT" />
<category android:name="android.intent.category.BROWSABLE" />
<!-- Accepts URIs that begin with "http://www.example.com/gizmos” -->
<data android:scheme="http"
android:host="www.example.com"
android:pathPrefix="/gizmos" />
<!-- note that the leading "/" is required for pathPrefix-->
<!-- Accepts URIs that begin with "example://gizmos” -->
<data android:scheme="example"
android:host="gizmos" />
</intent-filter>
</activity>
To test via Android Debug Bridge
$ adb shell am start
-W -a android.intent.action.VIEW
-d <URI> <PACKAGE>
$ adb shell am start
-W -a android.intent.action.VIEW
-d "example://gizmos" com.example.android
Adding to Sani's and blak3r's answers, I've added the following to the startup code for my application, but in VB:
'** Overriding the certificate validation check.
Net.ServicePointManager.ServerCertificateValidationCallback = Function(sender, certificate, chain, sslPolicyErrors) True
Seems to do the trick.
I'm assuming you've got a nice fat USB HD and a good connection to the net. You can use apt-mirror to essentially create your own debian mirror.
What does the UDF EntityHasProfile() do?
Typically you could do something like this with a LEFT JOIN:
SELECT EntityId, EntityName, CASE WHEN EntityProfileIs IS NULL THEN 0 ELSE 1 END AS Has Profile
FROM Entities
LEFT JOIN EntityProfiles
ON EntityProfiles.EntityId = Entities.EntityId
This should eliminate a need for a costly scalar UDF call - in my experience, scalar UDFs should be a last resort for most database design problems in SQL Server - they are simply not good performers.
My version for a directive that uses jqplot to plot the data once it becomes available:
app.directive('lineChart', function() {
$.jqplot.config.enablePlugins = true;
return function(scope, element, attrs) {
scope.$watch(attrs.lineChart, function(newValue, oldValue) {
if (newValue) {
// alert(scope.$eval(attrs.lineChart));
var plot = $.jqplot(element[0].id, scope.$eval(attrs.lineChart), scope.$eval(attrs.options));
}
});
}
});
From previous project experience, this is a good way:
In the constants.js:
// constants.js
'use strict';
let constants = {
key1: "value1",
key2: "value2",
key3: {
subkey1: "subvalue1",
subkey2: "subvalue2"
}
};
module.exports =
Object.freeze(constants); // freeze prevents changes by users
In main.js (or app.js, etc.), use it as below:
// main.js
let constants = require('./constants');
console.log(constants.key1);
console.dir(constants.key3);
The List<>
class does guarantee ordering - things will be retained in the list in the order you add them, including duplicates, unless you explicitly sort the list.
According to MSDN:
...List "Represents a strongly typed list of objects that can be accessed by index."
The index values must remain reliable for this to be accurate. Therefore the order is guaranteed.
You might be getting odd results from your code if you're moving the item later in the list, as your Remove()
will move all of the other items down one place before the call to Insert()
.
Can you boil your code down to something small enough to post?
I want to extend this topic/answers with the following. As someone mentioned, this auto-generated AssemblyInfo can be an obstacle for the external tools. In my case, using FinalBuilder, I had an issue that AssemblyInfo wasn't getting updated by build action. Apparently, FinalBuilder relies on ~proj
file to find location of the AssemblyInfo. I thought, it was looking anywhere under project folder. No. So, changing this
<PropertyGroup>
<GenerateAssemblyInfo>false</GenerateAssemblyInfo>
</PropertyGroup>
did only half the job, it allowed custom assembly info if built by VS IDE/MS Build. But I needed FinalBuilder do it too without manual manipulations to assembly info file. I needed to satisfy all programs, MSBuild/VS and FinalBuilder.
I solved this by adding an entry to the existing ItemGroup
<ItemGroup>
<Compile Remove="Common\**" />
<Content Remove="Common\**" />
<EmbeddedResource Remove="Common\**" />
<None Remove="Common\**" />
<!-- new added item -->
<None Include="Properties\AssemblyInfo.cs" />
</ItemGroup>
Now, having this item, FinalBuilder finds location of AssemblyInfo and modifies the file. While action None
allows MSBuild/DevEnv ignore this entry and no longer report an error based on Compile
action that usually comes with Assembly Info entry in proj
files.
C:\Program Files\dotnet\sdk\2.0.2\Sdks\Microsoft.NET.Sdk\build\Microsoft.NET.Sdk.DefaultItems.targets(263,5): error : Duplicate 'Compile' items were included. The .NET SDK includes 'Compile' items from your project directory by default. You can either remove these items from your project file, or set the 'EnableDefaultCompileItems' property to 'false' if you want to explicitly include them in your project file. For more information, see https://aka.ms/sdkimplicititems. The duplicate items were: 'AssemblyInfo.cs'
In header.php
insert this code to show menu:
<?php
wp_nav_menu(
array(
'theme_location' => 'menu-one',
'walker' => new Custom_Walker_Nav_Menu_Top
)
);
?>
In functions.php
use this:
class Custom_Walker_Nav_Menu_top extends Walker_Nav_Menu
{
function start_el( &$output, $item, $depth = 0, $args = array(), $id = 0 ) {
$is_current_item = '';
if(array_search('current-menu-item', $item->classes) != 0)
{
$is_current_item = ' class="active"';
}
echo '<li'.$is_current_item.'><a href="'.$item->url.'">'.$item->title;
}
function end_el( &$output, $item, $depth = 0, $args = array() ) {
echo '</a></li>';
}
}
Quick fix. Create whole structure tr > td > button; then find button inside; attach event on it; end filtering of chain and at the and insert it into dom.
$("#myButton").click(function () {
var test = $('<tr><td><button>Test</button></td></tr>').find('button').click(function () {
alert('hi');
}).end();
$("#nodeAttributeHeader").attr('style', 'display: table-row;');
$("#addNodeTable tr:last").before(test);
});
$order = new WC_Order( $post_id );
If you
echo $order->id;
then you'll be returned the id of the post from which the order is made. As you've already got that, it's probably not what you want.
echo $order->get_order_number();
will return the id of the order (with a # in front of it). To get rid of the #,
echo trim( str_replace( '#', '', $order->get_order_number() ) );
as per the accepted answer.
I don't really understand the full scope of your question, but if all you need is a hash of the string, then it's very easy to get that.
Just use the GetHashCode method.
Like this:
string hash = username.GetHashCode();
F12 opens the developer panel
CTRL + SHIFT + C Will open the hover-to-inspect tool where it highlights elements as you hover and you can click to show it in the elements tab.
CTRL + SHIFT + I Opens the developer panel with console tab
RIGHT-CLICK > Inspect Right click any element, and click "inspect" to select it in the Elements tab of the Developer panel.
ESC If you right-click and inspect element or similar and end up in the "Elements" tab looking at the DOM, you can press ESC to toggle the console up and down, which can be a nice way to use both.
JSON doesn't accept circular objects - objects which reference themselves. JSON.stringify()
will throw an error if it comes across one of these.
The request (req
) object is circular by nature - Node does that.
In this case, because you just need to log it to the console, you can use the console's native stringifying and avoid using JSON:
console.log("Request data:");
console.log(req);
I quite often use ajaxpro along with jQuery. ajaxpro lets me call .NET functions from JavaScript and I use jQuery for the rest.
This is deletes the table table_name
.
Replace it with the name of the table, which shall be deleted.
DELETE FROM table_name;
The system
function invokes a shell to run the command. While this is convenient, it has well known security implications. If you can fully specify the path to the program or script that you want to execute, and you can afford losing the platform independence that system
provides, then you can use an execve
wrapper as illustrated in the exec_prog
function below to more securely execute your program.
Here's how you specify the arguments in the caller:
const char *my_argv[64] = {"/foo/bar/baz" , "-foo" , "-bar" , NULL};
Then call the exec_prog
function like this:
int rc = exec_prog(my_argv);
Here's the exec_prog
function:
static int exec_prog(const char **argv)
{
pid_t my_pid;
int status, timeout /* unused ifdef WAIT_FOR_COMPLETION */;
if (0 == (my_pid = fork())) {
if (-1 == execve(argv[0], (char **)argv , NULL)) {
perror("child process execve failed [%m]");
return -1;
}
}
#ifdef WAIT_FOR_COMPLETION
timeout = 1000;
while (0 == waitpid(my_pid , &status , WNOHANG)) {
if ( --timeout < 0 ) {
perror("timeout");
return -1;
}
sleep(1);
}
printf("%s WEXITSTATUS %d WIFEXITED %d [status %d]\n",
argv[0], WEXITSTATUS(status), WIFEXITED(status), status);
if (1 != WIFEXITED(status) || 0 != WEXITSTATUS(status)) {
perror("%s failed, halt system");
return -1;
}
#endif
return 0;
}
Remember the includes:
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <stdio.h>
See related SE post for situations that require communication with the executed program via file descriptors such as stdin
and stdout
.
in my case, I was passing all the parameters but one of the parameter my code was passing a null value for string.
Eg: cmd.Parameters.AddWithValue("@userName", userName);
in the above case, if the data type of userName is string, I was passing userName as null.
Disconnected recordsets can be useful.
Const adVarChar = 200 'the SQL datatype is varchar
'Create a disconnected recordset
Set rs = CreateObject("ADODB.RECORDSET")
rs.Fields.append "SortField", adVarChar, 25
rs.CursorType = adOpenStatic
rs.Open
rs.AddNew "SortField", "Some data"
rs.Update
rs.AddNew "SortField", "All data"
rs.Update
rs.Sort = "SortField"
rs.MoveFirst
Do Until rs.EOF
strList=strList & vbCrLf & rs.Fields("SortField")
rs.MoveNext
Loop
MsgBox strList
I had this problem, then I did:
gem install bundle
notice "bundle" not "bundler" solved my problem.
then in your project folder do:
bundle install
and then you can run your project using:
script/rails server
DECLARE @INPUT VARCHAR(5) = '0.12',@INPUT_1 VARCHAR(5)='0.12x';
select CONVERT(float, @INPUT) YOUR_QUERY ,
case when isnumeric(@INPUT_1)=1 THEN CONVERT(float, @INPUT_1) ELSE 0 END AS YOUR_QUERY_ANSWERED
above will return values
however below query wont work
DECLARE @INPUT VARCHAR(5) = '0.12',@INPUT_1 VARCHAR(5)='0.12x';
select CONVERT(float, @INPUT) YOUR_QUERY ,
case when isnumeric(@INPUT_1)=1 THEN CONVERT(float, @INPUT_1) ELSE **@INPUT_1** END AS YOUR_QUERY_ANSWERED
as @INPUT_1 actually has varchar in it.
So your output column must have a varchar in it.
Those steps should be able to be shortened down to:
hg pull
hg update -r MY_BRANCH -C
The -C
flag tells the update command to discard all local changes before updating.
However, this might still leave untracked files in your repository. It sounds like you want to get rid of those as well, so I would use the purge
extension for that:
hg pull
hg update -r MY_BRANCH -C
hg purge
In any case, there is no single one command you can ask Mercurial to perform that will do everything you want here, except if you change the process to that "full clone" method that you say you can't do.
Remove the course_enrollment_settings.base_price
immediately after CASE
:
SELECT
CASE
WHEN course_enrollment_settings.base_price = 0 THEN 1
...
END
CASE
has two different forms, as detailed in the manual. Here, you want the second form since you're using search conditions.
I'm quite happy with my "make a weak pin storage program" solution. Maybe it will help people who need a very simple binary file IO example to follow.
$ ls
WeakPin my_pin_code.pin weak_pin.c
$ ./WeakPin
Pin: 45 47 49 32
$ ./WeakPin 8 2
$ Need 4 ints to write a new pin!
$./WeakPin 8 2 99 49
Pin saved.
$ ./WeakPin
Pin: 8 2 99 49
$
$ cat weak_pin.c
// a program to save and read 4-digit pin codes in binary format
#include <stdio.h>
#include <stdlib.h>
#define PIN_FILE "my_pin_code.pin"
typedef struct { unsigned short a, b, c, d; } PinCode;
int main(int argc, const char** argv)
{
if (argc > 1) // create pin
{
if (argc != 5)
{
printf("Need 4 ints to write a new pin!\n");
return -1;
}
unsigned short _a = atoi(argv[1]);
unsigned short _b = atoi(argv[2]);
unsigned short _c = atoi(argv[3]);
unsigned short _d = atoi(argv[4]);
PinCode pc;
pc.a = _a; pc.b = _b; pc.c = _c; pc.d = _d;
FILE *f = fopen(PIN_FILE, "wb"); // create and/or overwrite
if (!f)
{
printf("Error in creating file. Aborting.\n");
return -2;
}
// write one PinCode object pc to the file *f
fwrite(&pc, sizeof(PinCode), 1, f);
fclose(f);
printf("Pin saved.\n");
return 0;
}
// else read existing pin
FILE *f = fopen(PIN_FILE, "rb");
if (!f)
{
printf("Error in reading file. Abort.\n");
return -3;
}
PinCode pc;
fread(&pc, sizeof(PinCode), 1, f);
fclose(f);
printf("Pin: ");
printf("%hu ", pc.a);
printf("%hu ", pc.b);
printf("%hu ", pc.c);
printf("%hu\n", pc.d);
return 0;
}
$
Your item
variable holds Array
instance (in [hash_key, hash_value]
format), so it doesn't expect Symbol
in []
method.
This is how you could do it using Hash#each
:
def format(hash)
output = Hash.new
hash.each do |key, value|
output[key] = cleanup(value)
end
output
end
or, without this:
def format(hash)
output = hash.dup
output[:company_name] = cleanup(output[:company_name])
output[:street] = cleanup(output[:street])
output
end
ArrayList<Matrices> list = new ArrayList<Matrices>();
list.add( new Matrices(1,1,10) );
list.add( new Matrices(1,2,20) );
Note: You can use memset with any character.
Example:
int arr[20];
memset(arr, 'A', sizeof(arr));
Also could be partially filled
int arr[20];
memset(&arr[5], 0, 10);
But be carefull. It is not limited for the array size, you could easily cause severe damage to your program doing something like this:
int arr[20];
memset(arr, 0, 200);
It is going to work (under windows) and zero memory after your array. It might cause damage to other variables values.
As of API 21, you could also use:
ResourcesCompat.getDrawable(getResources(), R.drawable.name, null);
Instead of ContextCompat.getDrawable(context, android.R.drawable.ic_dialog_email)
Yes, let's use Select
as an example
sample code: Columns("A").select
How to loop through Columns:
Method 1: (You can use index to replace the Excel Address)
For i = 1 to 100
Columns(i).Select
next i
Method 2: (Using the address)
For i = 1 To 100
Columns(Columns(i).Address).Select
Next i
EDIT: Strip the Column for OP
columnString = Replace(Split(Columns(27).Address, ":")(0), "$", "")
e.g. you want to get the 27th Column --> AA, you can get it this way
In iOS10 instead of your code, you should request an authorization for notification with the following: (Don't forget to add the UserNotifications
Framework)
if #available(iOS 10.0, *) {
UNUserNotificationCenter.current().requestAuthorization([.alert, .sound, .badge]) { (granted: Bool, error: NSError?) in
// Do something here
}
}
Also, the correct code for you is (use in the else
of the previous condition, for example):
let setting = UIUserNotificationSettings(types: [.alert, .badge, .sound], categories: nil)
UIApplication.shared().registerUserNotificationSettings(setting)
UIApplication.shared().registerForRemoteNotifications()
Finally, make sure Push Notification
is activated under target
-> Capabilities
-> Push notification
. (set it on On
)
The files selected are stored in an array: [input].files
For example, you can access the items
// assuming there is a file input with the ID `my-input`...
var files = document.getElementById("my-input").files;
for (var i = 0; i < files.length; i++)
{
alert(files[i].name);
}
For jQuery-comfortable people, it's similarly easy
// assuming there is a file input with the ID `my-input`...
var files = $("#my-input")[0].files;
for (var i = 0; i < files.length; i++)
{
alert(files[i].name);
}
There is not an equivalent statement for export in Windows Command Prompt. In Windows the environment is copied so when you exit from the session (from a called command prompt or from an executable that set a variable) the variable in Windows get lost. You can set it in user registry or in machine registry via setx but you won't see it if you not start a new command prompt.
I always use the DisplayName
, Description
and DefaultValue
attributes over public properties of my user controls, custom controls or any class I'll edit through a property grid. These tags are used by the .NET PropertyGrid to format the name, the description panel, and bolds values that are not set to the default values.
[DisplayName("Error color")]
[Description("The color used on nodes containing errors.")]
[DefaultValue(Color.Red)]
public Color ErrorColor
{
...
}
I just wish Visual Studio's IntelliSense would take the Description
attribute into account if no XML comment are found. It would avoid having to repeat the same sentence twice.
In my Case, Adding the below functions to WebViewClient fixed the error.
the functions are:onReceivedSslError
and Depricated and new api versions of shouldOverrideUrlLoading
webView.setWebViewClient(new WebViewClient() {
@SuppressWarnings("deprecation")
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
Log.i(TAG, "loading: deprecation");
return true;
//return super.shouldOverrideUrlLoading(view, url);
}
@Override
@TargetApi(Build.VERSION_CODES.N)
public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) {
view.loadUrl(request.getUrl().toString());
Log.i(TAG, "loading: build.VERSION_CODES.N");
return true;
//return super.shouldOverrideUrlLoading(view, request);
}
@Override
public void onPageStarted(
WebView view, String url, Bitmap favicon) {
Log.i(TAG, "page started:"+url);
super.onPageStarted(view, url, favicon);
}
@Override
public void onPageFinished(WebView view, final String url) {
Log.i(TAG, "page finished:"+url);
}
@Override
public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError er) {
handler.proceed();
}
});
First off, RangeToHTML
. The script calls it like a method, but it isn't. It's a popular function by MVP Ron de Bruin. Coincidentally, that links points to the exact source of the script you posted, before those few lines got b?u?t?c?h?e?r?e?d? modified.
On with Range.SpecialCells. This method operates on a range and returns only those cells that match the given criteria. In your case, you seem to be only interested in the visible text cells. Importantly, it operates on a Range, not on HTML text.
For completeness sake, I'll post a working version of the script below. I'd certainly advise to disregard it and revisit the excellent original by Ron the Bruin.
Sub Mail_Selection_Range_Outlook_Body()
Dim rng As Range
Dim OutApp As Object
Dim OutMail As Object
Set rng = Nothing
' Only send the visible cells in the selection.
Set rng = Sheets("Sheet1").Range("D4:D12").SpecialCells(xlCellTypeVisible)
If rng Is Nothing Then
MsgBox "The selection is not a range or the sheet is protected. " & _
vbNewLine & "Please correct and try again.", vbOKOnly
Exit Sub
End If
With Application
.EnableEvents = False
.ScreenUpdating = False
End With
Set OutApp = CreateObject("Outlook.Application")
Set OutMail = OutApp.CreateItem(0)
With OutMail
.To = ThisWorkbook.Sheets("Sheet2").Range("C1").Value
.CC = ""
.BCC = ""
.Subject = "This is the Subject line"
.HTMLBody = RangetoHTML(rng)
' In place of the following statement, you can use ".Display" to
' display the e-mail message.
.Display
End With
On Error GoTo 0
With Application
.EnableEvents = True
.ScreenUpdating = True
End With
Set OutMail = Nothing
Set OutApp = Nothing
End Sub
Function RangetoHTML(rng As Range)
' By Ron de Bruin.
Dim fso As Object
Dim ts As Object
Dim TempFile As String
Dim TempWB As Workbook
TempFile = Environ$("temp") & "/" & Format(Now, "dd-mm-yy h-mm-ss") & ".htm"
'Copy the range and create a new workbook to past the data in
rng.Copy
Set TempWB = Workbooks.Add(1)
With TempWB.Sheets(1)
.Cells(1).PasteSpecial Paste:=8
.Cells(1).PasteSpecial xlPasteValues, , False, False
.Cells(1).PasteSpecial xlPasteFormats, , False, False
.Cells(1).Select
Application.CutCopyMode = False
On Error Resume Next
.DrawingObjects.Visible = True
.DrawingObjects.Delete
On Error GoTo 0
End With
'Publish the sheet to a htm file
With TempWB.PublishObjects.Add( _
SourceType:=xlSourceRange, _
Filename:=TempFile, _
Sheet:=TempWB.Sheets(1).Name, _
Source:=TempWB.Sheets(1).UsedRange.Address, _
HtmlType:=xlHtmlStatic)
.Publish (True)
End With
'Read all data from the htm file into RangetoHTML
Set fso = CreateObject("Scripting.FileSystemObject")
Set ts = fso.GetFile(TempFile).OpenAsTextStream(1, -2)
RangetoHTML = ts.ReadAll
ts.Close
RangetoHTML = Replace(RangetoHTML, "align=center x:publishsource=", _
"align=left x:publishsource=")
'Close TempWB
TempWB.Close savechanges:=False
'Delete the htm file we used in this function
Kill TempFile
Set ts = Nothing
Set fso = Nothing
Set TempWB = Nothing
End Function
Check out Awesome Print. Parse the JSON string into a Ruby Hash, then display it with ap
like so:
require "awesome_print"
require "json"
json = '{"holy": ["nested", "json"], "batman!": {"a": 1, "b": 2}}'
ap(JSON.parse(json))
With the above, you'll see:
{
"holy" => [
[0] "nested",
[1] "json"
],
"batman!" => {
"a" => 1,
"b" => 2
}
}
Awesome Print will also add some color that Stack Overflow won't show you.
This is your code
$q = $this -> db
-> select('id')
-> where('email', $email)
-> limit(1)
-> get('users');
Try this
$id = $q->result()[0]->id;
or this one, it's simpler
$id = $q->row()->id;
According to ISTQB those two are not comparable. Functional testing is not integration testing.
Unit test is one of tests level and functional testing is type of testing.
Basically:
The function of a system (or component) is 'what it does'. This is typically described in a requirements specification, a functional specification, or in use cases.
while
Component testing, also known as unit, module and program testing, searches for defects in, and verifies the functioning of software (e.g. modules, programs, objects, classes, etc.) that are separately testable.
According to ISTQB component/unit test can be functional or not-functional:
Component testing may include testing of functionality and specific non-functional characteristics such as resource-behavior (e.g. memory leaks), performance or robustness testing, as well as structural testing (e.g. decision coverage).
Quotes from Foundations of software testing - ISTQB certification
Problem with DIR is that it will return wrong answers.
If you are looking for DOC in a folder by using DIR *.DOC
it will also give you the DOCX. Searching for *.HTM
will also give the HTML and so on...
Use time
Let's say you have the initial dates as strings like these:
date1 = "31/12/2015"
date2 = "01/01/2016"
You can do the following:
newdate1 = time.strptime(date1, "%d/%m/%Y")
and newdate2 = time.strptime(date2, "%d/%m/%Y")
to convert them to python's date format. Then, the comparison is obvious:
newdate1 > newdate2
will return False
newdate1 < newdate2
will return True
I've updated @Cameron's answer to include some safety checks against Convert
typed lambda expressions:
PropertyInfo GetPropertyName<TSource, TProperty>(
Expression<Func<TSource, TProperty>> propertyLambda)
{
var body = propertyLambda.Body;
if (!(body is MemberExpression member)
&& !(body is UnaryExpression unary
&& (member = unary.Operand as MemberExpression) != null))
throw new ArgumentException($"Expression '{propertyLambda}' " +
"does not refer to a property.");
if (!(member.Member is PropertyInfo propInfo))
throw new ArgumentException($"Expression '{propertyLambda}' " +
"refers to a field, not a property.");
var type = typeof(TSource);
if (!propInfo.DeclaringType.GetTypeInfo().IsAssignableFrom(type.GetTypeInfo()))
throw new ArgumentException($"Expresion '{propertyLambda}' " +
"refers to a property that is not from type '{type}'.");
return propInfo;
}
The \s
metacharacter matches whitespace characters.
You should consider creating a timestamp from that date witk mktime()
eg:
$date = explode('/', $_POST['date']);
$time = mktime(0,0,0,$date[0],$date[1],$date[2]);
$mysqldate = date( 'Y-m-d H:i:s', $time );
Try below code
I will recommend to use error handler while using vlookup because error might occur when the lookup_value is not found.
Private Sub ComboBox1_Change()
On Error Resume Next
Ret = Application.WorksheetFunction.VLookup(Me.ComboBox1.Value, Worksheets("Sheet3").Range("Names"), 2, False)
On Error GoTo 0
If Ret <> "" Then MsgBox Ret
End Sub
OR
On Error Resume Next
Result = Application.VLookup(Me.ComboBox1.Value, Worksheets("Sheet3").Range("Names"), 2, False)
If Result = "Error 2042" Then
'nothing found
ElseIf cell <> Result Then
MsgBox cell.Value
End If
On Error GoTo 0
Does replacing a character in a String with a null character even work in Java?
No.
Would this be the culprit to the funky characters?
Quite likely.
Cameron MacFarland nailed it.
I'd like to add that the .NET 4.0 client profile will be included in Windows Update and future Windows releases. Expect most computers to have the client profile, not the full profile. Do not underestimate that fact if you're doing business-to-consumer (B2C) sales.
const tifOptions = [];
for (const [key, value] of Object.entries(tifs)) {
tifOptions.push(<option value={key} key={key}>{value}</option>);
}
return (
<select id="tif" name="tif" onChange={this.handleChange}>
{ tifOptions }
</select>
)
Array.prototype.unique = function () {
return [...new Set(this)]
}
then we can write:
const arr = [1, 5, 2, 2, 2, 3, 4, 3, 2, 1, 5]
const uniqueArr = arr.unique()
As Baptiste said, you need to specify the data argument at the geom level. Either
#df1 is the default dataset for all geoms
(plot1 <- ggplot(df1, aes(v, p)) +
geom_point() +
geom_step(data = df2)
)
or
#No default; data explicitly specified for each geom
(plot2 <- ggplot(NULL, aes(v, p)) +
geom_point(data = df1) +
geom_step(data = df2)
)
In Visual Studio, you can't just open a .cpp
file and expect it to run. You must create a project first, or open the .cpp in some existing project.
In your case, there is no project, so there is no project to build.
Go to File --> New --> Project --> Visual C++ --> Win32 Console Application
. You can uncheck "create a directory for solution". On the next page, be sure to check "Empty project".
Then, You can add .cpp
files you created outside the Visual Studio by right clicking in the Solution explorer
on folder icon "Source" and Add->Existing Item.
Obviously You can create new .cpp this way too (Add --> New). The .cpp file will be created in your project directory.
Then you can press ctrl+F5 to compile without debugging and can see output on console window.
I think Jake Archibald presented us some insights back in 2013 that might add even more positiveness to the topic:
https://www.html5rocks.com/en/tutorials/speed/script-loading/
The holy grail is having a set of scripts download immediately without blocking rendering and execute as soon as possible in the order they were added. Unfortunately HTML hates you and won’t let you do that.
(...)
The answer is actually in the HTML5 spec, although it’s hidden away at the bottom of the script-loading section. "The async IDL attribute controls whether the element will execute asynchronously or not. If the element's "force-async" flag is set, then, on getting, the async IDL attribute must return true, and on setting, the "force-async" flag must first be unset…".
(...)
Scripts that are dynamically created and added to the document are async by default, they don’t block rendering and execute as soon as they download, meaning they could come out in the wrong order. However, we can explicitly mark them as not async:
[
'//other-domain.com/1.js',
'2.js'
].forEach(function(src) {
var script = document.createElement('script');
script.src = src;
script.async = false;
document.head.appendChild(script);
});
This gives our scripts a mix of behaviour that can’t be achieved with plain HTML. By being explicitly not async, scripts are added to an execution queue, the same queue they’re added to in our first plain-HTML example. However, by being dynamically created, they’re executed outside of document parsing, so rendering isn’t blocked while they’re downloaded (don’t confuse not-async script loading with sync XHR, which is never a good thing).
The script above should be included inline in the head of pages, queueing script downloads as soon as possible without disrupting progressive rendering, and executes as soon as possible in the order you specified. “2.js” is free to download before “1.js”, but it won’t be executed until “1.js” has either successfully downloaded and executed, or fails to do either. Hurrah! async-download but ordered-execution!
Still, this might not be the fastest way to load scripts:
(...) With the example above the browser has to parse and execute script to discover which scripts to download. This hides your scripts from preload scanners. Browsers use these scanners to discover resources on pages you’re likely to visit next, or discover page resources while the parser is blocked by another resource.
We can add discoverability back in by putting this in the head of the document:
<link rel="subresource" href="//other-domain.com/1.js">
<link rel="subresource" href="2.js">
This tells the browser the page needs 1.js and 2.js. link[rel=subresource] is similar to link[rel=prefetch], but with different semantics. Unfortunately it’s currently only supported in Chrome, and you have to declare which scripts to load twice, once via link elements, and again in your script.
Correction: I originally stated these were picked up by the preload scanner, they're not, they're picked up by the regular parser. However, preload scanner could pick these up, it just doesn't yet, whereas scripts included by executable code can never be preloaded. Thanks to Yoav Weiss who corrected me in the comments.
The best solution (for python >= 3.4) when executing from any directory is:
from pathlib import Path
two_up = Path(__file__).resolve().parents[1]
You can get these data from RouteData of a ViewContext
ViewContext.RouteData.Values["controller"]
ViewContext.RouteData.Values["action"]
rules: {
cname: {
required: true,
minlength: 2
}
},
messages: {
cname: {
required: "<li>Please enter a name.</li>",
minlength: "<li>Your name is not long enough.</li>"
}
}
You can pass an Object as the parameter to your filter expression, as described in the API Reference. This object can selectively apply the properties you're interested in, like so:
<input ng-model="search.name">
<input ng-model="search.phone">
<input ng-model="search.secret">
<tr ng-repeat="user in users | filter:{name: search.name, phone: search.phone}">
Here's a Plunker
Heads up...this example works great with AngularJS 1.1.5, but not always as well in 1.0.7. In this example 1.0.7 will initialize with everything filtered out, then work when you start using the inputs. It behaves like the inputs have non-matching values in them, even though they start out blank. If you want to stay on stable releases, go ahead and try this out for your situation, but some scenarios may want to use @maxisam's solution until 1.2.0 is released.
You can use this
moment().format("DD/MM/YYYY");
However, this returns a date string in the specified format for today, not a moment date object. Doing the following will make it a moment date object in the format you want.
var someDateString = moment().format("DD/MM/YYYY");
var someDate = moment(someDateString, "DD/MM/YYYY");
You cannot use the static keyword with a class unless it is an inner class. A static inner class is a nested class which is a static member of the outer class. It can be accessed without instantiating the outer class, using other static members. Just like static members, a static nested class does not have access to the instance variables and methods of the outer class.
public class Outer {
static class Nested_Demo {
public void my_method() {
System.out.println("This is my nested class");
}
}
public static void main(String args[]) {
Outer.Nested_Demo nested = new Outer.Nested_Demo();
nested.my_method();
}
}
If the IUSR user is already specified in Authentication and you're still getting this issue, it could be that your Directory Listing isn't enabled. Be sure to check that. That was the case for me.
use getBoundingClientRect
if $el
is the actual DOM object:
var top = $el.getBoundingClientRect().top;
Fiddle will show that this will get the same value that jquery's offset top will give you
Edit: as mentioned in comments this does not account for scrolled content, below is the code that jQuery uses
https://github.com/jquery/jquery/blob/master/src/offset.js (5/13/2015)
offset: function( options ) {
//...
var docElem, win, rect, doc,
elem = this[ 0 ];
if ( !elem ) {
return;
}
rect = elem.getBoundingClientRect();
// Make sure element is not hidden (display: none) or disconnected
if ( rect.width || rect.height || elem.getClientRects().length ) {
doc = elem.ownerDocument;
win = getWindow( doc );
docElem = doc.documentElement;
return {
top: rect.top + win.pageYOffset - docElem.clientTop,
left: rect.left + win.pageXOffset - docElem.clientLeft
};
}
}
I have custom loading. Properties must be defined as:
key.0=value0
key.1=value1
...
Custom loading:
/** Return array from properties file. Array must be defined as "key.0=value0", "key.1=value1", ... */
public List<String> getSystemStringProperties(String key) {
// result list
List<String> result = new LinkedList<>();
// defining variable for assignment in loop condition part
String value;
// next value loading defined in condition part
for(int i = 0; (value = YOUR_PROPERTY_OBJECT.getProperty(key + "." + i)) != null; i++) {
result.add(value);
}
// return
return result;
}
First Check that is image exists? if yes then simply Call unlink(your file path) function to remove you file otherwise show message to the user.
if (file_exists($filePath))
{
unlink($filePath);
echo "File Successfully Delete.";
}
else
{
echo "File does not exists";
}
Without answering the question about how to create and inject Authentication objects, Spring Security 4.0 provides some welcome alternatives when it comes to testing. The @WithMockUser
annotation enables the developer to specify a mock user (with optional authorities, username, password and roles) in a neat way:
@Test
@WithMockUser(username = "admin", authorities = { "ADMIN", "USER" })
public void getMessageWithMockUserCustomAuthorities() {
String message = messageService.getMessage();
...
}
There is also the option to use @WithUserDetails
to emulate a UserDetails
returned from the UserDetailsService
, e.g.
@Test
@WithUserDetails("customUsername")
public void getMessageWithUserDetailsCustomUsername() {
String message = messageService.getMessage();
...
}
More details can be found in the @WithMockUser and the @WithUserDetails chapters in the Spring Security reference docs (from which the above examples were copied)
ipython
is an interactive shell built with python.
From the project website:
IPython provides a rich toolkit to help you make the most out of using Python, with:
- Powerful Python shells (terminal and Qt-based).
- A web-based notebook with the same core features but support for code, text, mathematical expressions, inline plots and other rich media.
- Support for interactive data visualization and use of GUI toolkits.
- Flexible, embeddable interpreters to load into your own projects.
- Easy to use, high performance tools for parallel computing.
Note that the first 2 lines tell you it helps you make the most of using Python. Thus, you don't need to alter your code, the IPython shell runs your python code just like the normal python shell does, only with more features.
I recommend reading the IPython tutorial to get a sense of what features you gain when using IPython.
After the same problem with "phantom lock" the only solution was:
1) Disconnect the Project Eclipse->Team->Disconnect (select option to delete .svn folder)
2) Than "reconnect" Eclipse->Team->SVN->Share Project. Ignore the warning about better do an checkout. After this all worked fine.
Cleanup and Restart was no solutions, also Scan Locks did not show anything.
This is the new suggested method.
WebRequest.GetSystemWebProxy();
I have found a npm package made with CoffeeScript that has a lot of incredible useful helpers for Handlebars. Take a look of the documentation in the following URL:
https://npmjs.org/package/handlebars-helpers
You can do a wget http://registry.npmjs.org/handlebars-helpers/-/handlebars-helpers-0.2.6.tgz
to download them and see the contents of the package.
You will be abled to do things like {{#is number 5}}
or {{formatDate date "%m/%d/%Y"}}
You can create a div with the exact same size as the image.
<div class="imageContainer">Some Text</div>
use the css background-image property to show the image
.imageContainer {
width:200px;
height:200px;
background-image: url(locationoftheimage);
}
note: this slichtly tampers the semantics of your document. If needed use javascript to inject the div in the place of a real image.
If the object was recently created, you can check the Schema Changes History report, within the SQL Server Management Studio, which "provides a history of all committed DDL statement executions within the Database recorded by the default trace":
You then can search for the create statements of the objects. Among all the information displayed, there is the login name of whom executed the DDL statement.
One way to order by positive integers, when they are stored as varchar
, is to order by the length first and then the value:
order by len(registration_no), registration_no
This is particularly useful when the column might contain non-numeric values.
Note: in some databases, the function to get the length of a string might be called length()
instead of len()
.
You don't need Jquery here! The simplest solution here is (based on the answer from charles):
<html>
<body onload="document.frm1.submit()">
<form action="http://www.google.com" name="frm1">
<input type="hidden" name="q" value="Hello world" />
</form>
</body>
</html>
Strings are immutable in Java.
You can use the redirect() function. Like this
class ControllerA extends CI_Controller{
public function MethodA(){
redirect("ControllerB/MethodB");
}
}
From the ansible docs: If a required variable has not been set, you can skip or fail using Jinja2’s defined test. For example:
tasks:
- shell: echo "I've got '{{ foo }}' and am not afraid to use it!"
when: foo is defined
- fail: msg="Bailing out. this play requires 'bar'"
when: bar is not defined
So in your case, when: deployed_revision is not defined
should work
@Craig:
A semaphore is a way to lock a resource so that it is guaranteed that while a piece of code is executed, only this piece of code has access to that resource. This keeps two threads from concurrently accesing a resource, which can cause problems.
This is not restricted to only one thread. A semaphore can be configured to allow a fixed number of threads to access a resource.
TL;DR:
print(yourstring.encode('ascii','replace'));
I ran into this myself, working on a Twitch chat (IRC) bot. (Python 2.7 latest)
I wanted to parse chat messages in order to respond...
msg = s.recv(1024).decode("utf-8")
but also print them safely to the console in a human-readable format:
print(msg.encode('ascii','replace'));
This corrected the issue of the bot throwing UnicodeEncodeError: 'charmap'
errors and replaced the unicode characters with ?
.
I prefer
l.at(4)= -1;
while [4] is your index
How about this?
https://maps.google.com/?q=1200 Pennsylvania Ave SE, Washington, District of Columbia, 20003
https://maps.google.com/?q=term
If you have lat-long then use below URL
https://maps.google.com/?ll=latitude,longitude
Example: maps.google.com/?ll=38.882147,-76.99017
UPDATE
As of year 2017, Google now has an official way to create cross-platform Google Maps URLs:
https://developers.google.com/maps/documentation/urls/guide
You can use links like
https://www.google.com/maps/search/?api=1&query=1200%20Pennsylvania%20Ave%20SE%2C%20Washington%2C%20District%20of%20Columbia%2C%2020003
It becomes clearer with some explanation of how the two values work.
The margin property is shorthand for:
margin-top
margin-right
margin-bottom
margin-left
So how come only two values?
Well, you can express margin with four values like this:
margin: 10px, 20px, 15px, 5px;
which would mean 10px top, 20px right, 15px bottom, 5px left
Likewise you can also express with two values like this:
margin: 20px 10px;
This would give you a margin 20px top and bottom and 10px left and right.
And if you set:
margin: 20px auto;
Then that means top and bottom margin of 20px and left and right margin of auto. And auto means that the left/right margin are automatically set based on the container. If your element is a block type element, meaning it is a box and takes up the entire width of the view, then auto sets the left and right margin the same and hence the element is centered.
This question has been answered already, but thought I'd add to the mix what I found out when I got these messages.
I have a repo called playground
that contains a number of sandbox apps. I added two new apps from a tutorial to the playground
directory by cloning the tutorial's repo. The result was that the new apps' git stuff pointed to the tutorial's repo and not to my repo. The solution was to delete the .git
directory from each of those apps' directories, mv
the apps' directories outside the playground
directory, and then mv
them back and run git add .
. After that it worked.
If you guys still interested, here is my workaround based on Guzzle middleware feature:
Create JsonAwaraResponse
that will decode JSON response by Content-Type
HTTP header, if not - it will act as standard Guzzle Response:
<?php
namespace GuzzleHttp\Psr7;
class JsonAwareResponse extends Response
{
/**
* Cache for performance
* @var array
*/
private $json;
public function getBody()
{
if ($this->json) {
return $this->json;
}
// get parent Body stream
$body = parent::getBody();
// if JSON HTTP header detected - then decode
if (false !== strpos($this->getHeaderLine('Content-Type'), 'application/json')) {
return $this->json = \json_decode($body, true);
}
return $body;
}
}
Create Middleware which going to replace Guzzle PSR-7 responses with above Response implementation:
<?php
$client = new \GuzzleHttp\Client();
/** @var HandlerStack $handler */
$handler = $client->getConfig('handler');
$handler->push(\GuzzleHttp\Middleware::mapResponse(function (\Psr\Http\Message\ResponseInterface $response) {
return new \GuzzleHttp\Psr7\JsonAwareResponse(
$response->getStatusCode(),
$response->getHeaders(),
$response->getBody(),
$response->getProtocolVersion(),
$response->getReasonPhrase()
);
}), 'json_decode_middleware');
After this to retrieve JSON as PHP native array use Guzzle as always:
$jsonArray = $client->get('http://httpbin.org/headers')->getBody();
Tested with guzzlehttp/guzzle 6.3.3
What you are looking for is called reverse geocoding. Google provides a server-side reverse geocoding service through the Google Geocoding API, which you should be able to use for your project.
This is how a response to the following request would look like:
http://maps.googleapis.com/maps/api/geocode/json?latlng=40.714224,-73.961452&sensor=false
Response:
{
"status": "OK",
"results": [ {
"types": [ "street_address" ],
"formatted_address": "275-291 Bedford Ave, Brooklyn, NY 11211, USA",
"address_components": [ {
"long_name": "275-291",
"short_name": "275-291",
"types": [ "street_number" ]
}, {
"long_name": "Bedford Ave",
"short_name": "Bedford Ave",
"types": [ "route" ]
}, {
"long_name": "New York",
"short_name": "New York",
"types": [ "locality", "political" ]
}, {
"long_name": "Brooklyn",
"short_name": "Brooklyn",
"types": [ "administrative_area_level_3", "political" ]
}, {
"long_name": "Kings",
"short_name": "Kings",
"types": [ "administrative_area_level_2", "political" ]
}, {
"long_name": "New York",
"short_name": "NY",
"types": [ "administrative_area_level_1", "political" ]
}, {
"long_name": "United States",
"short_name": "US",
"types": [ "country", "political" ]
}, {
"long_name": "11211",
"short_name": "11211",
"types": [ "postal_code" ]
} ],
"geometry": {
"location": {
"lat": 40.7142298,
"lng": -73.9614669
},
"location_type": "RANGE_INTERPOLATED",
"viewport": {
"southwest": {
"lat": 40.7110822,
"lng": -73.9646145
},
"northeast": {
"lat": 40.7173774,
"lng": -73.9583193
}
}
}
},
... Additional results[] ...
You can also opt to receive the response in xml instead of json, by simply substituting json for xml in the request URI:
http://maps.googleapis.com/maps/api/geocode/xml?latlng=40.714224,-73.961452&sensor=false
As far as I know, Google will also return the same name for address components, especially for high-level names like country names and city names. Nevertheless, keep in mind that while the results are very accurate for most applications, you could still find the occasional spelling mistake or ambiguous result.
Here is my example of launching bar/QR code scanner from my app if someone finds it useful
Intent intent = new Intent("com.google.zxing.client.android.SCAN");
intent.setPackage("com.google.zxing.client.android");
try
{
startActivityForResult(intent, SCAN_REQUEST_CODE);
}
catch (ActivityNotFoundException e)
{
//implement prompt dialog asking user to download the package
AlertDialog.Builder downloadDialog = new AlertDialog.Builder(this);
downloadDialog.setTitle(stringTitle);
downloadDialog.setMessage(stringMessage);
downloadDialog.setPositiveButton("yes",
new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialogInterface, int i)
{
Uri uri = Uri.parse("market://search?q=pname:com.google.zxing.client.android");
Intent intent = new Intent(Intent.ACTION_VIEW, uri);
try
{
myActivity.this.startActivity(intent);
}
catch (ActivityNotFoundException e)
{
Dialogs.this.showAlert("ERROR", "Google Play Market not found!");
}
}
});
downloadDialog.setNegativeButton("no",
new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog, int i)
{
dialog.dismiss();
}
});
downloadDialog.show();
}
This is a function we are using in our application and it is working fine.
delete cookie: No argument method
function clearListCookies()
{
var cookies = document.cookie.split(";");
for (var i = 0; i < cookies.length; i++)
{
var spcook = cookies[i].split("=");
deleteCookie(spcook[0]);
}
function deleteCookie(cookiename)
{
var d = new Date();
d.setDate(d.getDate() - 1);
var expires = ";expires="+d;
var name=cookiename;
//alert(name);
var value="";
document.cookie = name + "=" + value + expires + "; path=/acc/html";
}
window.location = ""; // TO REFRESH THE PAGE
}
Edit: This will delete the cookie by setting it to yesterday's date.
From here:
One way to conserve system resources is to configure idle time-out settings for the worker processes in an application pool. When these settings are configured, a worker process will shut down after a specified period of inactivity. The default value for idle time-out is 20 minutes.
Also check Why is the IIS default app pool recycle set to 1740 minutes?
If you have a just a few sites on your server and you want them to always load fast then set this to zero. Otherwise, when you have 20 minutes without any traffic then the app pool will terminate so that it can start up again on the next visit. The problem is that the first visit to an app pool needs to create a new w3wp.exe worker process which is slow because the app pool needs to be created, ASP.NET or another framework needs to be loaded, and then your application needs to be loaded. That can take a few seconds. Therefore I set that to 0 every chance I have, unless it’s for a server that hosts a lot of sites that don’t always need to be running.
If you wanna add dynamic width and height based on your device frame, you can do these calculations and assign the height and width.
AlertDialog.Builder builderSingle = new
AlertDialog.Builder(getActivity());
builderSingle.setTitle("Title");
final AlertDialog alertDialog = builderSingle.create();
alertDialog.show();
Rect displayRectangle = new Rect();
Window window = getActivity().getWindow();
window.getDecorView().getWindowVisibleDisplayFrame(displayRectangle);
alertDialog.getWindow().setLayout((int)(displayRectangle.width() *
0.8f), (int)(displayRectangle.height() * 0.8f));
P.S : Show the dialog first and then try to modify the window's layout attributes
Remember, Objective-C is a superset of C, so typecasting works as it does in C:
myEditController = [[SelectionListViewController alloc] init];
((SelectionListViewController *)myEditController).list = listOfItems;
Your E
class doesn't have a member of type struct X
, you've just defined a nested struct X
in there (i.e. you've defined a new type).
Try:
#include <iostream>
class E
{
public:
struct X { int v; };
X x; // an instance of `struct X`
};
int main(){
E object;
object.x.v = 1;
return 0;
}
Preamble
below may work or may not, this is all given as-is, you and only you are responsible person in case of some damage, data loss and so on. But I hope things go smooth!
To undo make install
I would do (and I did) this:
Idea: check whatever script installs and undo this with simple bash script.
--prefix=$PWD/install
. For CMake, you can go to your build dir, open CMakeCache.txt, and fix CMAKE_INSTALL_PREFIX value.make install
again).make install
script installs into custom dir just same contents you want to remove from somewhere else (usually /usr/local
). So, we need a script.
3.1. Script should compare custom dir, with dir you want clean. I use this:anti-install.sh
RM_DIR=$1
PRESENT_DIR=$2
echo "Remove files from $RM_DIR, which are present in $PRESENT_DIR"
pushd $RM_DIR
for fn in `find . -iname '*'`; do
# echo "Checking $PRESENT_DIR/$fn..."
if test -f "$PRESENT_DIR/$fn"; then
# First try this, and check whether things go plain
echo "rm $RM_DIR/$fn"
# Then uncomment this, (but, check twice it works good to you).
# rm $RM_DIR/$fn
fi
done
popd
3.2. Now just run this script (it will go dry-run)
bash anti-install.sh <dir you want to clean> <custom installation dir>
E.g. You wan't to clean /usr/local, and your custom installation dir is /user/me/llvm.build/install, then it would be
bash anti-install.sh /usr/local /user/me/llvm.build/install
3.3. Check log carefully, if commands are good to you, uncomment rm $RM_DIR/$fn
and run it again. But stop! Did you really check carefully? May be check again?
Source to instructions: https://dyatkovskiy.com/2019/11/26/anti-make-install/
Good luck!
Going with what you've started:
row = [[]]
crimefile = open(fileName, 'r')
for line in crimefile.readlines():
tmp = []
for element in line[0:-1].split(','):
tmp.append(element)
row.append(tmp)
A COUNT query is faster, although maybe not noticeably, but as far as getting the desired result, both should be sufficient.
You can also do the following:
CREATE TABLE #TEMPTABLE
(
Column1 type1,
Column2 type2,
Column3 type3
)
INSERT INTO #TEMPTABLE
SELECT ...
SELECT *
FROM #TEMPTABLE ...
DROP TABLE #TEMPTABLE
With Java 8 you can do this without any third party library.
If you want to join a Collection of Strings you can use the new String.join() method:
List<String> list = Arrays.asList("foo", "bar", "baz");
String joined = String.join(" and ", list); // "foo and bar and baz"
If you have a Collection with another type than String you can use the Stream API with the joining Collector:
List<Person> list = Arrays.asList(
new Person("John", "Smith"),
new Person("Anna", "Martinez"),
new Person("Paul", "Watson ")
);
String joinedFirstNames = list.stream()
.map(Person::getFirstName)
.collect(Collectors.joining(", ")); // "John, Anna, Paul"
The StringJoiner
class may also be useful.
Try
System.getProperty("user.dir")
It returns the current working directory.
For floating point numbers there is a standard (IEEE754): floats are 32 bit and doubles are 64. This is a hardware standard, not a C++ standard, so compilers could theoretically define float and double to some other size, but in practice I've never seen an architecture that used anything different.
boolean compare(String str1, String str2) {
if(str1==null || str2==null) {
//return false; if you assume null not equal to null
return str1==str2;
}
return str1.equals(str2);
}
is this what you desired?
For my case, I used to have branch folder (or whatever it is called) with capital letters, then I create a new one with difference casing (lowercase) but git actually create the branch with capital.
I have created a branch like feature-ABC/branch1
before and pushed it. Then I create a branch feature-abc/branch2
(notice the lower-case ABC), and try to push it to remote using git push --set-upstream origin feature-abc/branch2
and get the 'cannot be resolved to branch' error. So I git branch
and see that it actually created feature-ABC/branch2
instead of feature-abc/branch1
for me. I checkout again with git checkout feature-ABC/feature2
and push it using the uppercase (feature-ABC/feature2
) to solve it.
.class {_x000D_
display: none;_x000D_
}_x000D_
@media (min-width:400px) and (max-width:900px) {_x000D_
.class {_x000D_
display: block; /* just an example display property */_x000D_
}_x000D_
}
_x000D_
Use @Column
annotation and define its length
attribute. Check Hibernate's documentation for references (section 2.2.2.3).
In C++, the size of int
isn't specified explicitly. It just tells you that it must be at least the size of short int
, which must be at least as large as signed char
. The size of char
in bits isn't specified explicitly either, although sizeof(char) is defined to be 1. If you want a 64 bit int, C++11 specifies long long
to be at least 64 bits.
http://sourceforge.net/projects/xampp/files/
The old version, but the desired function will be sufficient.
Uninstall version 5.6.11 and downgrade to version 5.6.8.
This worked for me. Add sudo before python
curl https://bootstrap.pypa.io/get-pip.py |sudo python
RewriteBase is only useful in situations where you can only put a .htaccess at the root of your site. Otherwise, you may be better off placing your different .htaccess files in different directories of your site and completely omitting the RewriteBase directive.
Lately, for complex sites, I've been taking them out, because it makes deploying files from testing to live just one more step complicated.
You can use the overloaded constructor of DateTime
:
DateTime utcDateTime = new DateTime(dateTime.Year, dateTime.Month, dateTime.Day, dateTime.Hour, dateTime.Minute, dateTime.Second, DateTimeKind.Utc);
mysqli_fetch_assoc() expects parameter 1 to be mysqli_result, boolean given
This means that the first parameter you passed is a boolean (true or false).
The first parameter is $result
, and it is false
because there is a syntax error in the query.
" ... WHERE PartNumber = $partid';"
You should never directly include a request variable in a SQL query, else the users are able to inject SQL in your queries. (See SQL injection.)
You should escape the variable:
" ... WHERE PartNumber = '" . mysqli_escape_string($conn,$partid) . "';"
Or better, use Prepared Statements
.
I am surprised nobody used flex
which is easier to understand, so I put my version of answer here:
width
equals height
font-size
of number in the circle, use em
rather than px
justify-content: center; align-items: center;
width
and height
at same timeHere is an example:
.circled-number {
color: #666;
border: 2px solid #666;
border-radius: 50%;
font-size: 1rem;
display: flex;
justify-content: center;
align-items: center;
width: 2em;
height: 2em;
}
.circled-number--big {
color: #666;
border: 2px solid #666;
border-radius: 50%;
font-size: 1rem;
display: flex;
justify-content: center;
align-items: center;
width: 4em;
height: 4em;
}
_x000D_
<div class="circled-number">
30
</div>
<div class="circled-number--big">
3000000
</div>
_x000D_
<object>.__class__.__name__
Of course you can, just use setTimeout
to change a class or something to trigger the transition.
HTML:
<p id="aap">OHAI!</p>
CSS:
p {
opacity:1;
transition:opacity 500ms;
}
p.waa {
opacity:0;
}
JS to run on load or DOMContentReady:
setTimeout(function(){
document.getElementById('aap').className = 'waa';
}, 5000);
I found an easy way to fetch the details of Tables and columns of a particular DB using SQL developer.
Select *FROM USER_TAB_COLUMNS
The other answer didn't work for me (on Windows 7). But this worked:
telnet localhost 5554
kill
For linux/unix OS, you can use the shell syntax
const shell = require('child_process').execSync ;
const currentPath= `/path/to/name.png`;
const newPath= `/path/to/another_name.png`;
shell(`mv ${currentPath} ${newPath}`);
That's it!
You need to either convert each table individually:
ALTER TABLE mytable CONVERT TO CHARACTER SET utf8mb4
(this will convert the columns just as well), or export the database with latin1
and import it back with utf8mb4
.
The first example doesn't work because you can't assign values to arrays - arrays work (sort of) like const pointers in this respect. What you can do though is copy a new value into the array:
strcpy(p.name, "Jane");
Char arrays are fine to use if you know the maximum size of the string in advance, e.g. in the first example you are 100% sure that the name will fit into 19 characters (not 20 because one character is always needed to store the terminating zero value).
Conversely, pointers are better if you don't know the possible maximum size of your string, and/or you want to optimize your memory usage, e.g. avoid reserving 512 characters for the name "John". However, with pointers you need to dynamically allocate the buffer they point to, and free it when not needed anymore, to avoid memory leaks.
Update: example of dynamically allocated buffers (using the struct definition in your 2nd example):
char* firstName = "Johnnie";
char* surname = "B. Goode";
person p;
p.name = malloc(strlen(firstName) + 1);
p.surname = malloc(strlen(surname) + 1);
p.age = 25;
strcpy(p.name, firstName);
strcpy(p.surname, surname);
printf("Name: %s; Age: %d\n",p.name,p.age);
free(p.surname);
free(p.name);
In my case it happened when adding a new application to IIS that needed to be proxied with Apache.
I needed to set ProxyHTMLEnable On
to ProxyHTMLEnable Off
to get the content. (It looks like some js code most have triggered the error, but this gave me at least something to work from.)
IIS is sending the page content Content-Encoding: gzip
<Proxy "http://192.168.1.1:81">
ProxyHTMLEnable On #> change this to Off
ProxyHTMLURLMap ... ...
</Proxy>
I got this error when I was playing around while reading progit. I made a local repository, then fetched it in another repo on the same file system, made an edit and tried to push. After reading NowhereMan's answer, a quick fix was to go to the "remote" directory and temporarily checkout another commit, push from the directory I made changes in, then go back and put the head back on master.
In my case I accidentally wrote:
app:displayViewTitle="@string/instructions_defineExtract_confirm_email"
Interestingly, Android Studio were able to navigate the string via CTRL+click. It was just giving Build Time error. Changing to standard "dot seperation" did the trick
app:displayViewTitle="@string/instructions.defineExtract.confirm.email"
Try changing from windows authentication to mixed mode
In command line, you can use
spark-shell -i file.scala
to run code which is written in file.scala
Setup a DocumentListener on nameField. When nameField is updated, update your label.
http://download.oracle.com/javase/1.5.0/docs/api/javax/swing/JTextField.html
Parameters starting with -
or --
are usually considered optional. All other parameters are positional parameters and as such required by design (like positional function arguments). It is possible to require optional arguments, but this is a bit against their design. Since they are still part of the non-positional arguments, they will still be listed under the confusing header “optional arguments” even if they are required. The missing square brackets in the usage part however show that they are indeed required.
See also the documentation:
In general, the argparse module assumes that flags like -f and --bar indicate optional arguments, which can always be omitted at the command line.
Note: Required options are generally considered bad form because users expect options to be optional, and thus they should be avoided when possible.
That being said, the headers “positional arguments” and “optional arguments” in the help are generated by two argument groups in which the arguments are automatically separated into. Now, you could “hack into it” and change the name of the optional ones, but a far more elegant solution would be to create another group for “required named arguments” (or whatever you want to call them):
parser = argparse.ArgumentParser(description='Foo')
parser.add_argument('-o', '--output', help='Output file name', default='stdout')
requiredNamed = parser.add_argument_group('required named arguments')
requiredNamed.add_argument('-i', '--input', help='Input file name', required=True)
parser.parse_args(['-h'])
usage: [-h] [-o OUTPUT] -i INPUT
Foo
optional arguments:
-h, --help show this help message and exit
-o OUTPUT, --output OUTPUT
Output file name
required named arguments:
-i INPUT, --input INPUT
Input file name
Dictionaries do not have any inherent order. Or, rather, their inherent order is "arbitrary but not random", so it doesn't do you any good.
In different terms, your d
and your e
would be exactly equivalent dictionaries.
What you can do here is to use an OrderedDict
:
from collections import OrderedDict
d = { '123': { 'key1': 3, 'key2': 11, 'key3': 3 },
'124': { 'key1': 6, 'key2': 56, 'key3': 6 },
'125': { 'key1': 7, 'key2': 44, 'key3': 9 },
}
d_ascending = OrderedDict(sorted(d.items(), key=lambda kv: kv[1]['key3']))
d_descending = OrderedDict(sorted(d.items(),
key=lambda kv: kv[1]['key3'], reverse=True))
The original d
has some arbitrary order. d_ascending
has the order you thought you had in your original d
, but didn't. And d_descending
has the order you want for your e
.
If you don't really need to use e
as a dictionary, but you just want to be able to iterate over the elements of d
in a particular order, you can simplify this:
for key, value in sorted(d.items(), key=lambda kv: kv[1]['key3'], reverse=True):
do_something_with(key, value)
If you want to maintain a dictionary in sorted order across any changes, instead of an OrderedDict
, you want some kind of sorted dictionary. There are a number of options available that you can find on PyPI, some implemented on top of trees, others on top of an OrderedDict
that re-sorts itself as necessary, etc.
Use also this way to represent image in base64 encode format...
find PHP function file_get_content
and next to use function base64_encode
and get result to prepare str as data:" . file_mime_type . " base64_encoded string
. Use it in img src attribute. see following code can I help for you.
// A few settings
$img_file = 'raju.jpg';
// Read image path, convert to base64 encoding
$imgData = base64_encode(file_get_contents($img_file));
// Format the image SRC: data:{mime};base64,{data};
$src = 'data: '.mime_content_type($img_file).';base64,'.$imgData;
// Echo out a sample image
echo '<img src="'.$src.'">';
You can use the bootstrap grid system. as Yoann said
<div class="container">
<div class="row">
<form role="form">
<div class="form-group col-xs-10 col-sm-4 col-md-4 col-lg-4">
<label for="exampleInputEmail1">Email address</label>
<input type="email" class="form-control" id="exampleInputEmail1" placeholder="Enter email">
</div>
<div class="form-group col-xs-10 col-sm-4 col-md-4 col-lg-4">
<label for="exampleInputEmail1">Name</label>
<input type="text" class="form-control" id="exampleInputEmail1" placeholder="Enter Name">
</div>
<div class="clearfix"></div>
<div class="form-group col-xs-10 col-sm-4 col-md-4 col-lg-4">
<label for="exampleInputPassword1">Password</label>
<input type="password" class="form-control" id="exampleInputPassword1" placeholder="Password">
</div>
<div class="form-group col-xs-10 col-sm-4 col-md-4 col-lg-4">
<label for="exampleInputPassword1">Confirm Password</label>
<input type="password" class="form-control" id="exampleInputPassword1" placeholder="Confirm Password">
</div>
</form>
<div class="clearfix">
</div>
</div>
</div>
00 23 * * * [[ $(date +'%d') -eq $(cal | awk '!/^$/{ print $NF }' | tail -1) ]] && job
Check out a related question on the unix.com forum.
Move the queue to self instead of as an argument to your functions package
and send
May be the problem is with your python-opencv
version. It's better to downgrade your version to 3.3.0.9 which does not include any GUI dependencies. Same question was found on GitHub here the link to the answer.
U can try this JS code.. https://snack.expo.io/r1v0LwZFb
import React, { Component } from 'react';
import { View } from 'react-native';
export default class App extends Component {
render() {
const gradientHeight=500;
const gradientBackground = 'purple';
const data = Array.from({ length: gradientHeight });
return (
<View style={{flex:1}}>
{data.map((_, i) => (
<View
key={i}
style={{
position: 'absolute',
backgroundColor: gradientBackground,
height: 1,
bottom: (gradientHeight - i),
right: 0,
left: 0,
zIndex: 2,
opacity: (1 / gradientHeight) * (i + 1)
}}
/>
))}
</View>
);
}
}
With JavaScript it is very difficult if not impossible(?). I would suggest using some sort of code-behind language such as PHP, C#, or Java. If you were to use PHP, you could, in the page your button posts to, do something like this:
<?php
header('Content-type: application/pdf');
header('Content-disposition: attachment; filename=filename.pdf');
readfile("http://manuals.info.apple.com/en/iphone_user_guide.pdf");
?>
This also seems to work for JS (from http://www.phpbuilder.com/board/showthread.php?t=10149735):
<body>
<script>
function downloadme(x){
myTempWindow = window.open(x,'','left=10000,screenX=10000');
myTempWindow.document.execCommand('SaveAs','null','download.pdf');
myTempWindow.close();
}
</script>
<a href=javascript:downloadme('http://manuals.info.apple.com/en/iphone_user_guide.pdf');>Download this pdf</a>
</body>
You need to include your pipe in module declaration:
declarations: [ UsersPipe ],
providers: [UsersPipe]
Follow this code to sort any ArrayList
Collections.sort(myList, new Comparator<EmployeeClass>(){
public int compare(EmployeeClass obj1, EmployeeClass obj2) {
// ## Ascending order
return obj1.firstName.compareToIgnoreCase(obj2.firstName); // To compare string values
// return Integer.valueOf(obj1.empId).compareTo(Integer.valueOf(obj2.empId)); // To compare integer values
// ## Descending order
// return obj2.firstName.compareToIgnoreCase(obj1.firstName); // To compare string values
// return Integer.valueOf(obj2.empId).compareTo(Integer.valueOf(obj1.empId)); // To compare integer values
}
});
A simplified shortcut I've tried is this:
int x[] = {1,2,3};
String printableText = Arrays.toString(x).replaceAll("[\\[\\]]", "").replaceAll(", ", "\n");
System.out.println(printableText);
It will print
1
2
3
No loops required in this approach and it is best for small arrays only
Find timestamp from DateTime:
private long ConvertToTimestamp(DateTime value)
{
TimeZoneInfo NYTimeZone = TimeZoneInfo.FindSystemTimeZoneById("Eastern Standard Time");
DateTime NyTime = TimeZoneInfo.ConvertTime(value, NYTimeZone);
TimeZone localZone = TimeZone.CurrentTimeZone;
System.Globalization.DaylightTime dst = localZone.GetDaylightChanges(NyTime.Year);
NyTime = NyTime.AddHours(-1);
DateTime epoch = new DateTime(1970, 1, 1, 0, 0, 0, 0).ToLocalTime();
TimeSpan span = (NyTime - epoch);
return (long)Convert.ToDouble(span.TotalSeconds);
}
I use an alpha-transparent PNG for that:
div.semi-transparent {
background: url('semi-transparent.png');
}
Just add $locationProvider
In
.config(function ($routeProvider,$locationProvider)
and then add $locationProvider.hashPrefix('');
after
.otherwise({
redirectTo: '/'
});
That's it.
You can also use the CSS calc() function to subtract the width of your padding from the percentage of your container's width.
An example:
width: calc((100%) - (32px))
Just be sure to make the subtracted width equal to the total padding, not just one half. If you pad both sides of the inner div with 16px, then you should subtract 32px from the final width, assuming that the example below is what you want to achieve.
.outer {_x000D_
width: 200px;_x000D_
height: 120px;_x000D_
background-color: black;_x000D_
}_x000D_
_x000D_
.inner {_x000D_
height: 40px;_x000D_
top: 30px;_x000D_
position: relative;_x000D_
padding: 16px;_x000D_
background-color: teal;_x000D_
}_x000D_
_x000D_
#inner-1 {_x000D_
width: 100%;_x000D_
}_x000D_
_x000D_
#inner-2 {_x000D_
width: calc((100%) - (32px));_x000D_
}
_x000D_
<div class="outer" id="outer-1">_x000D_
<div class="inner" id="inner-1"> width of 100% </div>_x000D_
</div>_x000D_
_x000D_
<br>_x000D_
<br>_x000D_
_x000D_
<div class="outer" id="outer-2">_x000D_
<div class="inner" id="inner-2"> width of 100% - 16px </div>_x000D_
</div>
_x000D_
Go to :xampp\mysql\data\dbname
inside dbname have tablename.frm and tablename.ibd file.
remove it
and restart mysql and try again.
This works for me
Now the key point, choose MacIntosh as File Origin (it should be the first choice).
This is using Excel 2011 (version 14.4.2)
*There's a little dropdown at the bottom of the window
Converting from java.lang.Object
directly to ArrayList<T>
which has elements of T is not recommended as it can lead to casting Exceptions. The recommended way is to first convert to a primitive array of T
and then use Arrays.asList(T[])
One of the ways how you get entity from a java javax.ws.rs.core.Response
is as follows -
T[] t_array = response.readEntity(object);
ArrayList<T> t_arraylist = Arrays.asList(t_array);
You will still get Unchecked cast warnings.
% mysql --user=root mysql
CREATE USER 'monty'@'localhost' IDENTIFIED BY 'some_pass';
GRANT ALL PRIVILEGES ON *.* TO 'monty'@'localhost' WITH GRANT OPTION;
CREATE USER 'monty'@'%' IDENTIFIED BY 'some_pass';
GRANT ALL PRIVILEGES ON *.* TO 'monty'@'%' WITH GRANT OPTION;
CREATE USER 'admin'@'localhost';
GRANT RELOAD,PROCESS ON *.* TO 'admin'@'localhost';
CREATE USER 'dummy'@'localhost';
FLUSH PRIVILEGES;
Databases are heavily optimized for common usage scenarios (and LIKE is one of those).
You won't find a faster way of doing your search if you want to stay on the DB-level.
When you use the IntelliJ IDE, all the project-specific settings for the project are stored under the .idea
folder.
Project settings are stored with each specific project as a set of xml files under the .idea folder. If you specify the default project settings, these settings will be automatically used for each newly created project.
Check this documentation for the IDE settings and here is their recommendation on Source Control and an example .gitignore file.
Note: If you are using git or some version control system, you might want to set this folder "ignore".
Example - for git, add this directory to .gitignore
. This way, the application is not IDE-specific.
As I read your question, I have tried without success to search on the Internet how Bearer tokens are encrypted or signed. I guess bearer tokens are not hashed (maybe partially, but not completely) because in that case, it will not be possible to decrypt it and retrieve users properties from it.
But your question seems to be trying to find answers on Bearer token functionality:
Suppose I am implementing an authorization provider, can I supply any kind of string for the bearer token? Can it be a random string? Does it has to be a base64 encoding of some attributes? Should it be hashed?
So, I'll try to explain how Bearer tokens and Refresh tokens work:
When user requests to the server for a token sending user and password through SSL, the server returns two things: an Access token and a Refresh token.
An Access token is a Bearer token that you will have to add in all request headers to be authenticated as a concrete user.
Authorization: Bearer <access_token>
An Access token is an encrypted string with all User properties, Claims and Roles that you wish. (You can check that the size of a token increases if you add more roles or claims). Once the Resource Server receives an access token, it will be able to decrypt it and read these user properties. This way, the user will be validated and granted along with all the application.
Access tokens have a short expiration (ie. 30 minutes). If access tokens had a long expiration it would be a problem, because theoretically there is no possibility to revoke it. So imagine a user with a role="Admin" that changes to "User". If a user keeps the old token with role="Admin" he will be able to access till the token expiration with Admin rights. That's why access tokens have a short expiration.
But, one issue comes in mind. If an access token has short expiration, we have to send every short period the user and password. Is this secure? No, it isn't. We should avoid it. That's when Refresh tokens appear to solve this problem.
Refresh tokens are stored in DB and will have long expiration (example: 1 month).
A user can get a new Access token (when it expires, every 30 minutes for example) using a refresh token, that the user had received in the first request for a token. When an access token expires, the client must send a refresh token. If this refresh token exists in DB, the server will return to the client a new access token and another refresh token (and will replace the old refresh token by the new one).
In case a user Access token has been compromised, the refresh token of that user must be deleted from DB. This way the token will be valid only till the access token expires because when the hacker tries to get a new access token sending the refresh token, this action will be denied.
When you use setcookie
, you can either set the expiration time to 0
or simply omit the parametre - the cookie will then expire at the end of session (ie, when you close the browser).
When you’re faced with a problem to solve (and frankly, who isn’t these days?), the basic strategy usually taken by we computer people is called “divide and conquer.” It goes like this:
- Conceptualize the specific problem as a set of smaller sub-problems.
- Solve each smaller problem.
- Combine the results into a solution of the specific problem.
But “divide and conquer” is not the only possible strategy. We can also take a more generalist approach:
- Conceptualize the specific problem as a special case of a more general problem.
- Somehow solve the general problem.
- Adapt the solution of the general problem to the specific problem.
- Eric Lippert
I believe many solutions already exist for this problem in server-side languages such as ASP.Net/C#.
I've outlined some of the major aspects of the problem
Issue: We need to load data only for the desired language
Solution: For this purpose we save data to a separate files for each language
ex. res.de.js, res.fr.js, res.en.js, res.js(for default language)
Issue: Resource files for each page should be separated so we only get the data we need
Solution: We can use some tools that already exist like https://github.com/rgrove/lazyload
Issue: We need a key/value pair structure to save our data
Solution: I suggest a javascript object instead of string/string air. We can benefit from the intellisense from an IDE
Issue: General members should be stored in a public file and all pages should access them
Solution: For this purpose I make a folder in the root of web application called Global_Resources and a folder to store global file for each sub folders we named it 'Local_Resources'
Issue: Each subsystems/subfolders/modules member should override the Global_Resources members on their scope
Solution: I considered a file for each
Application Structure
root/ Global_Resources/ default.js default.fr.js UserManagementSystem/ Local_Resources/ default.js default.fr.js createUser.js Login.htm CreateUser.htm
The corresponding code for the files:
Global_Resources/default.js
var res = {
Create : "Create",
Update : "Save Changes",
Delete : "Delete"
};
Global_Resources/default.fr.js
var res = {
Create : "créer",
Update : "Enregistrer les modifications",
Delete : "effacer"
};
The resource file for the desired language should be loaded on the page selected from Global_Resource - This should be the first file that is loaded on all the pages.
UserManagementSystem/Local_Resources/default.js
res.Name = "Name";
res.UserName = "UserName";
res.Password = "Password";
UserManagementSystem/Local_Resources/default.fr.js
res.Name = "nom";
res.UserName = "Nom d'utilisateur";
res.Password = "Mot de passe";
UserManagementSystem/Local_Resources/createUser.js
// Override res.Create on Global_Resources/default.js
res.Create = "Create User";
UserManagementSystem/Local_Resources/createUser.fr.js
// Override Global_Resources/default.fr.js
res.Create = "Créer un utilisateur";
manager.js file (this file should be load last)
res.lang = "fr";
var globalResourcePath = "Global_Resources";
var resourceFiles = [];
var currentFile = globalResourcePath + "\\default" + res.lang + ".js" ;
if(!IsFileExist(currentFile))
currentFile = globalResourcePath + "\\default.js" ;
if(!IsFileExist(currentFile)) throw new Exception("File Not Found");
resourceFiles.push(currentFile);
// Push parent folder on folder into folder
foreach(var folder in parent folder of current page)
{
currentFile = folder + "\\Local_Resource\\default." + res.lang + ".js";
if(!IsExist(currentFile))
currentFile = folder + "\\Local_Resource\\default.js";
if(!IsExist(currentFile)) throw new Exception("File Not Found");
resourceFiles.push(currentFile);
}
for(int i = 0; i < resourceFiles.length; i++) { Load.js(resourceFiles[i]); }
// Get current page name
var pageNameWithoutExtension = "SomePage";
currentFile = currentPageFolderPath + pageNameWithoutExtension + res.lang + ".js" ;
if(!IsExist(currentFile))
currentFile = currentPageFolderPath + pageNameWithoutExtension + ".js" ;
if(!IsExist(currentFile)) throw new Exception("File Not Found");
Hope it helps :)
Python:
Latitude: result = re.match("^[+-]?((90\.?0*$)|(([0-8]?[0-9])\.?[0-9]*$))", '-90.00001')
Longitude: result = re.match("^[+-]?((180\.?0*$)|(((1[0-7][0-9])|([0-9]{0,2}))\.?[0-9]*$))", '-0.0000')
Latitude should fail in the example.
The code that worked for me on a Windows 10 machine using Sublime Text 3
{
"cmd" : "gcc $file_name -o ${file_base_name}",
"selector" : "source.c",
"shell" : true,
"working_dir" : "$file_path",
"variants":
[
{
"name": "Run",
"cmd": "${file_base_name}"
}
]
}
Be aware of an issue with sparse unique indexes in MongoDB. I've hit it and it is extremely cumbersome to workaround.
The problem is this - you have a field, which is unique if present and you wish to find all the objects where the field is absent. The way sparse unique indexes are implemented in Mongo is that objects where that field is missing are not in the index at all - they cannot be retrieved by a query on that field - {$exists: false}
just does not work.
The only workaround I have come up with is having a special null family of values, where an empty value is translated to a special prefix (like null:) concatenated to a uuid. This is a real headache, because one has to take care of transforming to/from the empty values when writing/quering/reading. A major nuisance.
I have never used server side javascript execution in MongoDB (it is not advised anyway) and their map/reduce has awful performance when there is just one Mongo node. Because of all these reasons I am now considering to check out CouchDB, maybe it fits more to my particular scenario.
BTW, if anyone knows the link to the respective Mongo issue describing the sparse unique index problem - please share.
You can try c#
public string ProcessMyDataItem(object myValue)
{
if (myValue == null)
{
return "0 %"";
}
else
{
if(Convert.ToInt32(myValue) < 50)
return "0";
else
return myValue.ToString() + "%";
}
}
asp
<div class="tooltip" style="display: none">
<div style="text-align: center; font-weight: normal">
Value =<%# ProcessMyDataItem(Eval("Percentage")) %> </div>
</div>
Another way around it that may/may not suit but surely the simplest:
td {
display: table-caption;
}
I am guessing there is a fundamental reason for the change, it isn't merely cosmetic to make the old interpretation clearer: that reason is concurrency. Unspecified order of elaboration is merely selection of one of several possible serial orderings, this is quite different to before and after orderings, because if there is no specified ordering, concurrent evaluation is possible: not so with the old rules. For example in:
f (a,b)
previously either a then b, or, b then a. Now, a and b can be evaluated with instructions interleaved or even on different cores.
from FOLDER_NAME import FILENAME
from FILENAME import CLASS_NAME FUNCTION_NAME
FILENAME is w/o the suffix
Delete the following files from the directory:
\wamp\bin\mysql\mysql5.6.17\ib_logfile0
\wamp\bin\mysql\mysql5.6.17\ib_logfile1
\wamp\bin\mysql\mysql5.6.17\ibdata1
This solved my problem.
What would be wrong with doing;
<div className="" key={index}>
{i.title}
</div>
[/*Use IIFE */]
{(function () {
if (child.children && child.children.length !== 0) {
let menu = createMenu(child.children);
console.log("nested menu", menu);
return menu;
}
})()}
Try below one:
svn copy http://svn.example.com/repos/calc/trunk@rev-no
http://svn.example.com/repos/calc/branches/my-calc-branch
-m "Creating a private branch of /calc/trunk." --parents
No slash "\" between the svn URLs.