I tried the accepted solution of using the Invoke-Expression cmdlet but it didn't work for me because my arguments had spaces on them. I tried to parse the arguments and escape the spaces but I couldn't properly make it work and also it was really a dirty work around in my opinion. So after some experimenting, my take on the problem is this:
function Invoke-Script
{
param
(
[Parameter(Mandatory = $true)]
[string]
$Script,
[Parameter(Mandatory = $false)]
[object[]]
$ArgumentList
)
$ScriptBlock = [Scriptblock]::Create((Get-Content $Script -Raw))
Invoke-Command -NoNewScope -ArgumentList $ArgumentList -ScriptBlock $ScriptBlock -Verbose
}
# example usage
Invoke-Script $scriptPath $argumentList
The only drawback of this solution is that you need to make sure that your script doesn't have a "Script" or "ArgumentList" parameter.
This simple trick works: Copy and Paste. Do NOT cut and paste. After you paste, then reselect the part you copied and go to EDIT, slide down to CLEAR, and CLEAR CONTENTS.
A complementary note about CREATE TABLE .. TYPE=""
syntax in SQL dump files
TLDR: If you still get CREATE TABLE ... TYPE="..."
statements in SQL dump files generated by third party tools, it most certainly indicates that your server is configured to use a default sqlmode
of MYSQL40
or MYSQL323
.
Long story
As it was said by others, the TYPE
argument to CREATE TABLE
has been deprecated for a long time in MySQL. mysqldump
correctly uses the ENGINE
argument, unless you specifically ask it to generate a backward compatible dump (for example using --compatible=mysql40
in versions of mysqldump
up to 5.7).
However, many external SQL dump tools (for example, those integrated in MySQL clients such as phpmyadmin, Navicat and DBVisualizer, as well as those used by external automated backup services such as iControlWP) are not specifically aware of this change, and instead rely on the SHOW CREATE TABLE ...
command to provide table creation statements for each tables (and just to it make it clear: this is actually a good thing). However, the SHOW CREATE TABLE
will actually produce outdated syntax, including the TYPE
argument, if the sqlmode
variable is set to MYSQL40
or MYSQL323
.
Therefore, if you still get CREATE TABLE ... TYPE="..."
statements in SQL dump files generated by third party tools, it most certainly indicates that your server is configured to use a default sqlmode
of MYSQL40
or MYSQL323
.
These sqlmode
s basically configure MySQL to retain some backward compatible behaviours, and using them by default was largely recommended a few years ago. It is however highly improbable that you still have any code that wouldn't work correctly without these modes. Anyway, MYSQL40
, MYSQL323
and several other similar sqlmode
s have themselves been deprecated and are not supported in MySQL 8.0 and higher.
If your server is still configured with these sqlmode
s and you are worried that some legacy program might fail if you change these, then one possibility is to set the sqlmode
locally for that program, by executing SET SESSION sql_mode = 'MYSQL40';
immediately after connection. Note that this should only be considered as a temporary patch, and will not work in MySQL 8.0 and higher.
A more future-proof solution that do not involve rewriting your SQL queries would be to determine exactly which compatibility features need to be enable, and to enable only those, on a per-program basis (as described previously). The default sqlmode
(that is, in server's configuration) should ideally be left unset (which will use official MySQL defaults for your current version). The full list of sqlmode
(as of MySQL 5.7) is described here: https://dev.mysql.com/doc/refman/5.7/en/sql-mode.html.
As clarified in your comment, Spacemoses, you stated an example: WHERE (Note is null) ^ (ID is null). I do not see why you chose to accept any answer given here as answering that. If i needed an xor for that, i think i'd have to use the AND/OR equivalent logic:
WHERE (Note is null and ID is not null) OR (Note is not null and ID is null)
That is equivalent to:
WHERE (Note is null) XOR (ID is null)
when 'XOR' is not available.
The SublimeText 3 Column-Select plugin should be all you need. Install that, then make sure you have something like the following in your 'Default (OSX).sublime-keymap' file:
// Column mode
{ "keys": ["ctrl+alt+up"], "command": "column_select", "args": {"by": "lines", "forward": false}},
{ "keys": ["ctrl+alt+down"], "command": "column_select", "args": {"by": "lines", "forward": true}},
{ "keys": ["ctrl+alt+pageup"], "command": "column_select", "args": {"by": "pages", "forward": false}},
{ "keys": ["ctrl+alt+pagedown"], "command": "column_select", "args": {"by": "pages", "forward": true}},
{ "keys": ["ctrl+alt+home"], "command": "column_select", "args": {"by": "all", "forward": false}},
{ "keys": ["ctrl+alt+end"], "command": "column_select", "args": {"by": "all", "forward": true}}
What exactly about it did not work for you?
For exiting app ways:
Way 1 :
call finish();
and override onDestroy();
. Put the following code in onDestroy()
:
System.runFinalizersOnExit(true)
or
android.os.Process.killProcess(android.os.Process.myPid());
Way 2 :
public void quit() {
int pid = android.os.Process.myPid();
android.os.Process.killProcess(pid);
System.exit(0);
}
Way 3 :
Quit();
protected void Quit() {
super.finish();
}
Way 4 :
Intent intent = new Intent(getApplicationContext(), LoginActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
intent.putExtra("EXIT", true);
startActivity(intent);
if (getIntent().getBooleanExtra("EXIT", false)) {
finish();
}
Way 5 :
Sometimes calling finish()
will only exit the current activity, not the entire application. However, there is a workaround for this. Every time you start an activity
, start it using startActivityForResult()
. When you want to close the entire app, you can do something like the following:
setResult(RESULT_CLOSE_ALL);
finish();
Then define every activity's onActivityResult(...)
callback so when an activity
returns with the RESULT_CLOSE_ALL
value, it also calls finish()
:
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
switch(resultCode){
case RESULT_CLOSE_ALL:{
setResult(RESULT_CLOSE_ALL);
finish();
}
}
super.onActivityResult(requestCode, resultCode, data);
}
This is a very late response, but adds some detail on the previous answers
When it comes to calling static methods in PHP from another static method on the same class, it is important to differentiate between self
and the class name.
Take for instance this code:
class static_test_class {
public static function test() {
echo "Original class\n";
}
public static function run($use_self) {
if($use_self) {
self::test();
} else {
$class = get_called_class();
$class::test();
}
}
}
class extended_static_test_class extends static_test_class {
public static function test() {
echo "Extended class\n";
}
}
extended_static_test_class::run(true);
extended_static_test_class::run(false);
The output of this code is:
Original class
Extended class
This is because self
refers to the class the code is in, rather than the class of the code it is being called from.
If you want to use a method defined on a class which inherits the original class, you need to use something like:
$class = get_called_class();
$class::function_name();
You need the DateUtils: see this article for details.
Or, better yet, use Andy Khan's JExcel instead of POI.
The max length of a string on my machine is 1,073,741,791.
You see, Strings aren't limited by integer as is commonly believed.
Memory restrictions aside, Strings cannot have more than 230 (1,073,741,824) characters, since a 2GB limit is imposed by the Microsoft CLR (Common Language Runtime). 33 more than my computer allowed.
Now, here's something you're welcome to try yourself.
Create a new C# console app in Visual Studio and then copy/paste the main method here:
static void Main(string[] args)
{
Console.WriteLine("String test, by Nicholas John Joseph Taylor");
Console.WriteLine("\nTheoretically, C# should support a string of int.MaxValue, but we run out of memory before then.");
Console.WriteLine("\nThis is a quickish test to narrow down results to find the max supported length of a string.");
Console.WriteLine("\nThe test starts ...now:\n");
int Length = 0;
string s = "";
int Increment = 1000000000; // We know that s string with the length of 1000000000 causes an out of memory exception.
LoopPoint:
// Make a string appendage the length of the value of Increment
StringBuilder StringAppendage = new StringBuilder();
for (int CharacterPosition = 0; CharacterPosition < Increment; CharacterPosition++)
{
StringAppendage.Append("0");
}
// Repeatedly append string appendage until an out of memory exception is thrown.
try
{
if (Increment > 0)
while (Length < int.MaxValue)
{
Length += Increment;
s += StringAppendage.ToString(); // Append string appendage the length of the value of Increment
Console.WriteLine("s.Length = " + s.Length + " at " + DateTime.Now.ToString("dd/MM/yyyy HH:mm"));
}
}
catch (OutOfMemoryException ex) // Note: Any other exception will crash the program.
{
Console.WriteLine("\n" + ex.Message + " at " + DateTime.Now.ToString("dd/MM/yyyy HH:mm") + ".");
Length -= Increment;
Increment /= 10;
Console.WriteLine("After decimation, the value of Increment is " + Increment + ".");
}
catch (Exception ex2)
{
Console.WriteLine("\n" + ex2.Message + " at " + DateTime.Now.ToString("dd/MM/yyyy HH:mm") + ".");
Console.WriteLine("Press a key to continue...");
Console.ReadKey();
}
if (Increment > 0)
{
goto LoopPoint;
}
Console.WriteLine("Test complete.");
Console.WriteLine("\nThe max length of a string is " + s.Length + ".");
Console.WriteLine("\nPress any key to continue.");
Console.ReadKey();
}
My results were as follows:
String test, by Nicholas John Joseph Taylor
Theoretically, C# should support a string of int.MaxValue, but we run out of memory before then.
This is a quickish test to narrow down results to find the max supported length of a string.
The test starts ...now:
s.Length = 1000000000 at 08/05/2019 12:06
Exception of type 'System.OutOfMemoryException' was thrown. at 08/05/2019 12:06. After decimation, the value of Increment is 100000000.
Exception of type 'System.OutOfMemoryException' was thrown. at 08/05/2019 12:06. After decimation, the value of Increment is 10000000. s.Length = 1010000000 at 08/05/2019 12:06 s.Length = 1020000000 at 08/05/2019 12:06 s.Length = 1030000000 at 08/05/2019 12:06 s.Length = 1040000000 at 08/05/2019 12:06 s.Length = 1050000000 at 08/05/2019 12:06 s.Length = 1060000000 at 08/05/2019 12:06 s.Length = 1070000000 at 08/05/2019 12:06
Exception of type 'System.OutOfMemoryException' was thrown. at 08/05/2019 12:06. After decimation, the value of Increment is 1000000. s.Length = 1071000000 at 08/05/2019 12:06 s.Length = 1072000000 at 08/05/2019 12:06 s.Length = 1073000000 at 08/05/2019 12:06
Exception of type 'System.OutOfMemoryException' was thrown. at 08/05/2019 12:06. After decimation, the value of Increment is 100000. s.Length = 1073100000 at 08/05/2019 12:06 s.Length = 1073200000 at 08/05/2019 12:06 s.Length = 1073300000 at 08/05/2019 12:06 s.Length = 1073400000 at 08/05/2019 12:06 s.Length = 1073500000 at 08/05/2019 12:06 s.Length = 1073600000 at 08/05/2019 12:06 s.Length = 1073700000 at 08/05/2019 12:06
Exception of type 'System.OutOfMemoryException' was thrown. at 08/05/2019 12:06. After decimation, the value of Increment is 10000. s.Length = 1073710000 at 08/05/2019 12:06 s.Length = 1073720000 at 08/05/2019 12:06 s.Length = 1073730000 at 08/05/2019 12:06 s.Length = 1073740000 at 08/05/2019 12:06
Exception of type 'System.OutOfMemoryException' was thrown. at 08/05/2019 12:06. After decimation, the value of Increment is 1000. s.Length = 1073741000 at 08/05/2019 12:06
Exception of type 'System.OutOfMemoryException' was thrown. at 08/05/2019 12:06. After decimation, the value of Increment is 100. s.Length = 1073741100 at 08/05/2019 12:06 s.Length = 1073741200 at 08/05/2019 12:06 s.Length = 1073741300 at 08/05/2019 12:07 s.Length = 1073741400 at 08/05/2019 12:07 s.Length = 1073741500 at 08/05/2019 12:07 s.Length = 1073741600 at 08/05/2019 12:07 s.Length = 1073741700 at 08/05/2019 12:07
Exception of type 'System.OutOfMemoryException' was thrown. at 08/05/2019 12:07. After decimation, the value of Increment is 10. s.Length = 1073741710 at 08/05/2019 12:07 s.Length = 1073741720 at 08/05/2019 12:07 s.Length = 1073741730 at 08/05/2019 12:07 s.Length = 1073741740 at 08/05/2019 12:07 s.Length = 1073741750 at 08/05/2019 12:07 s.Length = 1073741760 at 08/05/2019 12:07 s.Length = 1073741770 at 08/05/2019 12:07 s.Length = 1073741780 at 08/05/2019 12:07 s.Length = 1073741790 at 08/05/2019 12:07
Exception of type 'System.OutOfMemoryException' was thrown. at 08/05/2019 12:07. After decimation, the value of Increment is 1. s.Length = 1073741791 at 08/05/2019 12:07
Exception of type 'System.OutOfMemoryException' was thrown. at 08/05/2019 12:07. After decimation, the value of Increment is 0. Test complete.
The max length of a string is 1073741791.
Press any key to continue.
The max length of a string on my machine is 1073741791.
I'd appreciate it very much if people could post their results as a comment below.
It will be interesting to learn if people get the same or different results.
A more general answer would be to import java.util.Date
, then when you need to set a timestamp
equal to the current date, simply set it equal to new Date()
.
You can add capitalize functionality run time as:
<td>{{lastName.charAt(0).toUpperCase()+ lastName.substr(1).toLowerCase()}}</td>
In responsive.less, you can comment out the line that imports responsive-1200px-min.less.
// Large desktops
@import "responsive-1200px-min.less";
Like so:
// Large desktops
// @import "responsive-1200px-min.less";
This is how managed to change my data table row background (DataTables 1.10.19)
$('#memberList').DataTable({
"processing": true,
"serverSide": true,
"pageLength":25,
"ajax":{
"dataType": "json",
"type": "POST",
"url": mainUrl+"/getMember",
},
"columns": [
{ "data": "id" },
{ "data": "name" },
{ "data": "email" },
{ "data": "phone" },
{ "data": "country_id" },
{ "data": "created_at" },
{ "data": "action" },
],
"fnRowCallback": function( nRow, aData, iDisplayIndex, iDisplayIndexFull ) {
switch(aData['country_id']){
case 1:
$('td', nRow).css('background-color', '#dacfcf')
break;
}
}
});
You can use fnRowCallback
method function to change the background.
There are a couple of things you can't do with a primitive type:
null
valueObject
sUnless you need any of those, you should prefer primitive types, since they require less memory.
Set it in the JAVA_OPTS
variable in [path to tomcat]/bin/catalina.sh. Under windows there is a console where you can set it up or you use the catalina.bat.
JAVA_OPTS=-agentpath:C:\calltracer\jvmti\calltracer5.dll=traceFile-C:\calltracer\call.trace,filterFile-C:\calltracer\filters.txt,outputType-xml,usage-uncontrolled -Djava.library.path=C:\calltracer\jvmti -Dcalltracerlib=calltracer5
I had this for MapActivity. Builds in Eclipse gets NoClassDefFound in debugger.
Forgot to add library to manifest, inside <Application>...</Application>
element
<uses-library android:name="com.google.android.maps" />
You should take decodeURI
for it.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/decodeURI
As simple as this:
decodeURI('https://developer.mozilla.org/ru/docs/JavaScript_%D1%88%D0%B5%D0%BB%D0%BB%D1%8B');
// "https://developer.mozilla.org/ru/docs/JavaScript_?????"
Consider to use it inside try catch
block for not missing an URIError
.
Also it has full browsers support.
From the docs:
Modals have two optional sizes, available via modifier classes to be placed on a .modal-dialog
: modal-lg
and modal-sm
(as of 3.1).
Also the modal dialogue will scale itself on small screens (as of 3.1.1).
You can find your created database, named <your-database-name>
in
//data/data/<Your-Application-Package-Name>/databases/<your-database-name>
Pull it out using File explorer and rename it to have .db3 extension to use it in SQLiteExplorer
Use File explorer of DDMS to navigate to emulator directory.
Also, it's probably useful to note that if you have a multiple dimensional Array, you can get the respective dimension just by appending a '[0]' to the array you are querying until you arrive at the appropriate axis/tuple/dimension.
This is probably better explained with the following code:
public class Test {
public static void main(String[] args){
String[][] moo = new String[5][12];
System.out.println(moo.length); //Prints the size of the First Dimension in the array
System.out.println(moo[0].length);//Prints the size of the Second Dimension in the array
}
}
Which produces the output:
5
12
This seems unnecessary, but VBA is a strange place. If you declare an array variable, then set it using Array()
then pass the variable into your function, VBA will be happy.
Sub test()
Dim fString As String
Dim arr() As Variant
arr = Array("foo", "bar")
fString = processArr(arr)
End Sub
Also your function processArr()
could be written as:
Function processArr(arr() As Variant) As String
processArr = Replace(Join(arr()), " ", "")
End Function
If you are into the whole brevity thing.
$(document).ready(my_function);
Or
$(document).ready(function () {
// Function code here.
});
Or the shorter but less readable variant:
$(my_function);
All of these will cause my_function to be called after the DOM loads.
See the ready event documentation for more details.
Binds a function to be executed whenever the DOM is ready to be traversed and manipulated.
Edit:
To simulate a click, use the click() method without arguments:
$('#button').click();
From the docs:
Triggers the click event of each matched element. Causes all of the functions that have been bound to that click event to be executed.
To put it all together, the following code simulates a click when the document finishes loading:
$(function () {
$('#button').click();
});
git pull
is nothing but git fetch
followed by git merge
. So what you can do is
git fetch remote example_branch
git merge <commit_hash>
def map = [:]
map["stringKey"] = [1, 2, 3, 4]
map["anotherKey"] = [55, 66, 77]
assert map["anotherKey"] == [55, 66, 77]
For your question as asked
Columns(3).Insert
Range("c1:c4") = Application.Transpose(Array("Loc", "uk", "us", "nj"))
If you had a way of automatically looking up the data (ie matching uk against employer id) then you could do that in VBA
The Java runtime you try to execute your program with is an earlier version than Java 7 which was the target you compile your program for.
For Ubuntu use
apt-get install openjdk-7-jdk
to get Java 7 as default. You may have to uninstall openjdk-6 first.
My few cents on the subject. Assuming that kubectl
is working then the closest command that would be equivalent to the docker command that you mentioned in your question, would be something like this.
$ kubectl run ubuntu --image=ubuntu --restart=Never --command sleep infinity
Above command will create a single Pod
in default
namespace and, it will execute sleep
command with infinity
argument -this way you will have a process that runs in foreground keeping container alive.
Afterwords, you can interact with Pod
by running kubectl exec
command.
$ kubectl exec ubuntu -it -- bash
This technique is very useful for creating a Pod resource and ad-hoc debugging.
For EXAMPLE
Your Path = /home/serverID_name/www/your_route_Dir/
THIS_is_the_DIR_I_Want
A Soultion that WORKS:
$url = dirname(\__FILE__);
$array = explode('\\\',$url);
$count = count($array);
echo $array[$count-1];
Use the following:
echo (text here) >> (name here).txt
Ex. echo my name is jeff >> test.txt
test.txt
my name is jeff
You can use it in a script too.
You need to use the fn:contains()
or fn:containsIgnoreCase()
function.
<%@ taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions"%>
...
<c:if test="${not fn:containsIgnoreCase(mylist, 'apple')}">
<p>Doesn't contain 'apple'</p>
</c:if>
or
<c:if test="${not fn:contains(mylist, 'Apple')}">
<p>Contains 'Apple'</p>
</c:if>
Note:
This will work like mylist.toString().contains("apple")
and if this is not what you are looking for better use a other approach.
I too was looking for some way to interact with SQLite the same way I was used to doing previously in Objective-C. Admittedly, because of C compatibility, I just used the straight C API.
As no wrapper currently exists for SQLite in Swift and the SQLiteDB code mentioned above goes a bit higher level and assumes certain usage, I decided to create a wrapper and get a bit familiar with Swift in the process. You can find it here: https://github.com/chrismsimpson/SwiftSQLite.
var db = SQLiteDatabase();
db.open("/path/to/database.sqlite");
var statement = SQLiteStatement(database: db);
if ( statement.prepare("SELECT * FROM tableName WHERE Id = ?") != .Ok )
{
/* handle error */
}
statement.bindInt(1, value: 123);
if ( statement.step() == .Row )
{
/* do something with statement */
var id:Int = statement.getIntAt(0)
var stringValue:String? = statement.getStringAt(1)
var boolValue:Bool = statement.getBoolAt(2)
var dateValue:NSDate? = statement.getDateAt(3)
}
statement.finalizeStatement(); /* not called finalize() due to destructor/language keyword */
I just found a simple and reliable solution if you are using the system UI approach (https://developer.android.com/training/system-ui/immersive.html).
It works in the case when you are using View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
, e.g. if you are using CoordinatorLayout
.
It won't work for WindowManager.LayoutParams.FLAG_FULLSCREEN
(The one you can also set in theme with android:windowFullscreen
), but you can achieve similar effect with SYSTEM_UI_FLAG_LAYOUT_STABLE
(which "has the same visual effect" according to the docs) and this solution should work again.
getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN
| View.SYSTEM_UI_FLAG_HIDE_NAVIGATION /* If you want to hide navigation */
| View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_STABLE)
I've tested it on my device running Marshmallow.
The key is that soft keyboards are also one of the system windows (such as status bar and navigation bar), so the WindowInsets
dispatched by system contains accurate and reliable information about it.
For the use case such as in DrawerLayout
where we are trying to draw behind the status bar, We can create a layout that ignores only the top inset, and applies the bottom inset which accounts for the soft keyboard.
Here is my custom FrameLayout
:
/**
* Implements an effect similar to {@code android:fitsSystemWindows="true"} on Lollipop or higher,
* except ignoring the top system window inset. {@code android:fitsSystemWindows="true"} does not
* and should not be set on this layout.
*/
public class FitsSystemWindowsExceptTopFrameLayout extends FrameLayout {
public FitsSystemWindowsExceptTopFrameLayout(Context context) {
super(context);
}
public FitsSystemWindowsExceptTopFrameLayout(Context context, AttributeSet attrs) {
super(context, attrs);
}
public FitsSystemWindowsExceptTopFrameLayout(Context context, AttributeSet attrs,
int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
@RequiresApi(Build.VERSION_CODES.LOLLIPOP)
public FitsSystemWindowsExceptTopFrameLayout(Context context, AttributeSet attrs,
int defStyleAttr, int defStyleRes) {
super(context, attrs, defStyleAttr, defStyleRes);
}
@Override
public WindowInsets onApplyWindowInsets(WindowInsets insets) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
setPadding(insets.getSystemWindowInsetLeft(), 0, insets.getSystemWindowInsetRight(),
insets.getSystemWindowInsetBottom());
return insets.replaceSystemWindowInsets(0, insets.getSystemWindowInsetTop(), 0, 0);
} else {
return super.onApplyWindowInsets(insets);
}
}
}
And to use it:
<com.example.yourapplication.FitsSystemWindowsExceptTopFrameLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<!-- Your original layout here -->
</com.example.yourapplication.FitsSystemWindowsExceptTopFrameLayout>
This should theoretically work for any device without insane modification, much better than any hack that tries to take a random 1/3
or 1/4
of screen size as reference.
(It requires API 16+, but I'm using fullscreen only on Lollipop+ for drawing behind the status bar so it's the best solution in this case.)
Shorter explanation:
In C++, struct and class were just two sides of the same coin. The only real difference is that one was public by default and the other was private.
In .NET, there is a much greater difference between a struct and a class. The main thing is that struct provides value-type semantics, while class provides reference-type semantics. When you start thinking about the implications of this change, other changes start to make more sense as well, including the constructor behavior you describe.
Did you try to give the layout_width and layout_height like the following? Since you are setting with wrap_content, the image button expands to the size of source image's height and width.
<blink>
<ImageButton>
android:id="@+id/Button01"
android:scaleType="fitXY"
android:layout_width="80dip"
android:layout_height="80dip"
android:cropToPadding="false"
android:paddingLeft="10dp"
android:src="@drawable/eye">
</ImageButton>
</blink>
When testing for directories remember that every directory contains two special files.
One is called '.' and the other '..'
. is the directory's own name while .. is the name of it's parent directory.
To avoid trailing backslash problems just test to see if the directory knows it's own name.
eg:
if not exist %temp%\buffer\. mkdir %temp%\buffer
If you're generating the shell string within Python 2 or Python 3, the following may help to quote the arguments:
#!/usr/bin/env python
from __future__ import print_function
try: # py3
from shlex import quote as shlex_quote
except ImportError: # py2
from pipes import quote as shlex_quote
s = """foo ain't "bad" so there!"""
print(s)
print(" ".join([shlex_quote(t) for t in s.split()]))
This will output:
foo ain't "bad" so there!
foo 'ain'"'"'t' '"bad"' so 'there!'
I've googled this like a million times, so my solution is to just put this bash function in your environment.
.bashrc
or .profile
or whatever
dos2unixd() {
find $1 -type f -print0 | xargs -0 dos2unix
}
Usage
$ dos2unixd ./somepath
This way you still have the original command dos2unix
and it's easy to remember this one dos2unixd
.
You may use implicit classes:
import scala.math._
object ExtNumber extends App {
implicit class ExtendedDouble(n: Double) {
def rounded(x: Int) = {
val w = pow(10, x)
(n * w).toLong.toDouble / w
}
}
// usage
val a = 1.23456789
println(a.rounded(2))
}
If you are referring to the npm module sleep, it notes in the readme that sleep
will block execution. So you are right - it isn't what you want. Instead you want to use setTimeout which is non-blocking. Here is an example:
setTimeout(function() {
console.log('hello world!');
}, 5000);
For anyone looking to do this using es7 async/await, this example should help:
const snooze = ms => new Promise(resolve => setTimeout(resolve, ms));
const example = async () => {
console.log('About to snooze without halting the event loop...');
await snooze(1000);
console.log('done!');
};
example();
In addition to the answer of @dhroove (would have written a comment if I had 50 rep...)
The link has changed to: http://docs.oracle.com/javafx/2/api/
At least my eclipse wasn't able to use the link from him.
You don't need jquery, just use yourstring.length
. See reference here and also here.
Update:
To support unicode strings, length need to be computed as following:
[...""].length
or create an auxiliary function
function uniLen(s) {
return [...s].length
}
The difference in whether you have to instantiate your @InjectMocks
annotated field is in the version of Mockito, not in whether you use the MockitoJunitRunner or MockitoAnnotations.initMocks
. In 1.9, which will also handle some constructor injection of your @Mock
fields, it will do the instantiation for you. In earlier versions, you have to instantiate it yourself.
This is how I do unit testing of my Spring beans. There is no problem. People run into confusion when they want to use Spring configuration files to actually do the injection of the mocks, which is crossing up the point of unit tests and integration tests.
And of course the unit under test is an Impl. You need to test a real concrete thing, right? Even if you declared it as an interface you would have to instantiate the real thing to test it. Now, you could get into spies, which are stub/mock wrappers around real objects, but that should be for corner cases.
If you add Settings to a Class Library project in Visual Studio (Project Properties, Settings), it will add an app.config file to your project with the relevant userSettings/applicatioNSettings sections, and the default values for these settings from your Settings.settings file.
However this configuration file will not be used at runtime - instead the class library uses the configuration file of its hosting application.
I believe the main reason for generating this file is so that you can copy/paste the settings into the host application's configuration file.
The way I am doing it my code is to make an extension of UIFont: (This is Swift 4.1)
extension UIFont {
public func textWidth(s: String) -> CGFloat
{
return s.size(withAttributes: [NSAttributedString.Key.font: self]).width
}
} // extension UIFont
class1 item = lst[index];
item.foo = bar;
This suits the requirement:
select username, account_status, EXPIRY_DATE from dba_users where
username='<username>';
Output:
USERNAME ACCOUNT_STATUS EXPIRY_DA
--------------------------------------------------------------------------------
SYSTEM EXPIRED 13-NOV-17
Update your apt-get:
$ sudo apt-get update
$ sudo apt-get install g++
Run your program.cpp:
$ g++ program.cpp
$ ./a.out
If you're using node later than 7.6 and you don't like the callback style, you can also use node-util's promisify
function with async / await
to get shell commands which read cleanly. Here's an example of the accepted answer, using this technique:
const { promisify } = require('util');
const exec = promisify(require('child_process').exec)
module.exports.getGitUser = async function getGitUser () {
const name = await exec('git config --global user.name')
const email = await exec('git config --global user.email')
return { name, email }
};
This also has the added benefit of returning a rejected promise on failed commands, which can be handled with try / catch
inside the async code.
As recommended in a comment, I used the "Google Maps Platform API Checker" Chrome add-in to identify and resolve the issue.
Essentially, this add-in directed me to here where I was able to sign in to Google and create a free API key.
Afterwards, I updated my JavaScript and it immediately resolved this issue.
Old JavaScript: ...script src="https://maps.googleapis.com/maps/api/js?v=3" ...
Updated Javascript:...script src="https://maps.googleapis.com/maps/api/js?key=*****GOOGLE API KEY******&v=3" ...
The add-in then validated the JS API call. Hope this helps someone resolve the issue quickly!
I got the same question here. If the document is huge, it is not a good idea to use XmlDocument. The fact is that the first element is the root element, based on which XmlReader can be used to get the root element. Using XmlReader will be much more efficient than using XmlDocument as it doesn't require load the whole document into memory.
using (XmlReader reader = XmlReader.Create(<your_xml_file>)) {
while (reader.Read()) {
// first element is the root element
if (reader.NodeType == XmlNodeType.Element) {
System.Console.WriteLine(reader.Name);
break;
}
}
}
simply using Viewbag data as IEnumerable<> list
@{
var getlist= ViewBag.Listdata as IEnumerable<myproject.models.listmodel>;
foreach (var item in getlist){ //using foreach
<span>item .name</span>
}
}
//---------or just write name inside the getlist
<span>getlist[0].name</span>
Does this work:
$msgid = $_GET['msgid'];
$oldMessage = '';
$deletedFormat = '';
//read the entire string
$str=file_get_contents('msghistory.txt');
//replace something in the file string - this is a VERY simple example
$str=str_replace($oldMessage, $deletedFormat,$str);
//write the entire string
file_put_contents('msghistory.txt', $str);
You could use D3 to handle the callback, and load the local JSON file data.json
, as follows:
<script src="//d3js.org/d3.v3.min.js" charset="utf-8"></script>
<script>
d3.json("data.json", function(error, data) {
if (error)
throw error;
console.log(data);
});
</script>
I had the same problem but it had nothing to do with annotations. The problem happened while indexing beans in my container (Jboss EAP 6.3). One of my beans could not be indexed because it used Java 8 features an I got this sneaky little warning while deploying:
WARN [org.jboss.as.server.deployment] ... Could not index class ... java.lang.IllegalStateException: Unknown tag! pos=20 poolCount = 133
Then at the injection point I got the error:
Unsatisfied dependencies for type ... with qualifiers @Default
The solution is to update the Java annotations index. download new version of jandex (jandex-1.2.3.Final or newer) then put it into
JBOSS_HOME\modules\system\layers\base\org\jboss\jandex\main and then update reference to the new file in module.xml
NOTE: EAP 6.4.x already have this fixed
I think that scipy.stats.probplot
will do what you want. See the documentation for more detail.
import numpy as np
import pylab
import scipy.stats as stats
measurements = np.random.normal(loc = 20, scale = 5, size=100)
stats.probplot(measurements, dist="norm", plot=pylab)
pylab.show()
Result
Well it was very simple. I was missing the format of the date in the json file, so I should write :
st = datetime.strptime(st, '%A %d %B %H %M')
because in the json file the date was like :
"start": "Friday 06 December 02:05",
UPDATE ANDROID 10 AND HIGHER
Start an activity from service (foreground or background) is no longer allowed.
There are still some restrictions that can be seen in the documentation
https://developer.android.com/guide/components/activities/background-starts
I used a jQuery plugin, HUtil, and wrote a YUI History like interface on top of it.
Check it out once. If you need help I can help.
In my case, I wanted to see .htaccess files, but not all the other .* resources.
In Zend Studio for Eclipse, in PHP Explorer (not Remote System Explorer), click the downward facing arrow (next to the left/right arrows).
Choose Filters.
Uncheck .* resources
In the "Name filter patterns" area, type the filenames you want to ignore.
I used:
.svn, .cvs, .DS_Store, .buildpath, .project
I have just upgraded the Ubuntu Server version from 12.04 LTS to 14.04 LTS.
Indeed, as said above, the .conf extension to Apache 2.4.x is needed to the websites vhost files that resides on sites-available directory.
Before read this question I did not have a clue what was going on with the server.
Pretty nice solution.
Just summarizing I did the following steps on Terminal:
1) Access sites-enabled folder
$ cd /etc/apache2/sites-enabled
2) Because the command a2dissite will not work with deprecated files (without .conf) remove the old website files that was published
$ sudo rm <my-old-website-without-.conf>
3) Rename the website vhost files changing its extension adding .conf to the end
$ sudo mv /etc/apache2/sites-available/mywebsite /etc/apache2/sites-available/mywebsite.conf
4) Republish the new and correct vhost file
$ sudo a2ensite mywebsite.conf
5) Check the website on browser and have fun! :)
add
credits: {
enabled: false
}
[NOTE] that it is in the same line with
xAxis: {}
and yAxis: {}
There are some open source alternatives:
but I can't initialize my derived class, I mean I did this Inheritance so I can add animals to my PetStore but now since sizeF is private how can I do that ?? so I'm thinking maybe in the PetStore default constructor I can call Farm()... so any Idea ???
Don't panic.
Farm constructor will be called in the constructor of PetStore, automatically.
See the base class inheritance calling rules: What are the rules for calling the superclass constructor?
public static Int32 getLongIPAddress(string ipAddress)
{
return IPAddress.NetworkToHostOrder(BitConverter.ToInt32(IPAddress.Parse(ipAddress).GetAddressBytes(), 0));
}
The above example would be the way I go.. Only thing you might have to do is convert to a UInt32 for display purposes, or string purposes including using it as a long address in string form.
Which is what is needed when using the IPAddress.Parse(String) function. Sigh.
here is my solution. I have also extended the PDO class:
class Db extends PDO
{
/**
* SELECT ... WHERE fieldName IN (:paramName) workaround
*
* @param array $array
* @param string $prefix
*
* @return string
*/
public function CreateArrayBindParamNames(array $array, $prefix = 'id_')
{
$newparams = [];
foreach ($array as $n => $val)
{
$newparams[] = ":".$prefix.$n;
}
return implode(", ", $newparams);
}
/**
* Bind every array element to the proper named parameter
*
* @param PDOStatement $stmt
* @param array $array
* @param string $prefix
*/
public function BindArrayParam(PDOStatement &$stmt, array $array, $prefix = 'id_')
{
foreach($array as $n => $val)
{
$val = intval($val);
$stmt -> bindParam(":".$prefix.$n, $val, PDO::PARAM_INT);
}
}
}
Here is a sample usage for the above code:
$idList = [1, 2, 3, 4];
$stmt = $this -> db -> prepare("
SELECT
`Name`
FROM
`User`
WHERE
(`ID` IN (".$this -> db -> CreateArrayBindParamNames($idList)."))");
$this -> db -> BindArrayParam($stmt, $idList);
$stmt -> execute();
foreach($stmt as $row)
{
echo $row['Name'];
}
Let me know what you think
If you really mean exactly what you say (that you only need to find out IF "there are any keys" in B and not in A, not WHICH ONES might those be if any), the fastest way should be:
if any(True for k in dictB if k not in dictA): ...
If you actually need to find out WHICH KEYS, if any, are in B and not in A, and not just "IF" there are such keys, then existing answers are quite appropriate (but I do suggest more precision in future questions if that's indeed what you mean;-).
I am using Ubuntu. I just disabled ssl mode of apache2 and it worked for me.
a2dismod ssl
and then restarted apache2.
service apache2 restart
You just need this:
$(".hidden").attr("placeholder", "Type here to search");
classList
is used for manipulating classes and not attributes.
UPDATE: JUST USE JSON.stringify to print objects on screen!
All you need is this line:
document.body.innerHTML = '<pre>' + JSON.stringify(ObjectWithSubObjects, null, "\t") + '</pre>';
This is my older version of printing objects recursively on screen:
var previousStack = '';
var output = '';
function objToString(obj, stack) {
for (var property in obj) {
var tab = ' ';
if (obj.hasOwnProperty(property)) {
if (typeof obj[property] === 'object' && typeof stack === 'undefined') {
config = objToString(obj[property], property);
} else {
if (typeof stack !== 'undefined' && stack !== null && stack === previousStack) {
output = output.substring(0, output.length - 1); // remove last }
output += tab + '<span>' + property + ': ' + obj[property] + '</span><br />'; // insert property
output += '}'; // add last } again
} else {
if (typeof stack !== 'undefined') {
output += stack + ': { <br />' + tab;
}
output += '<span>' + property + ': ' + obj[property] + '</span><br />';
if (typeof stack !== 'undefined') {
output += '}';
}
}
previousStack = stack;
}
}
}
return output;
}
Usage:
document.body.innerHTML = objToString(ObjectWithSubObjects);
Example output:
cache: false
position: fixed
effect: {
fade: false
fall: true
}
Obviously this can be improved by adding comma's when needed and quotes from string values. But this was good enough for my case.
As you've guessed, the right syntax is
del df['column_name']
It's difficult to make del df.column_name
work simply as the result of syntactic limitations in Python. del df[name]
gets translated to df.__delitem__(name)
under the covers by Python.
From my notes:
Which parses like this:
q=latN+lonW+(label) location of teardrop
t=k keyhole (satelite map)
t=h hybrid
ll=lat,-lon center of map
spn=w.w,h.h span of map, degrees
iwloc has something to do with the info window. hl is obviously language.
See also: http://www.seomoz.org/ugc/everything-you-never-wanted-to-know-about-google-maps-parameters
You can get your package name like so:
$ /path/to/adb shell 'pm list packages -f myapp'
package:/data/app/mycompany.myapp-2.apk=mycompany.myapp
Here are the options:
$ adb
Android Debug Bridge version 1.0.32
Revision 09a0d98bebce-android
-a - directs adb to listen on all interfaces for a connection
-d - directs command to the only connected USB device
returns an error if more than one USB device is present.
-e - directs command to the only running emulator.
returns an error if more than one emulator is running.
-s <specific device> - directs command to the device or emulator with the given
serial number or qualifier. Overrides ANDROID_SERIAL
environment variable.
-p <product name or path> - simple product name like 'sooner', or
a relative/absolute path to a product
out directory like 'out/target/product/sooner'.
If -p is not specified, the ANDROID_PRODUCT_OUT
environment variable is used, which must
be an absolute path.
-H - Name of adb server host (default: localhost)
-P - Port of adb server (default: 5037)
devices [-l] - list all connected devices
('-l' will also list device qualifiers)
connect <host>[:<port>] - connect to a device via TCP/IP
Port 5555 is used by default if no port number is specified.
disconnect [<host>[:<port>]] - disconnect from a TCP/IP device.
Port 5555 is used by default if no port number is specified.
Using this command with no additional arguments
will disconnect from all connected TCP/IP devices.
device commands:
adb push [-p] <local> <remote>
- copy file/dir to device
('-p' to display the transfer progress)
adb pull [-p] [-a] <remote> [<local>]
- copy file/dir from device
('-p' to display the transfer progress)
('-a' means copy timestamp and mode)
adb sync [ <directory> ] - copy host->device only if changed
(-l means list but don't copy)
adb shell - run remote shell interactively
adb shell <command> - run remote shell command
adb emu <command> - run emulator console command
adb logcat [ <filter-spec> ] - View device log
adb forward --list - list all forward socket connections.
the format is a list of lines with the following format:
<serial> " " <local> " " <remote> "\n"
adb forward <local> <remote> - forward socket connections
forward specs are one of:
tcp:<port>
localabstract:<unix domain socket name>
localreserved:<unix domain socket name>
localfilesystem:<unix domain socket name>
dev:<character device name>
jdwp:<process pid> (remote only)
adb forward --no-rebind <local> <remote>
- same as 'adb forward <local> <remote>' but fails
if <local> is already forwarded
adb forward --remove <local> - remove a specific forward socket connection
adb forward --remove-all - remove all forward socket connections
adb reverse --list - list all reverse socket connections from device
adb reverse <remote> <local> - reverse socket connections
reverse specs are one of:
tcp:<port>
localabstract:<unix domain socket name>
localreserved:<unix domain socket name>
localfilesystem:<unix domain socket name>
adb reverse --norebind <remote> <local>
- same as 'adb reverse <remote> <local>' but fails
if <remote> is already reversed.
adb reverse --remove <remote>
- remove a specific reversed socket connection
adb reverse --remove-all - remove all reversed socket connections from device
adb jdwp - list PIDs of processes hosting a JDWP transport
adb install [-lrtsdg] <file>
- push this package file to the device and install it
(-l: forward lock application)
(-r: replace existing application)
(-t: allow test packages)
(-s: install application on sdcard)
(-d: allow version code downgrade)
(-g: grant all runtime permissions)
adb install-multiple [-lrtsdpg] <file...>
- push this package file to the device and install it
(-l: forward lock application)
(-r: replace existing application)
(-t: allow test packages)
(-s: install application on sdcard)
(-d: allow version code downgrade)
(-p: partial application install)
(-g: grant all runtime permissions)
adb uninstall [-k] <package> - remove this app package from the device
('-k' means keep the data and cache directories)
adb bugreport - return all information from the device
that should be included in a bug report.
adb backup [-f <file>] [-apk|-noapk] [-obb|-noobb] [-shared|-noshared] [-all] [-system|-nosystem] [<packages...>]
- write an archive of the device's data to <file>.
If no -f option is supplied then the data is written
to "backup.ab" in the current directory.
(-apk|-noapk enable/disable backup of the .apks themselves
in the archive; the default is noapk.)
(-obb|-noobb enable/disable backup of any installed apk expansion
(aka .obb) files associated with each application; the default
is noobb.)
(-shared|-noshared enable/disable backup of the device's
shared storage / SD card contents; the default is noshared.)
(-all means to back up all installed applications)
(-system|-nosystem toggles whether -all automatically includes
system applications; the default is to include system apps)
(<packages...> is the list of applications to be backed up. If
the -all or -shared flags are passed, then the package
list is optional. Applications explicitly given on the
command line will be included even if -nosystem would
ordinarily cause them to be omitted.)
adb restore <file> - restore device contents from the <file> backup archive
adb disable-verity - disable dm-verity checking on USERDEBUG builds
adb enable-verity - re-enable dm-verity checking on USERDEBUG builds
adb keygen <file> - generate adb public/private key. The private key is stored in <file>,
and the public key is stored in <file>.pub. Any existing files
are overwritten.
adb help - show this help message
adb version - show version num
scripting:
adb wait-for-device - block until device is online
adb start-server - ensure that there is a server running
adb kill-server - kill the server if it is running
adb get-state - prints: offline | bootloader | device
adb get-serialno - prints: <serial-number>
adb get-devpath - prints: <device-path>
adb remount - remounts the /system, /vendor (if present) and /oem (if present) partitions on the device read-write
adb reboot [bootloader|recovery]
- reboots the device, optionally into the bootloader or recovery program.
adb reboot sideload - reboots the device into the sideload mode in recovery program (adb root required).
adb reboot sideload-auto-reboot
- reboots into the sideload mode, then reboots automatically after the sideload regardless of the result.
adb sideload <file> - sideloads the given package
adb root - restarts the adbd daemon with root permissions
adb unroot - restarts the adbd daemon without root permissions
adb usb - restarts the adbd daemon listening on USB
adb tcpip <port> - restarts the adbd daemon listening on TCP on the specified port
networking:
adb ppp <tty> [parameters] - Run PPP over USB.
Note: you should not automatically start a PPP connection.
<tty> refers to the tty for PPP stream. Eg. dev:/dev/omap_csmi_tty1
[parameters] - Eg. defaultroute debug dump local notty usepeerdns
adb sync notes: adb sync [ <directory> ]
<localdir> can be interpreted in several ways:
- If <directory> is not specified, /system, /vendor (if present), /oem (if present) and /data partitions will be updated.
- If it is "system", "vendor", "oem" or "data", only the corresponding partition
is updated.
environment variables:
ADB_TRACE - Print debug information. A comma separated list of the following values
1 or all, adb, sockets, packets, rwx, usb, sync, sysdeps, transport, jdwp
ANDROID_SERIAL - The serial number to connect to. -s takes priority over this if given.
ANDROID_LOG_TAGS - When used with the logcat option, only these debug tags are printed.
In .htaccess add this line:
AddCharset utf-8 .html .css .php .txt .js
This is for those that do not have access to their server's conf file. It is just one more thing to try when other attempts failed.
As far as performance issues regarding the use of .htaccess I have not seen this. My typical page load times are 150-200 mS with or without .htaccess
What good is performance if your page does not render correctly. Most shared servers do not allow user access to the config file which is the preferred place to add a character set.
You can try with Directory.GetFiles and fix your pattern
string[] files = Directory.GetFiles(@"c:\", "*.txt");
foreach (string file in files)
{
File.Copy(file, "....");
}
Or Move
foreach (string file in files)
{
File.Move(file, "....");
}
For Swift 3
override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
if UIDevice.current.orientation.isLandscape {
//Landscape
}
else if UIDevice.current.orientation.isFlat {
//isFlat
}
else {
//Portrait
}
}
Before MVC 5 you could map URLs to specific actions and controllers by calling routes.MapRoute(...)
in the RouteConfig.cs file. This is where the url for the homepage is stored (Home/Index
). However if you modify the default route as shown below,
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
keep in mind that this will affect the URLs of other actions and controllers. For example, if you had a controller class named ExampleController
and an action method inside of it called DoSomething
, then the expected default url ExampleController/DoSomething
will no longer work because the default route was changed.
A workaround for this is to not mess with the default route and create new routes in the RouteConfig.cs file for other actions and controllers like so,
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
routes.MapRoute(
name: "Example",
url: "hey/now",
defaults: new { controller = "Example", action = "DoSomething", id = UrlParameter.Optional }
);
Now the DoSomething
action of the ExampleController
class will be mapped to the url hey/now
. But this can get tedious to do for every time you want to define routes for different actions. So in MVC 5 you can now add attributes to match urls to actions like so,
public class HomeController : Controller
{
// url is now 'index/' instead of 'home/index'
[Route("index")]
public ActionResult Index()
{
return View();
}
// url is now 'create/new' instead of 'home/create'
[Route("create/new")]
public ActionResult Create()
{
return View();
}
}
Trim()
will only remove leading or trailing spaces.
Try .Contains()
to check if a string contains white space
"sossjjs sskkk".Contains(" ") // returns true
If you are facing this issue with rails and you know that you already have created that user-name with password along with correct rights then you just need to put following at the end of your database.yml file.
host: localhost
overall file will look like below
development:
adapter: postgresql
encoding: unicode
database: myapp_development
pool: 5
username: root
password: admin
host: localhost
You do not need to touch you pg_hba.conf
file at all. Happy coding
Logit is a function that maps probabilities [0, 1]
to [-inf, +inf]
.
Softmax is a function that maps [-inf, +inf]
to [0, 1]
similar as Sigmoid. But Softmax also normalizes the sum of the values(output vector) to be 1.
Tensorflow "with logit": It means that you are applying a softmax function to logit numbers to normalize it. The input_vector/logit is not normalized and can scale from [-inf, inf].
This normalization is used for multiclass classification problems. And for multilabel classification problems sigmoid normalization is used i.e. tf.nn.sigmoid_cross_entropy_with_logits
Try following command sequence on Ubuntu terminal:
sudo apt-get install software-properties-common
sudo apt-add-repository universe
sudo apt-get update
sudo apt-get install python-pip
Here's a way to pass a dynamic object to a view (or partial view)
Add the following class anywhere in your solution (use System namespace, so its ready to use without having to add any references) -
namespace System
{
public static class ExpandoHelper
{
public static ExpandoObject ToExpando(this object anonymousObject)
{
IDictionary<string, object> anonymousDictionary = HtmlHelper.AnonymousObjectToHtmlAttributes(anonymousObject);
IDictionary<string, object> expando = new ExpandoObject();
foreach (var item in anonymousDictionary)
expando.Add(item);
return (ExpandoObject)expando;
}
}
}
When you send the model to the view, convert it to Expando :
return View(new {x=4, y=6}.ToExpando());
Cheers
If you have a unix/linux system I'd just rename the file via command line
mv file_name.pynb.txt file_name.ipynb
worked like a charm for me!
First you need to understand, that both are different things. Stored Procedures
are best used for INSERT-UPDATE-DELETE
statements. Whereas Views
are used for SELECT
statements. You should use both of them.
In views you cannot alter the data. Some databases have updatable Views where you can use INSERT-UPDATE-DELETE
on Views
.
You were on the right track with response.getOutputStream()
, but you're not using its output anywhere in your code. Essentially what you need to do is to stream the PDF file's bytes directly to the output stream and flush the response. In Spring you can do it like this:
@RequestMapping(value="/getpdf", method=RequestMethod.POST)
public ResponseEntity<byte[]> getPDF(@RequestBody String json) {
// convert JSON to Employee
Employee emp = convertSomehow(json);
// generate the file
PdfUtil.showHelp(emp);
// retrieve contents of "C:/tmp/report.pdf" that were written in showHelp
byte[] contents = (...);
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_PDF);
// Here you have to set the actual filename of your pdf
String filename = "output.pdf";
headers.setContentDispositionFormData(filename, filename);
headers.setCacheControl("must-revalidate, post-check=0, pre-check=0");
ResponseEntity<byte[]> response = new ResponseEntity<>(contents, headers, HttpStatus.OK);
return response;
}
Notes:
showHelp
is not a good ideabyte[]
: example hereshowHelp()
to avoid overwriting the file if two users send a request at the same timeIn WPF, you use a DispatcherTimer
.
System.Windows.Threading.DispatcherTimer dispatcherTimer = new System.Windows.Threading.DispatcherTimer();
dispatcherTimer.Tick += new EventHandler(dispatcherTimer_Tick);
dispatcherTimer.Interval = new TimeSpan(0,5,0);
dispatcherTimer.Start();
private void dispatcherTimer_Tick(object sender, EventArgs e)
{
// code goes here
}
Try this for revert all changes uncommited in local branch
$ git reset --hard HEAD
But if you see a error like this:
fatal: Unable to create '/directory/for/your/project/.git/index.lock': File exists.
You can navigate to '.git' folder then delete index.lock file:
$ cd /directory/for/your/project/.git/
$ rm index.lock
Finaly, run again the command:
$ git reset --hard HEAD
Compiling the original example in Eclipse at compliance 1.8 and with annotation based null analysis enabled, we get this warning:
directPathToA(y);
^
Null type safety (type annotations): The expression of type 'Integer' needs unchecked conversion to conform to '@NonNull Integer'
This warning is worded in analogy to those warnings you get when mixing generified code with legacy code using raw types ("unchecked conversion"). We have the exact same situation here: method indirectPathToA()
has a "legacy" signature in that it doesn't specify any null contract. Tools can easily report this, so they will chase you down all alleys where null annotations need to be propagated but aren't yet.
And when using a clever @NonNullByDefault
we don't even have to say this every time.
In other words: whether or not null annotations "propagate very far" may depend on the tool you use, and on how rigorously you attend to all the warnings issued by the tool. With TYPE_USE null annotations you finally have the option to let the tool warn you about every possible NPE in your program, because nullness has become an intrisic property of the type system.
In case someone is still struggling with this issue:
I faced similar issue where 2 requests were hitting the server at the same time. There was no situation like below:
T1:
BEGIN TRANSACTION
INSERT TABLE A
INSERT TABLE B
END TRANSACTION
T2:
BEGIN TRANSACTION
INSERT TABLE B
INSERT TABLE A
END TRANSACTION
So, I was puzzled why deadlock is happening.
Then I found that there was parent child relation ship between 2 tables because of foreign key. When I was inserting a record in child table, the transaction was acquiring a lock on parent table's row. Immediately after that I was trying to update the parent row which was triggering elevation of lock to EXCLUSIVE one. As 2nd concurrent transaction was already holding a SHARED lock, it was causing deadlock.
Refer to: https://blog.tekenlight.com/2019/02/21/database-deadlock-mysql.html
Here is my "IE please don't crash"
typeof console=="undefined"&&(console={});typeof console.log=="undefined"&&(console.log=function(){});
* * * * 0
you can use above cron job to run on every week on sunday, but in addition on what time you want to run this job for that you can follow below concept :
* * * * * Command_to_execute
- ? ? ? -
| | | | |
| | | | +?? Day of week (0?6) (Sunday=0) or Sun, Mon, Tue,...
| | | +???- Month (1?12) or Jan, Feb,...
| | +????-? Day of month (1?31)
| +??????? Hour (0?23)
+????????- Minute (0?59)
See String.format
method.
String s = "hello %s!";
s = String.format(s, "world");
assertEquals(s, "hello world!"); // should be true
@hop5 and @RnMss suggested to use C++11 lambdas, but if you deal with pointers, you can use them directly:
#include <thread>
#include <iostream>
class CFoo {
public:
int m_i = 0;
void bar() {
++m_i;
}
};
int main() {
CFoo foo;
std::thread t1(&CFoo::bar, &foo);
t1.join();
std::thread t2(&CFoo::bar, &foo);
t2.join();
std::cout << foo.m_i << std::endl;
return 0;
}
outputs
2
Rewritten sample from this answer would be then:
#include <thread>
#include <iostream>
class Wrapper {
public:
void member1() {
std::cout << "i am member1" << std::endl;
}
void member2(const char *arg1, unsigned arg2) {
std::cout << "i am member2 and my first arg is (" << arg1 << ") and second arg is (" << arg2 << ")" << std::endl;
}
std::thread member1Thread() {
return std::thread(&Wrapper::member1, this);
}
std::thread member2Thread(const char *arg1, unsigned arg2) {
return std::thread(&Wrapper::member2, this, arg1, arg2);
}
};
int main() {
Wrapper *w = new Wrapper();
std::thread tw1 = w->member1Thread();
tw1.join();
std::thread tw2 = w->member2Thread("hello", 100);
tw2.join();
return 0;
}
It's not working since April of 2018 because Google decided to give greater control of playback to users. You just need to add &mute=1 to your URL. Autoplay Policy Changes
<iframe id="existing-iframe-example"
width="640" height="360"
src="https://www.youtube.com/embed/-SFcIUEvNOQ?autoplay=1&mute=1&enablejsapi=1"
frameborder="0"
style="border: solid 4px #37474F"
></iframe>
Update :
Audio/Video Updates in Chrome 73
Google said : Now that Progressive Web Apps (PWAs) are available on all desktop platforms, we are extending the rule that we had on mobile to desktop: autoplay with sound is now allowed for installed PWAs. Note that it only applies to pages in the scope of the web app manifest. https://developers.google.com/web/updates/2019/02/chrome-73-media-updates#autoplay-pwa
The answer by @Stenyg only works for older Raspbian images. The recently released Raspbian based on Debian Buster requires an updated toolchain:
In Debian Buster the gcc compiler and glibc was updated to version 8.3. The toolchain in git://github.com/raspberrypi/tools.git
is still based on the older gcc 6 version. This means that using git://github.com/raspberrypi/tools.git
will lead to many compile errors.
This tutorial is based on @Stenyg answer. In addition to many other solutions in the internet, this tutorial also supports older Rasperry Pi (A, B, B+, Zero) based on the ARMv6 CPU. See also: GCC 8 Cross Compiler outputs ARMv7 executable instead of ARMv6
There is no official git repository containing an updated toolchain (See https://github.com/raspberrypi/tools/issues/102).
I created a new github repository which includes building and precompiled toolchains for ARMv6 based on GCC8 and newer:
https://github.com/Pro/raspi-toolchain
As mentioned in the project's readme, these are the steps to get the toolchain. You can also build it yourself (see the README for further details).
wget https://github.com/Pro/raspi-toolchain/releases/latest/download/raspi-toolchain.tar.gz
/opt/cross-pi-gcc
since it's not location independent.sudo tar xfz raspi-toolchain.tar.gz --strip-components=1 -C /opt
You are done! The toolchain is now in /opt/cross-pi-gcc
Optional, add the toolchain to your path, by adding:
export PATH=$PATH:/opt/cross-pi-gcc/bin
to the end of the file named ~/.bashrc
Now you can either log out and log back in (i.e. restart your terminal session), or run . ~/.bashrc
in your terminal to pick up the PATH
addition in your current terminal session.
To cross-compile for your own Raspberry Pi, which may have some custom libraries installed, you need to get these libraries onto your host.
Create a folder $HOME/raspberrypi
.
In your raspberrypi
folder, make a folder called rootfs
.
Now you need to copy the entire /lib
and /usr
directory to this newly created folder. I usually bring the rpi image up and copy it via rsync:
rsync -vR --progress -rl --delete-after --safe-links [email protected]:/{lib,usr,opt/vc/lib} $HOME/raspberrypi/rootfs
where 192.168.1.PI
is replaced by the IP of your Raspberry Pi.
To tell CMake to take your own toolchain, you need to have a toolchain file which initializes the compiler settings.
Get this toolchain file from here: https://github.com/Pro/raspi-toolchain/blob/master/Toolchain-rpi.cmake
Now you should be able to compile your cmake
programs simply by adding this extra flag: -D CMAKE_TOOLCHAIN_FILE=$HOME/raspberrypi/pi.cmake
and setting the correct environment variables:
export RASPBIAN_ROOTFS=$HOME/raspberry/rootfs
export PATH=/opt/cross-pi-gcc/bin:$PATH
export RASPBERRY_VERSION=1
cmake -DCMAKE_TOOLCHAIN_FILE=$HOME/raspberry/Toolchain-rpi.cmake ..
An example hello world is shown here: https://github.com/Pro/raspi-toolchain/blob/master/build_hello_world.sh
I wanted to note that the fourth part of Accepted Answer is wrong .
theApp.factory('mainInfo', function($http) {
var obj = {content:null};
$http.get('content.json').success(function(data) {
// you can do some processing here
obj.content = data;
});
return obj;
});
The above code as @Karl Zilles wrote will fail because obj
will always be returned before it receives data (thus the value will always be null
) and this is because we are making an Asynchronous call.
The details of similar questions are discussed in this post
In Angular, use $promise
to deal with the fetched data when you want to make an asynchronous call.
The simplest version is
theApp.factory('mainInfo', function($http) {
return {
get: function(){
$http.get('content.json'); // this will return a promise to controller
}
});
// and in controller
mainInfo.get().then(function(response) {
$scope.foo = response.data.contentItem;
});
The reason I don't use success
and error
is I just found out from the doc, these two methods are deprecated.
The
$http
legacy promise methods success and error have been deprecated. Use the standardthen
method instead.
Solution using the "case" is universal, but then do not use the indexes.
order by case when MyDate is null then 1 else 0 end, MyDate
In my case, I needed performance.
SELECT smoneCol1,someCol2
FROM someSch.someTab
WHERE someCol2 = 2101 and ( someCol1 IS NULL )
UNION
SELECT smoneCol1,someCol2
FROM someSch.someTab
WHERE someCol2 = 2101 and ( someCol1 IS NOT NULL)
try this:
var hasVScroll = document.body.scrollHeight > document.body.clientHeight;
This will only tell you if the vertical scrollHeight is bigger than the height of the viewable content, however. The hasVScroll
variable will contain true or false.
If you need to do a more thorough check, add the following to the code above:
// Get the computed style of the body element
var cStyle = document.body.currentStyle||window.getComputedStyle(document.body, "");
// Check the overflow and overflowY properties for "auto" and "visible" values
hasVScroll = cStyle.overflow == "visible"
|| cStyle.overflowY == "visible"
|| (hasVScroll && cStyle.overflow == "auto")
|| (hasVScroll && cStyle.overflowY == "auto");
I don't think that you really want an iframe, do you?
Unless you're doing something weird, you should be getting your results back as JSON or (in the worst case) XML, right?
For your white box / extra space issue, try
style="display: none;"
instead of
style="visibility: hidden;"
HTML
<div>
<h4>Show content</h4>
</div>
<div>
<p>Hello World</p>
</div>
CSS
div+div {
display: none;
}
div:hover +div {
display: block;
}
For general command-line automation, Expect is the classic tool. Or try pexpect if you're more comfortable with Python.
Here's a similar question that suggests using Expect: Use expect in bash script to provide password to SSH command
The Windows version of Qt 4 includes both WebKit and classes to create ActiveX components. It probably isn't an ideal solution if you aren't already using Qt though.
You can save a string raw as is by using FileReader.
Save the string in a blob and call readAsArrayBuffer(). Then the onload-event results an arraybuffer, which can converted in a Uint8Array. Unfortunately this call is asynchronous.
This little function will help you:
function stringToBytes(str)
{
let reader = new FileReader();
let done = () => {};
reader.onload = event =>
{
done(new Uint8Array(event.target.result), str);
};
reader.readAsArrayBuffer(new Blob([str], { type: "application/octet-stream" }));
return { done: callback => { done = callback; } };
}
Call it like this:
stringToBytes("\u{1f4a9}").done(bytes =>
{
console.log(bytes);
});
output: [240, 159, 146, 169]
explanation:
JavaScript use UTF-16 and surrogate-pairs to store unicode characters in memory. To save unicode character in raw binary byte streams an encoding is necessary. Usually and in the most case, UTF-8 is used for this. If you not use an enconding you can't save unicode character, just ASCII up to 0x7f.
FileReader.readAsArrayBuffer() uses UTF-8.
https://support.procore.com/faq/what-is-the-difference-between-sp-and-idp-initiated-sso
There is much more to this but this is a high level overview on which is which.
Procore supports both SP- and IdP-initiated SSO:
Identity Provider Initiated (IdP-initiated) SSO. With this option, your end users must log into your Identity Provider's SSO page (e.g., Okta, OneLogin, or Microsoft Azure AD) and then click an icon to log into and open the Procore web application. To configure this solution, see Configure IdP-Initiated SSO for Microsoft Azure AD, Configure Procore for IdP-Initated Okta SSO, or Configure IdP-Initiated SSO for OneLogin. OR Service Provider Initiated (SP-initiated) SSO. Referred to as Procore-initiated SSO, this option gives your end users the ability to sign into the Procore Login page and then sends an authorization request to the Identify Provider (e.g., Okta, OneLogin, or Microsoft Azure AD). Once the IdP authenticates the user's identify, the user is logged into Procore. To configure this solution, see Configure Procore-Initiated SSO for Microsoft Azure Active Directory, Configure Procore-Initiated SSO for Okta, or Configure Procore-Initiated SSO for OneLogin.
<html>
<head>
<script type="text/javascript" src="jquery.js"></script>
<script>
$(document).ready(function(){
var locations = ["http://webPage1.com", "http://webPage2.com"];
var len = locations.length;
var iframe = $('#frame');
var i = 0;
setInterval(function () {
iframe.attr('src', locations[++i % len]);
}, 30000);
});
</script>
</head>
<body>
<iframe id="frame"></iframe>
</body>
</html>
Using the classes "responsive nowrap" on the table element should do the trick.
it was hard to solve but i did it look go to C:\Users(user name)
delete .gradle file its you didn't see it it may be in hidden files so if you use windows 7 right click then click on properties and click on hidden to be not checked
then the file will appear then delete it i hope this works
if you remove the float: left
from the a
and add white-space: nowrap
to the outer div
#myWorkContent{
width:530px;
height:210px;
border: 13px solid #bed5cd;
overflow-x: scroll;
overflow-y: hidden;
white-space: nowrap;
}
#myWorkContent a {
display: inline;
}
this should work for any size or amount of images..
or even:
#myWorkContent a {
display: inline-block;
vertical-align: middle;
}
which would also vertically align images of different heights if required
For a concrete example of accessing the SMS/MMS database, take a look at gTalkSMS.
I recently wrote a custom directive which can be generic enough to do any validation. It take a validation function from the current scope
module.directive('customValidator', [function () {
return {
restrict: 'A',
require: 'ngModel',
scope: { validateFunction: '&' },
link: function (scope, elm, attr, ngModelCtrl) {
ngModelCtrl.$parsers.push(function (value) {
var result = scope.validateFunction({ 'value': value });
if (result || result === false) {
if (result.then) {
result.then(function (data) { //For promise type result object
ngModelCtrl.$setValidity(attr.customValidator, data);
}, function (error) {
ngModelCtrl.$setValidity(attr.customValidator, false);
});
}
else {
ngModelCtrl.$setValidity(attr.customValidator, result);
return result ? value : undefined; //For boolean result return based on boolean value
}
}
return value;
});
}
};
}]);
To use it you do
<input type="email" name="email2" ng-model="emailReg2" custom-validator='emailMatch' data-validate-function='checkEmailMatch(value)'>
<span ng-show="registerForm.email2.$error.emailMatch">Emails have to match!</span>
In you controller then you can implement the method, that should return true or false
$scope.checkEmailMatch=function(value) {
return value===$scope.emailReg;
}
The advantage is that you do not have to write custom directive for each custom validation.
If a node is so unhealthy that the master can't get status from it -- Kubernetes may not be able to restart the node. And if health checks aren't working, what hope do you have of accessing the node by SSH?
In this case, you may have to hard-reboot -- or, if your hardware is in the cloud, let your provider do it.
For example, the AWS EC2 Dashboard allows you to right-click an instance to pull up an "Instance State" menu -- from which you can reboot/terminate an unresponsive node.
Before doing this, you might choose to kubectl cordon node
for good measure. And you may find kubectl delete node
to be an important part of the process for getting things back to normal -- if the node doesn't automatically rejoin the cluster after a reboot.
Why would a node become unresponsive? Probably some resource has been exhausted in a way that prevents the host operating system from handling new requests in a timely manner. This could be disk, or network -- but the more insidious case is out-of-memory (OOM), which Linux handles poorly.
To help Kubernetes manage node memory safely, it's a good idea to do both of the following:
requests
and limits
for memory.The idea here is to avoid the complications associated with memory overcommit, because memory is incompressible, and both Linux and Kubernetes' OOM killers may not trigger before the node has already become unhealthy and unreachable.
Use the below function.
function utf8_converter($array)
{
array_walk_recursive($array, function (&$item, $key) {
if (!mb_detect_encoding($item, 'utf-8', true)) {
$item = utf8_encode($item);
}
});
return $array;
}
Simplest way I did this. Not the best way but simplest way I know how.
import "fmt"
func main() {
fmt.Print(addTwoNumbers(5, 6))
}
func addTwoNumbers(val1 interface{}, val2 interface{}) int {
op1, _ := val1.(int)
op2, _ := val2.(int)
return op1 + op2
}
I think you’re misreading the message — your branch isn’t ahead of master
, it is master
. It’s ahead of origin/master
, which is a remote tracking branch that records the status of the remote repository from your last push
, pull
, or fetch
. It’s telling you exactly what you did; you got ahead of the remote and it’s reminding you to push.
Syntax:
transition: <property> || <duration> || <timing-function> || <delay> [, ...];
Note that the duration must come before the delay, if the latter is specified.
Individual transitions combined in shorthand declarations:
-webkit-transition: height 0.3s ease-out, opacity 0.3s ease 0.5s;
-moz-transition: height 0.3s ease-out, opacity 0.3s ease 0.5s;
-o-transition: height 0.3s ease-out, opacity 0.3s ease 0.5s;
transition: height 0.3s ease-out, opacity 0.3s ease 0.5s;
Or just transition them all:
-webkit-transition: all 0.3s ease-out;
-moz-transition: all 0.3s ease-out;
-o-transition: all 0.3s ease-out;
transition: all 0.3s ease-out;
Here is a straightforward example. Here is another one with the delay property.
Edit: previously listed here were the compatibilities and known issues regarding transition
. Removed for readability.
Bottom-line: just use it. The nature of this property is non-breaking for all applications and compatibility is now well above 94% globally.
If you still want to be sure, refer to http://caniuse.com/css-transitions
To complement the version of Leo Dabus, I added support for projects written Swift and Objective-C, also added support for the optional milliseconds, probably isn't the best but you would get the point:
Xcode 8 and Swift 3
extension Date {
struct Formatter {
static let iso8601: DateFormatter = {
let formatter = DateFormatter()
formatter.calendar = Calendar(identifier: .iso8601)
formatter.locale = Locale(identifier: "en_US_POSIX")
formatter.timeZone = TimeZone(secondsFromGMT: 0)
formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSXXXXX"
return formatter
}()
}
var iso8601: String {
return Formatter.iso8601.string(from: self)
}
}
extension String {
var dateFromISO8601: Date? {
var data = self
if self.range(of: ".") == nil {
// Case where the string doesn't contain the optional milliseconds
data = data.replacingOccurrences(of: "Z", with: ".000000Z")
}
return Date.Formatter.iso8601.date(from: data)
}
}
extension NSString {
var dateFromISO8601: Date? {
return (self as String).dateFromISO8601
}
}
There is a tiny drop-in replacement for the standard android Log class - https://github.com/zserge/log
Basically all you have to do is to replace imports from android.util.Log
to trikita.log.Log
. Then in your Application.onCreate()
or in some static initalizer check for the BuilConfig.DEBUG
or any other flag and use Log.level(Log.D)
or Log.level(Log.E)
to change the minimal log level. You can use Log.useLog(false)
to disable logging at all.
I think that the above answers missed the key point.
Let's have a class with a method:
class A(object):
def m(self):
pass
Now, let's play with it in ipython:
In [2]: A.m
Out[2]: <unbound method A.m>
Ok, so m() somehow becomes an unbound method of A. But is it really like that?
In [5]: A.__dict__['m']
Out[5]: <function m at 0xa66b8b4>
It turns out that m() is just a function, reference to which is added to A class dictionary - there's no magic. Then why A.m gives us an unbound method? It's because the dot is not translated to a simple dictionary lookup. It's de facto a call of A.__class__.__getattribute__(A, 'm'):
In [11]: class MetaA(type):
....: def __getattribute__(self, attr_name):
....: print str(self), '-', attr_name
In [12]: class A(object):
....: __metaclass__ = MetaA
In [23]: A.m
<class '__main__.A'> - m
<class '__main__.A'> - m
Now, I'm not sure out of the top of my head why the last line is printed twice, but still it's clear what's going on there.
Now, what the default __getattribute__ does is that it checks if the attribute is a so-called descriptor or not, i.e. if it implements a special __get__ method. If it implements that method, then what is returned is the result of calling that __get__ method. Going back to the first version of our A class, this is what we have:
In [28]: A.__dict__['m'].__get__(None, A)
Out[28]: <unbound method A.m>
And because Python functions implement the descriptor protocol, if they are called on behalf of an object, they bind themselves to that object in their __get__ method.
Ok, so how to add a method to an existing object? Assuming you don't mind patching class, it's as simple as:
B.m = m
Then B.m "becomes" an unbound method, thanks to the descriptor magic.
And if you want to add a method just to a single object, then you have to emulate the machinery yourself, by using types.MethodType:
b.m = types.MethodType(m, b)
By the way:
In [2]: A.m
Out[2]: <unbound method A.m>
In [59]: type(A.m)
Out[59]: <type 'instancemethod'>
In [60]: type(b.m)
Out[60]: <type 'instancemethod'>
In [61]: types.MethodType
Out[61]: <type 'instancemethod'>
copy mysql-connector-java-5.1.24-bin.jar
Paste it into \Apache Software Foundation\Tomcat 6.0\lib\<--here-->
Restart Your Server from Eclipes.
Done
const coloring = fn => ({ background, color = 'white' }) => (...text) => fn(`%c${text.join('')}`, `color:${color};background:${background}`);
const colors = {
primary: '#007bff',
success: '#28a745',
warning: '#ffc107',
danger: '#dc3545',
info: '#17a2b8',
};
const dir = (key = '', value = {}) => {
logs.primary(`++++++++++++start:${key}++++++++++++++`);
console.dir(value);
logs.primary(`++++++++++++end:${key}++++++++++++++`);
};
const logs = Object.keys(colors)
.reduce((prev, curr) => ({ ...prev, [curr]: coloring(console.log)({ background: colors[curr] }) }), { dir });
logs.success('hello succes');
logs.warning('hello fail');
_x000D_
By creating the increment table you should be aware not to delete inserted rows. reason for this is to avoid storing large dumb data in db with ID-s in it. Otherwise in case of mysql restart it would get max existing row and continue increment from that point as mention in documentation http://dev.mysql.com/doc/refman/5.0/en/innodb-auto-increment-handling.html
For those interested in the OS X solution for apps like Intelli-J where authorizations are stored by OSX:
Much easier than having to try to decrypt a password :-)
I also had this issue. Initially, a proxy was set and work fine. Then I connected to a network where it doesn't go through a proxy. After unsetting proxy pip again get works.
unset http_proxy; unset http_prox; unset HTTP_PROXY; unset HTTPS_PROXY
The .gitignore
file in the root directory does apply to all subdirectories. Mine looks like this:
.classpath
.project
.settings/
target/
This is in a multi-module maven project. All the submodules are imported as individual eclipse projects using m2eclipse. I have no further .gitignore
files. Indeed, if you look in the gitignore man page:
Patterns read from a
.gitignore
file in the same directory as the path, or in any parent directory…
So this should work for you.
You can use pandas.Series.map :
df['col'].map('str{}'.format)
It will apply the word "str" before all your values.
The Android support library can be imported within gradle in the dependencies :
compile 'com.android.support:design:22.2.0'
It should be included within GradlePlease! And as an example to use it:
<android.support.design.widget.TextInputLayout
android:id="@+id/to_text_input_layout"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<AutoCompleteTextView
android:id="@+id/autoCompleteTextViewTo"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:hint="To"
android:layout_marginTop="45dp"
/>
</android.support.design.widget.TextInputLayout>
Btw, the editor may not understand that AutoCompleteTextView is allowed within TextInputLayout.
preg_replace('/[^a-zA-Z0-9_ \-()\/%-&]/s', '', $String);
It's so simple with URLSearchParams
, supported in all modern browsers (caniuse).
let p = new URLSearchParams();
p.set("foo", "bar");
p.set("name", "Jack & Jill?");
console.log("http://example.com/?" + p.toString());
_x000D_
If you want to modify the existing URL, construct the object like this: new URLSearchParams(window.location.search)
and assign the string to window.location.search
.
var divID = "question-" + (parseInt(i)+1);
Use this +
operator behave as concat
that's why it showing 11.
You just need to define in your bean where you need a different scope than default singleton scope except prototype. For example:
<bean id="shoppingCart"
class="com.xxxxx.xxxx.ShoppingCartBean" scope="session">
<aop:scoped-proxy/>
</bean>
Another user mentioned this in slight detail but I missed it until I came back here about 3 times over 2 days -
There is a section titled EventListener breakpoints that contains a list of other breakpoints that can be set. It happens that I accidentally enabled one of them on DOM Mutation that was letting me know whenever anything to the DOM was overridden. Unfortunately this led to me disabling a bunch of plug-ins and add-ons before I realized it was just my machine. Hope this helps someone else.
There are many open source projects that can generate screenshots. For example PhantomJS, webkit2png etc
The big problem with these projects is that they are based on older browser technology and have problems rendering many sites, especially sites that use webfonts, flexbox, svg and various other additions to the HTML5 and CSS spec over the last couple of months/years.
I've tried a few of the third party services, and most are based on PhantomJS, meaning they also produce poor quality screenshots. The best third party service for generating website screenshots is urlbox.io. It is a paid service, although there is a free 7-day trial to test it out without committing to any paid plan.
Here is a link to the documentation, and below are simple steps to get it working in PHP with composer.
// 1 . Get the urlbox/screenshots composer package (on command line):
composer require urlbox/screenshots
// 2. Set up the composer package with Urlbox API credentials:
$urlbox = UrlboxRenderer::fromCredentials('API_KEY', 'API_SECRET');
// 3. Set your options (all options such as full page/full height screenshots, retina resolution, viewport dimensions, thumbnail width etc can be set here. See the docs for more.)
$options['url'] = 'example.com';
// 4. Generate the Urlbox url
$urlboxUrl = $urlbox->generateUrl($options);
// $urlboxUrl is now 'https://api.urlbox.io/v1/API_KEY/TOKEN/png?url=example.com'
// 5. Now stick it in an img tag, when the image is loaded in browser, the API call to urlbox will be triggered and a nice PNG screenshot will be generated!
<img src="$urlboxUrl" />
For e.g. here's a full height screenshot of this very page:
Template argument deduction for class templates
[*this]{ std::cout << could << " be " << useful << '\n'; }
[[fallthrough]]
, [[nodiscard]]
, [[maybe_unused]]
attributes
using
in attributes to avoid having to repeat an attribute namespace.
Compilers are now required to ignore non-standard attributes they don't recognize.
Simple static_assert(expression);
with no string
no throw
unless throw()
, and throw()
is noexcept(true)
.
std::tie
with auto
const auto [it, inserted] = map.insert( {"foo", bar} );
it
and inserted
with deduced type from the pair
that map::insert
returns.std::array
s and relatively flat structsif (init; condition)
and switch (init; condition)
if (const auto [it, inserted] = map.insert( {"foo", bar} ); inserted)
if(decl)
to cases where decl
isn't convertible-to-bool sensibly.Generalizing range-based for loops
Fixed order-of-evaluation for (some) expressions with some modifications
.then
on future work.Forward progress guarantees (FPG) (also, FPGs for parallel algorithms)
u8'U', u8'T', u8'F', u8'8'
character literals (string already existed)
inherited constructors fixes to some corner cases (see P0136R0 for examples of behavior changes)
std::string
like reference-to-character-array or substringstring const&
again. Also can make parsing a bajillion times faster."hello world"sv
char_traits
std::byte
off more than they could chew.
std::invoke
std::apply
std::make_from_tuple
, std::apply
applied to object construction
is_invocable
, is_invocable_r
, invoke_result
result_of
is_invocable<Foo(Args...), R>
is "can you call Foo
with Args...
and get something compatible with R
", where R=void
is default.invoke_result<Foo, Args...>
is std::result_of_t<Foo(Args...)>
but apparently less confusing?[class.directory_iterator]
and [class.recursive_directory_iterator]
fstream
s can be opened with path
s, as well as with const path::value_type*
strings.
for_each_n
reduce
transform_reduce
exclusive_scan
inclusive_scan
transform_exclusive_scan
transform_inclusive_scan
Added for threading purposes, exposed even if you aren't using them threaded
atomic<T>
::is_always_lockfree
std::lock
pain when locking more than one mutex at a time.std
algorithms, and related machinery[func.searchers]
and [alg.search]
std::function
for allocatorsstd::sample
, sampling from a range?
try_emplace
and insert_or_assign
Splicing for map<>
, unordered_map<>
, set<>
, and unordered_set<>
non-const .data()
for string.
non-member std::size
, std::empty
, std::data
std::begin
/end
The emplace
family of functions now returns a reference to the created object.
unique_ptr<T[]>
fixes and other unique_ptr
tweaks.weak_from_this
and some fixed to shared from thisstd
datatype improvements:{}
construction of std::tuple
and other improvementsC++17 library is based on C11 instead of C99
Reserved std[0-9]+
for future standard libraries
std
implementations exposedstd::clamp()
std::clamp( a, b, c ) == std::max( b, std::min( a, c ) )
roughlygcd
and lcm
std::uncaught_exceptions
std::as_const
std::bool_constant
_v
template variablesstd::void_t<T>
std::owner_less<void>
std::less<void>
, but for smart pointers to sort based on contentsstd::chrono
polishstd::conjunction
, std::disjunction
, std::negation
exposedstd::not_fn
std
std::less
.<codecvt>
memory_order_consume
result_of
, replaced with invoke_result
shared_ptr::unique
, it isn't very threadsafeIsocpp.org has has an independent list of changes since C++14; it has been partly pillaged.
Naturally TS work continues in parallel, so there are some TS that are not-quite-ripe that will have to wait for the next iteration. The target for the next iteration is C++20 as previously planned, not C++19 as some rumors implied. C++1O has been avoided.
Initial list taken from this reddit post and this reddit post, with links added via googling or from the above isocpp.org page.
Additional entries pillaged from SD-6 feature-test list.
clang's feature list and library feature list are next to be pillaged. This doesn't seem to be reliable, as it is C++1z, not C++17.
these slides had some features missing elsewhere.
While "what was removed" was not asked, here is a short list of a few things ((mostly?) previous deprecated) that are removed in C++17 from C++:
register
, keyword reserved for future usebool b; ++b;
<functional>
stuff, random_shuffle
std::function
There were rewordings. I am unsure if these have any impact on code, or if they are just cleanups in the standard:
P0505R0 (constexpr chrono)
P0418R2 (atomic tweaks)
P0512R0 (template argument deduction tweaks)
P0490R0 (structured binding tweaks)
P0513R0 (changes to std::hash
)
P0502R0 (parallel exceptions)
P0509R1 (updating restrictions on exception handling)
P0012R1 (make exception specifications be part of the type system)
P0510R0 (restrictions on variants)
P0504R0 (tags for optional/variant/any)
P0497R0 (shared ptr tweaks)
P0508R0 (structured bindings node handles)
P0521R0 (shared pointer use count and unique changes?)
https://isocpp.org/files/papers/p0636r0.html
my solution:
create a file card_view_border.xml
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
<solid android:color="@color/white_background"/>
<stroke android:width="2dp"
android:color="@color/red" />
<corners android:radius="20dip"/>
</shape>
and set programmatically
cardView.setBackgroundResource(R.drawable.card_view_border);
alloca() is very useful if you can't use a standard local variable because its size would need to be determined at runtime and you can absolutely guarantee that the pointer you get from alloca() will NEVER be used after this function returns.
You can be fairly safe if you
The real danger comes from the chance that someone else will violate these conditions sometime later. With that in mind it's great for passing buffers to functions that format text into them :)
I found the reason why the connection was not working, it was because the connection was trying to connect to port 8888, when it needed to connect to port 8889.
$conn = new PDO("mysql:host=$servername;port=8889;dbname=AppDatabase", $username, $password);
This fixed the problem, although changing the server name to localhost still gives the error.
Connection failed: SQLSTATE[HY000] [2002] No such file or directory
But it connects successfully when the IP address is entered for the server name.
1) Open your project url: https://github.com/someuser/project-name
2) in the top, aside of the project name, click EDIT
Change the order you're including your scripts (jQuery first):
<script src="http://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<script type="text/javascript" src="./javascript.js"></script>
<script
src="http://maps.googleapis.com/maps/api/js?key=YOUR_APIKEY&sensor=false">
</script>
On load of My Windows Form the comboBox
will display the ClassName
column of my DataTable
as it's the DisplayMember
also has its ValueMember
(not visible to user) with it.
private void Form1_Load(object sender, EventArgs e)
{
this.comboBoxSubjectCName.DataSource = this.Student.TableClass;
this.comboBoxSubjectCName.DisplayMember = TableColumn.ClassName;//Column name that will be the DisplayMember
this.comboBoxSubjectCName.ValueMember = TableColumn.ClassID;//Column name that will be the ValueMember
}
In my case reload() doesn't work because the asp.net controls behavior. So, to solve this issue I've used this approach, despite seems a work around.
self.clear = function () {
//location.reload(true); Doesn't work to IE neither Firefox;
//also, hash tags must be removed or no postback will occur.
window.location.href = window.location.href.replace(/#.*$/, '');
};
You can use this to continue using the type Date and a more legible code, if you preffer:
import org.apache.commons.lang.time.DateUtils;
...
Date yourDate = DateUtils.addDays(new Date(), *days here*);
Another way is to select a column with the columns
array:
In [5]: df = pd.DataFrame([[1,2], [3,4]], columns=['a', 'b'])
In [6]: df
Out[6]:
a b
0 1 2
1 3 4
In [7]: df[df.columns[0]]
Out[7]:
0 1
1 3
Name: a, dtype: int64
This works fine
@echo off
set word=table
set str=jump over the chair
set rpl=%str:chair=%%word%
echo %rpl%
To me it was a wrong deployment. Deployed properly, everything works (check my question for details).
Try using file to view the encoding details (reference):
cd directory/of/interest
file *
It produces useful output like this:
$ file *
CR6Series_stats resaved.dat: ASCII text, with very long lines, with CRLF line terminators
CR6Series_stats utf8.dat: UTF-8 Unicode (with BOM) text, with very long lines, with CRLF line terminators
CR6Series_stats.dat: ASCII text, with very long lines, with CRLF line terminators
readme.md: ASCII text, with CRLF line terminators
In a second level cache, domain hbm files can be of key mutable and value false. For example, In this domain class some of the duration in a day remains constant as the universal truth. So, it can be marked as immutable across application.
mongodump -h hostname -u dbusername -p dbpassword --db dbname --port portnumber --out /path/folder
mongodump -h hostname -u dbusername -p dbpassword --db dbname --port portnumber --out /path/folder.gz
This is because you are executing the function not referencing it. You should do:
setInterval(swapImages,1000);
You can't have 1:1 ratio.
However you can scale it from the iOS Simulator > Window > Scale
menu.
If you want to use SQL Server Management Studio, you want to install the full Oracle client, not the Instant Client. The full Oracle client is on the same download page as the Oracle database. Assuming that you are installing on a 64-bit version of Windows, I expect you want the "Oracle Database 11g Release 2 Client (11.2.0.1.0) for Microsoft Windows (x64)" download. This is several hundred MB rather than a couple of MB for the Instant Client.
background-image
instead of background
This works in Opera : http://jsfiddle.net/ZNsbU/5/
But it doesn't work in FF5 nor IE8. (yay for outdated browsers :D )
body {
background:url(http://www.google.com/intl/en_com/images/srpr/logo3w.png) 400px 200px / 600px 400px no-repeat;
}
You could do it like this :
body {
background:url(http://www.google.com/intl/en_com/images/srpr/logo3w.png) 400px 400px no-repeat;
background-size:20px 20px
}
Which works in FF5 and Opera but not in IE8.
run:
vagrant ssh-config > .ssh.config
and then in config/deploy.rb
role :web, "default"
role :app, "default"
set :use_sudo, true
set :user, 'root'
set :run_method, :sudo
# Must be set for the password prompt from git to work
default_run_options[:pty] = true
ssh_options[:forward_agent] = true
ssh_options[:config] = '.ssh.config'
You need to give the body
and the html
a height too. Otherwise, the body will only be as high as its contents (the single div), and 50% of that will be half the height of this div.
Updated fiddle: http://jsfiddle.net/j8bsS/5/
At its most basic, concatenating files from a batch file is done with 'copy'.
copy file1.txt + file2.txt + file3.txt concattedfile.txt
You need to use a back_inserter
:
std::copy(input.begin(), input.end(), std::back_inserter(output));
std::copy
doesn't add elements to the container into which you are inserting: it can't; it only has an iterator into the container. Because of this, if you pass an output iterator directly to std::copy
, you must make sure it points to a range that is at least large enough to hold the input range.
std::back_inserter
creates an output iterator that calls push_back
on a container for each element, so each element is inserted into the container. Alternatively, you could have created a sufficient number of elements in the std::vector
to hold the range being copied:
std::vector<double> output(input.size());
std::copy(input.begin(), input.end(), output.begin());
Or, you could use the std::vector
range constructor:
std::vector<double> output(input.begin(), input.end());
Following on from the answer by @karask, you could wrap the function as a helper like so:
public static bool HasProperty(ExpandoObject expandoObj,
string name)
{
return ((IDictionary<string, object>)expandoObj).ContainsKey(name);
}
In simple, Normalisation is Reduction of Redundancies.
Examples of Redundancies:
a) white spaces outside of the root/document tags(...<document></document>...)
b) white spaces within start tag (<...>) and end tag (</...>)
c) white spaces between attributes and their values (ie. spaces between key name and =")
d) superfluous namespace declarations
e) line breaks/white spaces in texts of attributes and tags
f) comments etc...
If you want to check or validate a specific UUID version, here are the corresponding regexes.
Note that the only difference is the version number, which is explained in
4.1.3. Version
chapter of UUID 4122 RFC.
The version number is the first character of the third group : [VERSION_NUMBER][0-9A-F]{3}
:
UUID v1 :
/^[0-9A-F]{8}-[0-9A-F]{4}-[1][0-9A-F]{3}-[89AB][0-9A-F]{3}-[0-9A-F]{12}$/i
UUID v2 :
/^[0-9A-F]{8}-[0-9A-F]{4}-[2][0-9A-F]{3}-[89AB][0-9A-F]{3}-[0-9A-F]{12}$/i
UUID v3 :
/^[0-9A-F]{8}-[0-9A-F]{4}-[3][0-9A-F]{3}-[89AB][0-9A-F]{3}-[0-9A-F]{12}$/i
UUID v4 :
/^[0-9A-F]{8}-[0-9A-F]{4}-[4][0-9A-F]{3}-[89AB][0-9A-F]{3}-[0-9A-F]{12}$/i
UUID v5 :
/^[0-9A-F]{8}-[0-9A-F]{4}-[5][0-9A-F]{3}-[89AB][0-9A-F]{3}-[0-9A-F]{12}$/i
Use the size
property on the UIImage instance. See the documentation for more details.
In the onCreate function, below the setContentView, add this line:
getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
The common practice is to put scripts in a discrete folder, typically at the root of the site. So, if clock.js lived here:
/js/clock.js
then you could add this code to the top of any page in your site and it would just work:
<script src="/js/clock.js" type="text/javascript"></script>
Same concept as a .jar
file in Java, it is a .zip
file with some metadata files renamed .egg
, for distributing code as bundles.
Specifically: The Internal Structure of Python Eggs
A "Python egg" is a logical structure embodying the release of a specific version of a Python project, comprising its code, resources, and metadata. There are multiple formats that can be used to physically encode a Python egg, and others can be developed. However, a key principle of Python eggs is that they should be discoverable and importable. That is, it should be possible for a Python application to easily and efficiently find out what eggs are present on a system, and to ensure that the desired eggs' contents are importable.
The
.egg
format is well-suited to distribution and the easy uninstallation or upgrades of code, since the project is essentially self-contained within a single directory or file, unmingled with any other projects' code or resources. It also makes it possible to have multiple versions of a project simultaneously installed, such that individual programs can select the versions they wish to use.
None of the video settings posted above worked in modern browsers I tested (like Firefox) using the embed
or object
elements in HTML5. For video
or audio
elements they did stop autoplay. For embed
and object
they did not.
I tested this using the embed
and object
elements using several different media types as well as HTML attributes (like autostart and autoplay). These videos always played regardless of any combination of settings in several browsers. Again, this was not an issue using the newer HTML5 video
or audio
elements, just when using embed
and object
.
It turns out the new browser settings for video "autoplay" have changed. Firefox will now ignore the autoplay
attributes on these tags and play videos anyway unless you explicitly set to "block audio and video" autoplay in your browser settings.
To do this in Firefox I have posted the settings below:
Your videos will NOT autoplay now when displaying videos in web pages using object
or embed
elements.
Add this to your section:
<script> function resizeIframe(obj) { obj.style.height = obj.contentWindow.document.body.scrollHeight + 'px'; } </script>
And change your iframe to this:
<iframe src="..." frameborder="0" scrolling="no" onload="resizeIframe(this)" />
It is posted Here
It does however use javascript, but it is simple and easy to use code that will fix your problem.
Ahem...
The short answer to your question is that you must set the height of 100% to the body and html tag, then set the height to 100% on each div element you want to make 100% the height of the page.
Actually, 100% height will not work in most design situations - this may be short but it is not a good answer. Google "any column longest" layouts. The best way is to put the left and right cols inside a wrapper div
, float the left and right cols and then float the wrapper - this makes it stretch to the height of the inner containers - then set background image on the outer wrapper. But watch for any horizontal margins on the floated elements in case you get the IE "double margin float bug".
The other answers detail the reason for the error. A possible cause (to check) may be your class has a variable and method with the same name, which you then call. Python accesses the variable as a callable - with ()
.
e.g. Class A defines self.a
and self.a()
:
>>> class A:
... def __init__(self, val):
... self.a = val
... def a(self):
... return self.a
...
>>> my_a = A(12)
>>> val = my_a.a()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'int' object is not callable
>>>
Something a little shorter in syntax but taking what the others have already stated.
int num1, num2 = num1 = 1;
sed is a stream editor. I would say try man sed.If you didn't find this man page in your system refer this URL:
We can use iterator to filter out the array entries instead of creating a new Array.
'public static void removeNullsFrom(JSONArray array) throws JSONException {
if (array != null) {
Iterator<Object> iterator = array.iterator();
while (iterator.hasNext()) {
Object o = iterator.next();
if (o == null || o == JSONObject.NULL) {
iterator.remove();
}
}
}
}'
Use the fact that awk
splits the lines in fields based on a field separator, that you can define. Hence, defining the field separator to /
you can say:
awk -F "/" '{print $NF}' input
as NF
refers to the number of fields of the current record, printing $NF
means printing the last one.
So given a file like this:
/home/parent/child1/child2/child3/filename
/home/parent/child1/child2/filename
/home/parent/child1/filename
This would be the output:
$ awk -F"/" '{print $NF}' file
filename
filename
filename
Uninstall homebrew:
ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/uninstall)"
Then reinstall
ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)"
Warning: This script will remove: /Library/Caches/Homebrew/ - thks benjaminsila
If anyone is looking for a VB.Net answer (as I was initially), here it is:
Public Function IsSatisfied() As Expression(Of Func(Of Charity, String, String, Boolean))
Return Function(charity, name, referenceNumber) (String.IsNullOrWhiteSpace(name) Or
charity.registeredName.ToLower().Contains(name.ToLower()) Or
charity.alias.ToLower().Contains(name.ToLower()) Or
charity.charityId.ToLower().Contains(name.ToLower())) And
(String.IsNullOrEmpty(referenceNumber) Or
charity.charityReference.ToLower().Contains(referenceNumber.ToLower()))
End Function
In drawable I use this xml code to define the border and background:
<shape xmlns:android="http://schemas.android.com/apk/res/android">
<stroke android:width="4dp" android:color="#D8FDFB" />
<padding android:left="7dp" android:top="7dp"
android:right="7dp" android:bottom="7dp" />
<corners android:radius="4dp" />
<solid android:color="#f0600000"/>
</shape>
I'm not sure you have gotten past this yet, but I had to work on something very similar today and I got your fiddle working like you are asking, basically what I did was make another table row under it, and then used the accordion control. I tried using just collapse but could not get it working and saw an example somewhere on SO that used accordion.
Here's your updated fiddle: http://jsfiddle.net/whytheday/2Dj7Y/11/
Since I need to post code here is what each collapsible "section" should look like ->
<tr data-toggle="collapse" data-target="#demo1" class="accordion-toggle">
<td>1</td>
<td>05 May 2013</td>
<td>Credit Account</td>
<td class="text-success">$150.00</td>
<td class="text-error"></td>
<td class="text-success">$150.00</td>
</tr>
<tr>
<td colspan="6" class="hiddenRow">
<div class="accordion-body collapse" id="demo1">Demo1</div>
</td>
</tr>
in my case i just changed spring.postgresql.jdbc.url that contained IPV4, i changed it to 127.0.0.1
For what it's worth I was having the same issue when passing app
into onRequest
. I realized the issue was a trailing slash on the request url for the firebase function. Express was looking for '/'
but I didn't have the trailing slash on the function [project-id].cloudfunctions.net/[function-name]
. The CORS error was a false negative. When I added the trailing slash, I got the response I was expecting.
The following solution worked for me:
brew install python2
It also upgraded pip
to version 1.10.1
As mentioned above, be sure that you don't set any id fields which are supposed to be auto-generated.
To cause this problem during testing, make sure that the db 'sees' aka flush this SQL, otherwise everything may seem fine when really its not.
I encountered this problem when inserting my parent with a child into the db:
The 3. statement failed. Indeed the entry with the autogenerated ID (by Hibernate) was not in the table as a trigger changed the ID upon each insertion, thus letting the update fail with no matching row found.
Since the table can be updated without any Hibernate I added a check whether the ID is null and only fill it in then to the trigger.
Try to add this lines to the top of your settings file:
import django
django.setup()
And if this will not help you try to remove third-party applications from your installed apps list one-by-one.
we can check it on submit or we can make change event of that control
var fileInput = document.getElementById('file');
var filePath = fileInput.value;
var allowedExtensions = /(\.jpeg|\.JPEG|\.gif|\.GIF|\.png|\.PNG)$/;
if (filePath != "" && !allowedExtensions.exec(filePath)) {
alert('Invalid file extention pleasse select another file');
fileInput.value = '';
return false;
}
Try ReoScript, an open-source JavaScript interpreter implemented in C#.
ReoScript makes your application can execute JavaScript. It has a wide variety of extension methons such as SetVariable, Function Extension, using CLR Type, .Net Event Binding and etc.
Hello World:
ScriptRunningMachine srm = new ScriptRunningMachine();
srm.Run(" alert('hello world!'); ");
And here is an example of script that creates a winform and show it.
import System.Windows.Forms.*; // import namespace
var f = new Form(); // create form
f.click = function() { f.close(); }; // close when user clicked on form
f.show(); // show
Try this code:
final File f = new File(MyClass.class.getProtectionDomain().getCodeSource().getLocation().getPath());
replace 'MyClass
' with your class containing the main method.
Alternatively you can also use
System.getProperty("java.class.path")
Above mentioned System property provides
Path used to find directories and JAR archives containing class files. Elements of the class path are separated by a platform-specific character specified in the path.separator property.
If you have headers in the markdown files, you can directly link them in the file.
Markdown Header -
## The Header
this will generate an implicit id #the-header
(replace internal spaces with hyphens and make lowercase).
To navigate to this id, you can create the link like this:
[Link to Header](#the-header)
This is equivalent to:
<a href="#the-header">Link to Header</a>
Please note the reference's name is a lower-case #header
.
You can use dict.pop
:
mydict.pop("key", None)
Note that if the second argument, i.e. None
is not given, KeyError
is raised if the key is not in the dictionary. Providing the second argument prevents the conditional exception.
Yes, it's doable due to jQuery's noconflict mode. http://blog.nemikor.com/2009/10/03/using-multiple-versions-of-jquery/
<!-- load jQuery 1.1.3 -->
<script type="text/javascript" src="http://example.com/jquery-1.1.3.js"></script>
<script type="text/javascript">
var jQuery_1_1_3 = $.noConflict(true);
</script>
<!-- load jQuery 1.3.2 -->
<script type="text/javascript" src="http://example.com/jquery-1.3.2.js"></script>
<script type="text/javascript">
var jQuery_1_3_2 = $.noConflict(true);
</script>
Then, instead of $('#selector').function();
, you'd do jQuery_1_3_2('#selector').function();
or jQuery_1_1_3('#selector').function();
.
As of 2020, my approach is to use the material-icons-font package. It simplifies the usage of Google's material-design-icons package and the community based material-design-icons-iconfont.
Install the package. npm install material-icons-font --save
Add the path of the package's CSS file to the style property of your project's angular.json file.
...
"styles": [
"./node_modules/material-icons-font/material-icons-font.css"
],
...
If using SCSS, copy content below to the top of your styles.scss file.
@import '~material-icons-font/sass/variables';
@import '~material-icons-font/sass/mixins';
$MaterialIcons_FontPath: "~material-icons-font/fonts";
@import '~material-icons-font/sass/main';
@import '~material-icons-font/sass/Regular';
Use the icons in the HTML file of your project.
// Using icon tag
<i class="material-icons">face</i>
<i class="material-icons md-48">face</i>
<i class="material-icons md-light md-inactive">face</i>
// Using Angular Material's <mat-icon> tag
<mat-icon>face</mat-icon>
<mat-icon>add_circle</mat-icon>
<mat-icon>add_circle_outline</mat-icon>
Icons from @angular/material tend to break when developing offline. Adding material-icons-font package in conjunction with @angular/material allows you to use the tag while developing offline.
Random URL and filename string safe (1 liner)
Crypto.randomBytes(48).toString('base64').replace(/\+/g, '-').replace(/\//g, '_').replace(/\=/g, '');
Another solution with your own message in exception.
import os
try:
os.remove(filename)
except:
print("Not able to delete the file %s" % filename)
Please note that this article: https://medium.com/the-web-tub/supporting-iphone-x-for-mobile-web-cordova-app-using-onsen-ui-f17a4c272fcd has different sizes than above and cordova plugin page:
Default@2x~iphone~anyany.png (= 1334x1334 = 667x667@2x)
Default@2x~iphone~comany.png (= 750x1334 = 375x667@2x)
Default@2x~iphone~comcom.png (= 750x750 = 375x375@2x)
Default@3x~iphone~anyany.png (= 2436x2436 = 812x812@3x)
Default@3x~iphone~anycom.png (= 2436x1242 = 812x414@3x)
Default@3x~iphone~comany.png (= 1242x2436 = 414x812@3x)
Default@2x~ipad~anyany.png (= 2732x2732 = 1366x1366@2x)
Default@2x~ipad~comany.png (= 1278x2732 = 639x1366@2x)
I resized images as above and updated ios
platform and cordova-plugin-splashscreen
to latest and the flash to white screen after a second issue was fixed. However the initial spash image has a white border at bottom now.
I see many (all) posts above relying on LBound
/UBound
calls upon yet potentially uninitialized VBA dynamic array, what causes application's inevitable death ...
Erratic code:
Dim x As Long
Dim arr1() As SomeType
...
x = UBound(arr1) 'crashes
Correct code:
Dim x As Long
Dim arr1() As SomeType
...
ReDim Preserve arr1(0 To 0)
...
x = UBound(arr1)
... i.e. any code where Dim arr1()
is followed immediatelly by LBound(arr1)
/UBound(arr1)
calls without ReDim arr1(...)
in between, crashes. The roundabout is to employ an On Error Resume Next
and check the Err.Number
right after the LBound(arr1)
/UBound(arr1)
call - it should be 0 if the array is initialized, otherwise non-zero. As there is some VBA built-in misbehavior, the further check of array's limits is needed. Detailed explanation may everybody read at Chip Pearson's website (which should be celebrated as a Mankind Treasure Of VBA Wisdom ...)
Heh, that's my first post, believe it is legible.
Instead of override you can add another class to the element and then you have an extra abilities. for example:
HTML
<div class="style1 style2"></div>
CSS
//only style for the first stylesheet
.style1 {
width: 100%;
}
//only style for second stylesheet
.style2 {
width: 50%;
}
//override all
.style1.style2 {
width: 70%;
}
Ya, though w3c says the right click can be detected by the click event, onClick is not triggered through right click in usual browsers.
In fact, right click only trigger onMouseDown onMouseUp and onContextMenu.
Thus, you can regard "onContextMenu" as the right click event. It's an HTML5.0 standard.
Try the following code.
TimeSpan CurrentTime = DateTime.Now.TimeOfDay;
Get the time of the day and assign it to TimeSpan
variable.
Just try this:
Bitmap bitmap = BitmapFactory.decodeFile("/path/images/image.jpg");
ByteArrayOutputStream blob = new ByteArrayOutputStream();
bitmap.compress(CompressFormat.PNG, 0 /* Ignored for PNGs */, blob);
byte[] bitmapdata = blob.toByteArray();
If bitmapdata
is the byte array then getting Bitmap
is done like this:
Bitmap bitmap = BitmapFactory.decodeByteArray(bitmapdata, 0, bitmapdata.length);
Returns the decoded Bitmap
, or null
if the image could not be decoded.
In jQuery it would be as simple as $('#yourDivID').empty()
See the documentation.
I tried some of your solutions. This one :
margin: 0px -100%;
padding: 0 100%;
is by far the best, since we don't need extra css for smaller screen. I made a codePen to show the results : I used a parent div with a background image, and a child divon div with inner content.
You can invoke reflections and also, set order of sequence for getter for values through annotations
public class Student {
private String grade;
private String name;
private String id;
private String gender;
private Method[] methods;
@Retention(RetentionPolicy.RUNTIME)
public @interface Order {
int value();
}
/**
* Sort methods as per Order Annotations
*
* @return
*/
private void sortMethods() {
methods = Student.class.getMethods();
Arrays.sort(methods, new Comparator<Method>() {
public int compare(Method o1, Method o2) {
Order or1 = o1.getAnnotation(Order.class);
Order or2 = o2.getAnnotation(Order.class);
if (or1 != null && or2 != null) {
return or1.value() - or2.value();
}
else if (or1 != null && or2 == null) {
return -1;
}
else if (or1 == null && or2 != null) {
return 1;
}
return o1.getName().compareTo(o2.getName());
}
});
}
/**
* Read Elements
*
* @return
*/
public void readElements() {
int pos = 0;
/**
* Sort Methods
*/
if (methods == null) {
sortMethods();
}
for (Method method : methods) {
String name = method.getName();
if (name.startsWith("get") && !name.equalsIgnoreCase("getClass")) {
pos++;
String value = "";
try {
value = (String) method.invoke(this);
}
catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException e) {
e.printStackTrace();
}
System.out.println(name + " Pos: " + pos + " Value: " + value);
}
}
}
// /////////////////////// Getter and Setter Methods
/**
* @param grade
* @param name
* @param id
* @param gender
*/
public Student(String grade, String name, String id, String gender) {
super();
this.grade = grade;
this.name = name;
this.id = id;
this.gender = gender;
}
/**
* @return the grade
*/
@Order(value = 4)
public String getGrade() {
return grade;
}
/**
* @param grade the grade to set
*/
public void setGrade(String grade) {
this.grade = grade;
}
/**
* @return the name
*/
@Order(value = 2)
public String getName() {
return name;
}
/**
* @param name the name to set
*/
public void setName(String name) {
this.name = name;
}
/**
* @return the id
*/
@Order(value = 1)
public String getId() {
return id;
}
/**
* @param id the id to set
*/
public void setId(String id) {
this.id = id;
}
/**
* @return the gender
*/
@Order(value = 3)
public String getGender() {
return gender;
}
/**
* @param gender the gender to set
*/
public void setGender(String gender) {
this.gender = gender;
}
/**
* Main
*
* @param args
* @throws IOException
* @throws SQLException
* @throws InvocationTargetException
* @throws IllegalArgumentException
* @throws IllegalAccessException
*/
public static void main(String args[]) throws IOException, SQLException, IllegalAccessException,
IllegalArgumentException, InvocationTargetException {
Student student = new Student("A", "Anand", "001", "Male");
student.readElements();
}
}
Output when sorted
getId Pos: 1 Value: 001
getName Pos: 2 Value: Anand
getGender Pos: 3 Value: Male
getGrade Pos: 4 Value: A
"Validation injection without submit looping":
I just want to check reCaptcha and some other stuff before HTML5 validation, so I did something like that (the validation function returns true or false):
$(document).ready(function(){
var application_form = $('form#application-form');
application_form.on('submit',function(e){
if(application_form_extra_validation()===true){
return true;
}
e.preventDefault();
});
});
Here's what I've been doing to cope with the situation.
I use global imports on a new test class.
import static org.junit.Assert.*;
import static org.mockito.Mockito.*;
import static org.mockito.Matchers.*;
When you are finished writing your test and need to commit, you just CTRL+SHIFT+O to organize the packages. For example, you may just be left with:
import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import static org.mockito.Matchers.anyString;
This allows you to code away without getting 'stuck' trying to find the correct package to import.