You are trying to use the string as a function:
"Your new price is: $"(float(price) * 0.1)
Because there is nothing between the string literal and the (..)
parenthesis, Python interprets that as an instruction to treat the string as a callable and invoke it with one argument:
>>> "Hello World!"(42)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'str' object is not callable
Seems you forgot to concatenate (and call str()
):
easygui.msgbox("Your new price is: $" + str(float(price) * 0.1))
The next line needs fixing as well:
easygui.msgbox("Your new price is: $" + str(float(price) * 0.2))
Alternatively, use string formatting with str.format()
:
easygui.msgbox("Your new price is: ${:.2f}".format(float(price) * 0.1))
easygui.msgbox("Your new price is: ${:.2f}".format(float(price) * 0.2))
where {:02.2f}
will be replaced by your price calculation, formatting the floating point value as a value with 2 decimals.
Since this question is from 4 years ago new things have been implemented and among them there is a new function plt.subplots
which is very convenient:
fig, axes = plot.subplots(nrows=2, ncols=3, sharex=True, sharey=True)
where axes
is a numpy.ndarray
of AxesSubplot objects, making it very convenient to go through the different subplots just using array indices [i,j]
.
I was using Postman to test my Laravel API.
I received an error that stated
"SQLSTATE[42S22]: Column not found: 1054 Unknown column" because Laravel was trying to automatically create two columns "created_at" and "updated_at".
I had to enter public $timestamps = false;
to my model. Then, I tested again with Postman and saw that an "id" = 0
variable was being created in my database.
I finally had to add public $incrementing false;
to fix my API.
you can save the path of the image in the database or save the image itself as a BLOB ( binary - array of bytes)..it depends on the case you got,if your application is a web application,then saving the path of the image is much better.but if you got a client based application that connects to a centralized database,then you must save it as binary.
As part of htmlAttributes,e.g.
Html.BeginForm(
action, controller, FormMethod.Post, new { enctype="multipart/form-data"})
Or you can pass null
for action and controller to get the same default target as for BeginForm() without any parameters:
Html.BeginForm(
null, null, FormMethod.Post, new { enctype="multipart/form-data"})
I Feel Eclipse IDE is more suitable for android applications rather than other IDEs. Because its providing us more than five perspectives which will make our project flexible and ease.You may try Eclipse ides starts with 3.6 and above will provide you better performance.
Eclipse_jee_indigo
Eclipse_java_indigo
Eclipse_classic
The above eclipses are belongs to the version3.7.2 which are all latest and supports all kind of access.
JavaScript has replace()
method of String object for replacing substrings. This method can have two arguments. The first argument can be a string or a regular expression pattern (regExp object) and the second argument can be a string or a function. An example of replace()
method having both string arguments is shown below.
var text = 'one, two, three, one, five, one';
var new_text = text.replace('one', 'ten');
console.log(new_text) //ten, two, three, one, five, one
Note that if the first argument is the string, only the first occurrence of the substring is replaced as in the example above. To replace all occurrences of the substring you need to provide a regular expression with a g
(global) flag. If you do not provide the global flag, only the first occurrence of the substring will be replaced even if you provide the regular expression as the first argument. So let's replace all occurrences of one
in the above example.
var text = 'one, two, three, one, five, one';
var new_text = text.replace(/one/g, 'ten');
console.log(new_text) //ten, two, three, ten, five, ten
Note that you do not wrap the regular expression pattern in quotes which will make it a string not a regExp object. To do a case insensitive replacement you need to provide additional flag i
which makes the pattern case-insensitive. In that case the above regular expression will be /one/gi
. Notice the i
flag added here.
If the second argument has a function and if there is a match the function is passed with three arguments. The arguments the function gets are the match, position of the match and the original text. You need to return what that match should be replaced with. For example,
var text = 'one, two, three, one, five, one';
var new_text = text.replace(/one/g, function(match, pos, text){
return 'ten';
});
console.log(new_text) //ten, two, three, ten, five, ten
You can have more control over the replacement text using a function as the second argument.
Ok I have found a solution. The problem is that the site uses SSLv3. And I know that there are some problems in the openssl module. Some time ago I had the same problem with the SSL versions.
<?php
function getSSLPage($url) {
$ch = curl_init();
curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_SSLVERSION,3);
$result = curl_exec($ch);
curl_close($ch);
return $result;
}
var_dump(getSSLPage("https://eresearch.fidelity.com/eresearch/evaluate/analystsOpinionsReport.jhtml?symbols=api"));
?>
When you set the SSL Version with curl to v3 then it works.
Edit:
Another problem under Windows is that you don't have access to the certificates. So put the root certificates directly to curl.
http://curl.haxx.se/docs/caextract.html
here you can download the root certificates.
curl_setopt($ch, CURLOPT_CAINFO, __DIR__ . "/certs/cacert.pem");
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, true);
Then you can use the CURLOPT_SSL_VERIFYPEER
option with true
otherwise you get an error.
A CDATA section is "a section of element content that is marked for the parser to interpret as only character data, not markup."
Syntactically, it behaves similarly to a comment:
<exampleOfAComment>
<!--
Since this is a comment
I can use all sorts of reserved characters
like > < " and &
or write things like
<foo></bar>
but my document is still well-formed!
-->
</exampleOfAComment>
... but it is still part of the document:
<exampleOfACDATA>
<![CDATA[
Since this is a CDATA section
I can use all sorts of reserved characters
like > < " and &
or write things like
<foo></bar>
but my document is still well formed!
]]>
</exampleOfACDATA>
Try saving the following as a .xhtml
file (not .html
) and open it using FireFox (not Internet Explorer) to see the difference between the comment and the CDATA section; the comment won't appear when you look at the document in a browser, while the CDATA section will:
<?xml version="1.0" encoding="UTF-8" standalone="no" ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en" >
<head>
<title>CDATA Example</title>
</head>
<body>
<h2>Using a Comment</h2>
<div id="commentExample">
<!--
You won't see this in the document
and can use reserved characters like
< > & "
-->
</div>
<h2>Using a CDATA Section</h2>
<div id="cdataExample">
<![CDATA[
You will see this in the document
and can use reserved characters like
< > & "
]]>
</div>
</body>
</html>
Something to take note of with CDATA sections is that they have no encoding, so there's no way to include the string ]]>
in them. Any character data which contains ]]>
will have to - as far as I know - be a text node instead. Likewise, from a DOM manipulation perspective you can't create a CDATA section which includes ]]>
:
var myEl = xmlDoc.getElementById("cdata-wrapper");
myEl.appendChild(xmlDoc.createCDATASection("This section cannot contain ]]>"));
This DOM manipulation code will either throw an exception (in Firefox) or result in a poorly structured XML document: http://jsfiddle.net/9NNHA/
If you are using Jackson, then you can use the @JsonProperty
annotation to customize the name of a given JSON property.
Therefore, you just have to annotate the entity fields with the @JsonProperty
annotation and provide a custom JSON property name, like this:
@Entity
public class City {
@Id
@JsonProperty("value")
private Long id;
@JsonProperty("label")
private String name;
//Getters and setters omitted for brevity
}
JSON-B is the standard binding layer for converting Java objects to and from JSON. If you are using JSON-B, then you can override the JSON property name via the @JsonbProperty
annotation:
@Entity
public class City {
@Id
@JsonbProperty("value")
private Long id;
@JsonbProperty("label")
private String name;
//Getters and setters omitted for brevity
}
A more cleaner and dynamic way without hardcoding any pixel values in the code.
I wanted to position a dialog (which I inflate on the fly) exactly below a clicked button.
and solved it this way :
// get the yoffset of the position where your View has to be placed
final int yoffset = < calculate the position of the view >
// position using top margin
if(myView.getLayoutParams() instanceof MarginLayoutParams) {
((MarginLayoutParams) myView.getLayoutParams()).topMargin = yOffset;
}
However you have to make sure the parent layout of myView
is an instance of RelativeLayout
.
more complete code :
// identify the button
final Button clickedButton = <... code to find the button here ...>
// inflate the dialog - the following style preserves xml layout params
final View floatingDialog =
this.getLayoutInflater().inflate(R.layout.floating_dialog,
this.floatingDialogContainer, false);
this.floatingDialogContainer.addView(floatingDialog);
// get the buttons position
final int[] buttonPos = new int[2];
clickedButton.getLocationOnScreen(buttonPos);
final int yOffset = buttonPos[1] + clickedButton.getHeight();
// position using top margin
if(floatingDialog.getLayoutParams() instanceof MarginLayoutParams) {
((MarginLayoutParams) floatingDialog.getLayoutParams()).topMargin = yOffset;
}
This way you can still expect the target view to adjust to any layout parameters set using layout XML files, instead of hardcoding those pixels/dps in your Java code.
For those who stuck at this error as me and nothing helped from above: check if problem folder from error.log actually exists on your server. Mine was generated automatically by Django in wrong place (was messed with static root, then manage.py collectstatic
). Have no idea why one can not name errors correctly.
The C++20 draft contains the convenience function std::erase_if
.
So you can use that function to do it as a one-liner.
std::map<K, V> map_obj;
//calls needs_removing for each element and erases it, if true was reuturned
std::erase_if(map_obj,needs_removing);
//if you need to pass only part of the key/value pair
std::erase_if(map_obj,[](auto& kv){return needs_removing(kv.first);});
The Java Language Specification(1) describes how try-catch-finally
is executed.
Having no catch is equivalent to not having a catch able to catch the given Throwable.
- If execution of the try block completes abruptly because of a throw of a value V, then there is a choice:
- If the run-time type of V is assignable to the parameter of any catch clause of the try statement, then …
…- If the run-time type of V is not assignable to the parameter of any catch clause of the try statement, then the finally block is executed. Then there is a choice:
- If the finally block completes normally, then the try statement completes abruptly because of a throw of the value V.
- If the finally block completes abruptly for reason S, then the try statement completes abruptly for reason S (and the throw of value V is discarded and forgotten).
If you have GNU extensions, you can use sed's \L (lower entire match, or until \L [lower] or \E [end - toggle casing off] is reached), like so:
sed 's/.*/\L&/' <input >output
Note: '&' means the full match pattern.
As a side note, GNU extensions include \U (upper), \u (upper next character of match), \l (lower next character of match). For example, if you wanted to camelcase a sentence:
$ sed -r 's/\w+/\u&/g' <<< "Now is the time for all good men..." # Camel Case
Now Is The Time For All Good Men...
Note: Since the assumption is we have GNU extensions, we can also use the dash-r (extended regular expressions) option, which allows \w (word character) and relieves you of having to escape the capturing parenthesis and one-or-more quantifier (+). (Aside: \W [non-word], \s [whitespace], \S [non-whitespace]
are also supported with dash-r, but \d [digit]
and \D [non-digit]
are not.)
It worked for by following process:
Add Reference:
system.net
system.web
also, include the namespace
using system.net
using system.web
Searched on the go-nuts email list and found a solution posted by Peter Froehlich on 11/15/2009.
package main
import "fmt"
func main() {
dict := map[string]int {"foo" : 1, "bar" : 2}
value, ok := dict["baz"]
if ok {
fmt.Println("value: ", value)
} else {
fmt.Println("key not found")
}
}
Or, more compactly,
if value, ok := dict["baz"]; ok {
fmt.Println("value: ", value)
} else {
fmt.Println("key not found")
}
Note, using this form of the if
statement, the value
and ok
variables are only visible inside the if
conditions.
I can't remember where I came across this script, but I've been using it with XCloner to move my WP multisites.
<?php
// Setup the associative array for replacing the old string with new string
$replace_array = array( 'FIND' => 'REPLACE', 'FIND' => 'REPLACE');
$mysql_link = mysql_connect( 'localhost', 'USERNAME', 'PASSWORD' );
if( ! $mysql_link) {
die( 'Could not connect: ' . mysql_error() );
}
$mysql_db = mysql_select_db( 'DATABASE', $mysql_link );
if(! $mysql_db ) {
die( 'Can\'t select database: ' . mysql_error() );
}
// Traverse all tables
$tables_query = 'SHOW TABLES';
$tables_result = mysql_query( $tables_query );
while( $tables_rows = mysql_fetch_row( $tables_result ) ) {
foreach( $tables_rows as $table ) {
// Traverse all columns
$columns_query = 'SHOW COLUMNS FROM ' . $table;
$columns_result = mysql_query( $columns_query );
while( $columns_row = mysql_fetch_assoc( $columns_result ) ) {
$column = $columns_row['Field'];
$type = $columns_row['Type'];
// Process only text-based columns
if( strpos( $type, 'char' ) !== false || strpos( $type, 'text' ) !== false ) {
// Process all replacements for the specific column
foreach( $replace_array as $old_string => $new_string ) {
$replace_query = 'UPDATE ' . $table .
' SET ' . $column . ' = REPLACE(' . $column .
', \'' . $old_string . '\', \'' . $new_string . '\')';
mysql_query( $replace_query );
}
}
}
}
}
mysql_free_result( $columns_result );
mysql_free_result( $tables_result );
mysql_close( $mysql_link );
echo 'Done!';
?>
Use one way flow syntax property binding:
<div [innerHTML]="comment"></div>
From angular docs: "Angular recognizes the value as unsafe and automatically sanitizes it, which removes the <script>
tag but keeps safe content such as the <b>
element."
select inet_server_port();
gives you the port of the server.
The primitive data types prefixed with "u" are unsigned versions with the same bit sizes. Effectively, this means they cannot store negative numbers, but on the other hand they can store positive numbers twice as large as their signed counterparts. The signed counterparts do not have "u" prefixed.
The limits for int (32 bit) are:
int: –2147483648 to 2147483647
uint: 0 to 4294967295
And for long (64 bit):
long: -9223372036854775808 to 9223372036854775807
ulong: 0 to 18446744073709551615
Some compilers support compound literals as an extention, allowing this construct:
Customer customerRecords[2];
customerRecords[0] = (Customer){25, "Bob Jones"};
customerRecords[1] = (Customer){26, "Jim Smith"};
But it's rather unportable.
In modern browsers you can use the Map
data structure instead of a object.
A Map object can iterate its elements in insertion order...
Try this one for current selection:
Sub A_SelectAllMakeTable2()
Dim tbl As ListObject
Set tbl = ActiveSheet.ListObjects.Add(xlSrcRange, Selection, , xlYes)
tbl.TableStyle = "TableStyleMedium15"
End Sub
or equivalent of your macro (for Ctrl+Shift+End range selection):
Sub A_SelectAllMakeTable()
Dim tbl As ListObject
Dim rng As Range
Set rng = Range(Range("A1"), Range("A1").SpecialCells(xlLastCell))
Set tbl = ActiveSheet.ListObjects.Add(xlSrcRange, rng, , xlYes)
tbl.TableStyle = "TableStyleMedium15"
End Sub
If the project was compiling just before, you can try to clear the cache using :
./gradlew clean
or
./gradlew cleanBuildCache
or for windows
gradlew cleanBuildCache
Since in css3 one might set multiple background images setting "none" will only create a new layer and hide nothing.
http://www.css3.info/preview/multiple-backgrounds/ http://www.w3.org/TR/css3-background/#backgrounds
I have not found a solution yet...
$(this).find(".bgHeaderH2").html();
or
$(this).find(".bgHeaderH2").text();
A basic but simple to understand answer:
Sub Example()
ActiveSheet.Unprotect
Program logic...
ActiveSheet.Protect
End Sub
I am running an Iphone 8+ and VMWare macOS High Sierra on a Windows 10 machine.
I went through dozens of troubleshooting posts, and the none of them, excluding setting your VMs USBs to 2.0, helped. Through trial and error, and a decent amount of liquor, I have figured it out.
SOLUTION:
Do these things, in this order:
With the VM off, go to your settings for whichever machine you're using, and change the USBs to 2.0. You can find this in the same menu that you allocated your ram and cores
Make sure your phone is plugged in, and turned off.
Boot up the VM, macOS.
Turn Phone on when mac is booted
Open Xcode
Below is answering the original first question:
Should I use
dict
orOrderedDict
in Python 3.6?
I think this sentence from the documentation is actually enough to answer your question
The order-preserving aspect of this new implementation is considered an implementation detail and should not be relied upon
dict
is not explicitly meant to be an ordered collection, so if you want to stay consistent and not rely on a side effect of the new implementation you should stick with OrderedDict
.
Make your code future proof :)
There's a debate about that here.
EDIT: Python 3.7 will keep this as a feature see
As I haven't seen it at serverfault yet, and the answer is quite simple:
Change:
ssh -f -L3310:remote.server:3306 [email protected] -N
To:
ssh -f -L3310:localhost:3306 [email protected] -N
And change:
mysqldump -P 3310 -h localhost -u mysql_user -p database_name table_name
To:
mysqldump -P 3310 -h 127.0.0.1 -u mysql_user -p database_name table_name
(do not use localhost, it's one of these 'special meaning' nonsense that probably connects by socket rather then by port)
edit: well, to elaborate: if host is set to localhost
, a configured (or default) --socket
option is assumed. See the manual for which option files are sought / used. Under Windows, this can be a named pipe.
If you want to add wsdl reference in .Net Core project, there is no "Add web reference" option.
To add the wsdl reference go to Solution Explorer, right-click on the References project item and then click on the Add Connected Service option.
Then click 'Microsoft WCF Web Service Reference':
Enter the file path into URI text box and import the WSDL:
It will generate a simple, very basic WCF client and you to use it something like this:
YourServiceClient client = new YourServiceClient();
client.DoSomething();
You should make x
and y
numpy arrays, not lists:
x = np.array([0.46,0.59,0.68,0.99,0.39,0.31,1.09,
0.77,0.72,0.49,0.55,0.62,0.58,0.88,0.78])
y = np.array([0.315,0.383,0.452,0.650,0.279,0.215,0.727,0.512,
0.478,0.335,0.365,0.424,0.390,0.585,0.511])
With this change, it produces the expect plot. If they are lists, m * x
will not produce the result you expect, but an empty list. Note that m
is anumpy.float64
scalar, not a standard Python float
.
I actually consider this a bit dubious behavior of Numpy. In normal Python, multiplying a list with an integer just repeats the list:
In [42]: 2 * [1, 2, 3]
Out[42]: [1, 2, 3, 1, 2, 3]
while multiplying a list with a float gives an error (as I think it should):
In [43]: 1.5 * [1, 2, 3]
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-43-d710bb467cdd> in <module>()
----> 1 1.5 * [1, 2, 3]
TypeError: can't multiply sequence by non-int of type 'float'
The weird thing is that multiplying a Python list with a Numpy scalar apparently works:
In [45]: np.float64(0.5) * [1, 2, 3]
Out[45]: []
In [46]: np.float64(1.5) * [1, 2, 3]
Out[46]: [1, 2, 3]
In [47]: np.float64(2.5) * [1, 2, 3]
Out[47]: [1, 2, 3, 1, 2, 3]
So it seems that the float gets truncated to an int, after which you get the standard Python behavior of repeating the list, which is quite unexpected behavior. The best thing would have been to raise an error (so that you would have spotted the problem yourself instead of having to ask your question on Stackoverflow) or to just show the expected element-wise multiplication (in which your code would have just worked). Interestingly, addition between a list and a Numpy scalar does work:
In [69]: np.float64(0.123) + [1, 2, 3]
Out[69]: array([ 1.123, 2.123, 3.123])
I found this table super useful for deciding when to use different types of Contexts:
Original article here.
createOrReplaceTempView
creates (or replaces if that view name already exists) a lazily evaluated "view" that you can then use like a hive table in Spark SQL. It does not persist to memory unless you cache the dataset that underpins the view.
scala> val s = Seq(1,2,3).toDF("num")
s: org.apache.spark.sql.DataFrame = [num: int]
scala> s.createOrReplaceTempView("nums")
scala> spark.table("nums")
res22: org.apache.spark.sql.DataFrame = [num: int]
scala> spark.table("nums").cache
res23: org.apache.spark.sql.Dataset[org.apache.spark.sql.Row] = [num: int]
scala> spark.table("nums").count
res24: Long = 3
The data is cached fully only after the .count
call. Here's proof it's been cached:
Related SO: spark createOrReplaceTempView vs createGlobalTempView
Relevant quote (comparing to persistent table): "Unlike the createOrReplaceTempView command, saveAsTable will materialize the contents of the DataFrame and create a pointer to the data in the Hive metastore." from https://spark.apache.org/docs/latest/sql-programming-guide.html#saving-to-persistent-tables
Note : createOrReplaceTempView
was formerly registerTempTable
✗
✗
✘
✘
✕
✕
✖
✖
If you run the Get-Item or Get-ChildItem commands these will output System.IO.FileInfo and System.IO.DirectoryInfo objects that contain this information e.g.:
Get-Item c:\folder | Format-List
Or you can access the property directly like so:
Get-Item c:\folder | Foreach {$_.LastWriteTime}
To start to filter folders & files based on last write time you can do this:
Get-ChildItem c:\folder | Where{$_.LastWriteTime -gt (Get-Date).AddDays(-7)}
This is the numerical representation of the date. The thing you get when referring to dates from formulas like that.
You'll have to do:
= A1 & TEXT(A2, "mm/dd/yyyy")
The biggest problem here is that the format specifier is locale-dependent. It will not work/produce not what expected if the file is opened with a differently localized Excel.
Now, you could have a user-defined function:
public function AsDisplayed(byval c as range) as string
AsDisplayed = c.Text
end function
and then
= A1 & AsDisplayed(A2)
But then there's a bug (feature?) in Excel because of which the .Text
property is suddenly not available during certain stages of the computation cycle, and your formulas display #VALUE
instead of what they should.
That is, it's bad either way.
Use ON DUPLICATE KEY UPDATE ...
,
Negative : because the UPDATE
uses resources for the second action.
Use INSERT IGNORE ...
,
Negative : MySQL will not show any errors if something goes wrong, so you cannot handle the errors. Use it only if you don’t care about the query.
June 2018 Issue fixed by using a different appcompact version. Use these codes onto your project dependencies...
In build.gradle(Module: app) add this dependency
implementation 'com.android.support:appcompat-v7:28.0.0-alpha1'
Happy Coding... :)
Building PhoneGap Android app for deployment to the Google Play Store
These steps would work for Cordova, PhoneGap or Ionic. The only difference would be, wherever a call to cordova
is placed, replace it with phonegap
or ionic
, for your particular scenario.
Once you are done with the development and are ready to deploy, follow these steps:
Open a command line window (Terminal on macOS and Linux OR Command Prompt on Windows).
Head over to the /path/to/your/project/, which we would refer to as the Project Root.
While at the project root, remove the "Console" plugin from your set of plugins.
The command is: cordova plugin rm cordova-plugin-console
While still at the project root, use the cordova build command to create an APK for release distribution.
The command is: cordova build --release android
The above process creates a file called android-release-unsigned.apk
in the folder ProjectRoot/platforms/android/build/outputs/apk/
Sign and align the APK using the instructions at https://developer.android.com/studio/publish/app-signing.html#signing-manually
At the end of this step the APK which you get can be uploaded to the Play Store.
Note: As a newbie or a beginner, the last step may be a bit confusing as it was to me. One may run into a few issues and may have some questions as to what these commands are and where to find them.
Q1. What are jarsigner and keytool?
Ans: The Android App Signing instructions do tell you specifically what jarsigner and keytool are all about BUT it doesn't tell you where to find them if you run into a 'command not found error' on the command line window.
Thus, if you've got the Java Development Kit(JDK) added to your PATH variable, simply running the commands as in the Guide would work. BUT, if you don't have it in your PATH, you can always access them from the bin folder of your JDK installation.
Q2. Where is zipalign?
Ans: There is a high probability to not find the zipalign command and receive the 'command not found error'. You'd probably be googling zipalign and where to find it?
The zipalign utility is present within the Android SDK installation folder. On macOS, the default location is at, user-name/Library/Android/sdk/
. If you head over to the folder you would find a bunch of other folders like docs
, platform-tools
, build-tools
, tools
, add-ons
...
Open the build-tools
folder. cd build-tools
. In here, there would be a number of folders which are versioned according to the build tool-chain you are using in the Android SDK Manager. ZipAlign is available in each of these folders. I personally go for the folder with the latest version on it. Open Any.
On macOS or Linux you may have to use ./zipalign
rather than simply typing in zipalign
as the documentation mentions. On Windows, zipalign
is good enough.
If you're using SQL Server 2005 or later, use varchar(MAX)
. The text
datatype is deprecated and should not be used for new development work. From the docs:
Important
ntext
,text
, andimage
data types will be removed in a future version of Microsoft SQL Server. Avoid using these data types in new development work, and plan to modify applications that currently use them. Use nvarchar(max), varchar(max), and varbinary(max) instead.
Try this:
return Redirect("http://www.website.com");
If you are still looking to use Google Finance for your data you can check this out.
I recently needed to test if SGX data is indeed retrievable via google finance (and of course i met with the same problem as you)
This error appears in my android project with multiple kind of gfx files. At the end no change in the manifest file was accepted.
Because my lack of knowledge about the android devices I forget that my test device has a second User. This User also has an installed version of my app so I also have to delete the app for this user account and it works.
For the GUI minded people, you can:
This will uninstall a gem installed by bundler:
bundle exec gem uninstall GEM_NAME
Note that this throws
ERROR: While executing gem ... (NoMethodError) undefined method `delete' for #<Bundler::SpecSet:0x00000101142268>
but the gem is actually removed. Next time you run bundle install
the gem will be reinstalled.
If you want to use Codeblocks and Graphics.h,you can use Codeblocks-EP(I used it when I was learning C in college) then you can try
Codeblocks-EP http://codeblocks.codecutter.org/
In Codeblocks-EP , [File]->[New]->[Project]->[WinBGIm Project]
It has templates for WinBGIm projects installed and all the necessary libraries pre-installed.
OR try this https://stackoverflow.com/a/20321173/5227589
Instead of rotating the text, would it work to have it written "top to bottom?"
Like this:
S
O
M
E
T
E
X
T
I think that would be a lot easier - you can pick a string of text apart and insert a line break after each character.
This could be done via JavaScript in the browser like this:
"SOME TEXT".split("").join("\n")
... or you could do it server-side, so it wouldn't depend on the client's JS capabilities. (I assume that's what you mean by "portable?")
Also the user doesn't have to turn his/her head sideways to read it. :)
This thread is about doing this with jQuery.
Environment variable (can access anywhere/ dynamic object) is a type of variable. They are of 2 types system environment variables and user environment variables.
System variables having a predefined type and structure. That are used for system function. Values that produced by the system are stored in the system variable. They generally indicated by using capital letters Example: HOME,PATH,USER
User environment variables are the variables that determined by the user,and are represented by using small letters.
After setting the gems directory to the user directory that runs the gem install
, using export GEM_HOME=/home/<user>/gems
, the issue has been solved.
Actually you can fix it with following steps -
cls.__dict__
{'isFilled':True}
or {'isFilled':False}
depending upon what you have set.del cls.__dict__['isFilled']
In this case, we delete the entry which overrides the method as mentioned by BrenBarn.
If you pass the name of an array as an argument to a function, it is treated as if you had passed the address of the array. So &s and s are identical arguments. See K&R 5.3. &s[0] is the same as &s, since it takes the address of the first element of the array, which is the same as taking the address of the array itself.
For all the others, although all pointers are essentially memory locations they are still typed, and the compiler will warn about assigning one type of pointer to another.
void* p;
says p is a memory address, but I don't know what's in the memorychar* s;
says s is a memory address, and the first byte contains a characterchar** ps;
says ps is a memory address, and the four bytes there (for a 32-bit system) contain a pointer of type char*.cf http://www.oberon2005.ru/paper/kr_c.pdf (e-book version of K&R)
Try This Code.
.card {_x000D_
_x000D_
width: 200px;_x000D_
_x000D_
height: 195px;_x000D_
_x000D_
position: relative;_x000D_
_x000D_
display: inline-block;_x000D_
_x000D_
}_x000D_
_x000D_
.card .img-top {_x000D_
_x000D_
display: none;_x000D_
_x000D_
position: absolute;_x000D_
_x000D_
top: 0;_x000D_
_x000D_
left: 0;_x000D_
_x000D_
z-index: 99;_x000D_
width:200px;_x000D_
}_x000D_
_x000D_
.card:hover .img-top {_x000D_
_x000D_
display: inline;_x000D_
_x000D_
}
_x000D_
<!DOCTYPE html>_x000D_
_x000D_
<html lang="en">_x000D_
_x000D_
<head>_x000D_
_x000D_
<title>Image Change on Hover with CSS</title>_x000D_
_x000D_
_x000D_
</head>_x000D_
_x000D_
<body>_x000D_
_x000D_
<div class="card">_x000D_
_x000D_
<img src="http://www.dhresource.com/200x200s/f2-albu-g5-M00-EC-97-rBVaJFkAobCAHD9XAADvz9DDocA266.jpg/diy-wall-stickers-home-decor-nature-colorful.jpg" alt="Card Back" style="width:200px">_x000D_
_x000D_
<img src="https://s-media-cache-ak0.pinimg.com/236x/31/17/98/3117987a0be0a7d8976869aabf54d2d7.jpg" class="img-top" alt="Card Front">_x000D_
_x000D_
</div>_x000D_
_x000D_
</body>_x000D_
_x000D_
</html>
_x000D_
$('#my_elementtt').click(function(event){
trigger('click');
});
You can also use jq to track down the array within the returned json and then pipe that in to a second jq
call to get its length. Suppose it was in a property called records
, like {"records":[...]}
.
$ curl https://my-source-of-json.com/list | jq -r '.records' | jq length
2
$
You shouldn't use String.match but RegExp.prototype.test (i.e. /abc/.test("abcd")
) instead of String.search() if you're only interested in a boolean value. You also need to repeat your character class as explained in the answer by Andy E:
var regexp = /^[a-zA-Z0-9-_]+$/;
What I tend to do, and I believe this is what Google intended for developers to do too, is to still get the extras from an Intent
in an Activity
and then pass any extra data to fragments by instantiating them with arguments.
There's actually an example on the Android dev blog that illustrates this concept, and you'll see this in several of the API demos too. Although this specific example is given for API 3.0+ fragments, the same flow applies when using FragmentActivity
and Fragment
from the support library.
You first retrieve the intent extras as usual in your activity and pass them on as arguments to the fragment:
public static class DetailsActivity extends FragmentActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// (omitted some other stuff)
if (savedInstanceState == null) {
// During initial setup, plug in the details fragment.
DetailsFragment details = new DetailsFragment();
details.setArguments(getIntent().getExtras());
getSupportFragmentManager().beginTransaction().add(
android.R.id.content, details).commit();
}
}
}
In stead of directly invoking the constructor, it's probably easier to use a static method that plugs the arguments into the fragment for you. Such a method is often called newInstance
in the examples given by Google. There actually is a newInstance
method in DetailsFragment
, so I'm unsure why it isn't used in the snippet above...
Anyways, all extras provided as argument upon creating the fragment, will be available by calling getArguments()
. Since this returns a Bundle
, its usage is similar to that of the extras in an Activity
.
public static class DetailsFragment extends Fragment {
/**
* Create a new instance of DetailsFragment, initialized to
* show the text at 'index'.
*/
public static DetailsFragment newInstance(int index) {
DetailsFragment f = new DetailsFragment();
// Supply index input as an argument.
Bundle args = new Bundle();
args.putInt("index", index);
f.setArguments(args);
return f;
}
public int getShownIndex() {
return getArguments().getInt("index", 0);
}
// (other stuff omitted)
}
You have to parse all of the input string, you cannot just ignore parts.
from datetime import date, datetime
for item in j:
st = datetime.strptime(item['start'], '%A %d %B %H:%M')
if st.date() == date.today():
item['start'] = st.time()
Here, we compare the date to today's date by using more datetime
objects instead of trying to use strings.
The alternative is to only pass in part of the item['start']
string (splitting out just the time), but there really is no point here, not when you could just parse everything in one step first.
You could use the substr
function to return a substring starting from the 5th character:
$str = "The quick brown fox jumps over the lazy dog."
$str2 = substr($str, 4); // "quick brown fox jumps over the lazy dog."
Scala version of solution by nirg (assumes bounding rectangle pre-check is done separately):
def inside(p: Point, polygon: Array[Point], bounds: Bounds): Boolean = {
val length = polygon.length
@tailrec
def oddIntersections(i: Int, j: Int, tracker: Boolean): Boolean = {
if (i == length)
tracker
else {
val intersects = (polygon(i).y > p.y) != (polygon(j).y > p.y) && p.x < (polygon(j).x - polygon(i).x) * (p.y - polygon(i).y) / (polygon(j).y - polygon(i).y) + polygon(i).x
oddIntersections(i + 1, i, if (intersects) !tracker else tracker)
}
}
oddIntersections(0, length - 1, tracker = false)
}
Here's a great scripted solution for logging people out remotely or locally. I'm using qwinsta to get session information and building an array out of the given output. This makes it really easy to iterate through each entry and log out only the actual users, and not the system or RDP listener itself which usually just throws an access denied error anyway.
$serverName = "Name of server here OR localhost"
$sessions = qwinsta /server $serverName| ?{ $_ -notmatch '^ SESSIONNAME' } | %{
$item = "" | Select "Active", "SessionName", "Username", "Id", "State", "Type", "Device"
$item.Active = $_.Substring(0,1) -match '>'
$item.SessionName = $_.Substring(1,18).Trim()
$item.Username = $_.Substring(19,20).Trim()
$item.Id = $_.Substring(39,9).Trim()
$item.State = $_.Substring(48,8).Trim()
$item.Type = $_.Substring(56,12).Trim()
$item.Device = $_.Substring(68).Trim()
$item
}
foreach ($session in $sessions){
if ($session.Username -ne "" -or $session.Username.Length -gt 1){
logoff /server $serverName $session.Id
}
}
In the first line of this script give $serverName the appropriate value or localhost if running locally. I use this script to kick users before an automated process attempts to move some folders around. Prevents "file in use" errors for me. Another note, this script will have to be ran as an administrator user otherwise you can get accessed denied trying to log someone out. Hope this helps!
Meaning of a Const Member Function in C++ Common Knowledge: Essential Intermediate Programming gives a clear explanation:
The type of the this pointer in a non-const member function of a class X is X * const. That is, it’s a constant pointer to a non-constant X (see Const Pointers and Pointers to Const [7, 21]). Because the object to which this refers is not const, it can be modified. The type of this in a const member function of a class X is const X * const. That is, it’s a constant pointer to a constant X. Because the object to which this refers is const, it cannot be modified. That’s the difference between const and non-const member functions.
So in your code:
class foobar
{
public:
operator int () const;
const char* foo() const;
};
You can think it as this:
class foobar
{
public:
operator int (const foobar * const this) const;
const char* foo(const foobar * const this) const;
};
Using file extension and getimagesize
function to detect if uploaded file has right format is just the entry level check and it can simply bypass by uploading a file with true extension and some byte of an image header but wrong content.
for being secure and safe you may make thumbnail/resize (even with original image sizes) the uploaded picture and save this version instead the uploaded one.
Also its possible to get uploaded file content and search it for special character like <?php
to find the file is image or not.
This is a classic difficulty in LaTeX.
The problem is how to do layout with floats (figures and tables, an similar objects) and footnotes. In particular, it is hard to pick a place for a float with certainty that making room for the associated footnotes won't cause trouble. So the standard tabular
and figure
environments don't even try.
What can you do:
\footnotesize
for the size). You also have to manage the symbols or number yourself with \footnotemark
. Simple, but not very attractive, and the footnote does not appear at the bottom of the page.tabularx
, longtable
, threeparttable[x]
(kudos to Joseph) or ctable
which support this behavior.[h!]
(or [H]
with the float package) to control where the float will appear, and \footnotetext
on the same page to put the footnote where you want it. Again, use \footnotemark
to install the symbol. Fragile and requires hand-tooling every instance.footnotes
package provides the savenote
environment, which can be used to do this.\begin{figure} \begin{minipage}{\textwidth} ... \caption[Caption for LOF]% {Real caption\footnote{blah}} \end{minipage} \end{figure}
Additional reference: TeX FAQ item Footnotes in tables.
Just use <br>
. Do not use <br></br>
. <br>
is a special tag which doesn't need a closing unlike most tags.
I had the same problem and solved it by using the default woocommerce hook to display the product image.
while ( $loop->have_posts() ) : $loop->the_post();
echo woocommerce_get_product_thumbnail('woocommerce_full_size');
endwhile;
Available parameters:
You can't modify a collection while iterating it. That way lies madness - most notably, if you were allowed to delete and deleted the current item, the iterator would have to move on (+1) and the next call to next
would take you beyond that (+2), so you'd end up skipping one element (the one right behind the one you deleted). You have two options:
.keys()
et al for this (in Python 3, pass the resulting iterator to list
). Could be highly wasteful space-wise though.mydict
as usual, saving the keys to delete in a seperate collection to_delete
. When you're done iterating mydict
, delete all items in to_delete
from mydict
. Saves some (depending on how many keys are deleted and how many stay) space over the first approach, but also requires a few more lines.if you are writing styles in styles.xml then
remove android:inputType property and add below lines
<item name="android:capitalize">words</item>
This will search and replace all non ASCII letters:
String resultString = subjectString.replaceAll("[^\\x00-\\x7F]", "");
Make sure that your query ran successfully and you got the results. You can check like this:
$result = mysql_query("SELECT * FROM student WHERE IDNO=".$_GET['id']) or die(mysql_error());
if (is_resource($result))
{
// your while loop and fetch array function here....
}
You can use mysql scheduler to run it each 5 seconds. You can find samples at http://dev.mysql.com/doc/refman/5.1/en/create-event.html
Never used it but I hope this would work:
CREATE EVENT myevent
ON SCHEDULE EVERY 5 SECOND
DO
CALL delete_rows_links();
are there any cases where it doesn't work?
If the parent page was loaded from file://
, then it probably does not work (it will try to get file://cdn.example.com/js_file.js
, which of course you could provide locally as well).
...assuming that there is some maximum number of nestings you'd be happy to stop at.
Let me explain.
@torsten-marek is right that a regular expression cannot check for nested patterns like this, BUT it is possible to define a nested regex pattern which will allow you to capture nested structures like this up to some maximum depth. I created one to capture EBNF-style comments (try it out here), like:
(* This is a comment (* this is nested inside (* another level! *) hey *) yo *)
The regex (for single-depth comments) is the following:
m{1} = \(+\*+(?:[^*(]|(?:\*+[^)*])|(?:\(+[^*(]))*\*+\)+
This could easily be adapted for your purposes by replacing the \(+\*+
and \*+\)+
with {
and }
and replacing everything in between with a simple [^{}]
:
p{1} = \{(?:[^{}])*\}
(Here's the link to try that out.)
To nest, just allow this pattern within the block itself:
p{2} = \{(?:(?:p{1})|(?:[^{}]))*\}
...or...
p{2} = \{(?:(?:\{(?:[^{}])*\})|(?:[^{}]))*\}
To find triple-nested blocks, use:
p{3} = \{(?:(?:p{2})|(?:[^{}]))*\}
...or...
p{3} = \{(?:(?:\{(?:(?:\{(?:[^{}])*\})|(?:[^{}]))*\})|(?:[^{}]))*\}
A clear pattern has emerged. To find comments nested to a depth of N
, simply use the regex:
p{N} = \{(?:(?:p{N-1})|(?:[^{}]))*\}
where N > 1 and
p{1} = \{(?:[^{}])*\}
A script could be written to recursively generate these regexes, but that's beyond the scope of what I need this for. (This is left as an exercise for the reader. )
You can't render a partial view using only jQuery. You can, however, call a method (action) that will render the partial view for you and add it to the page using jQuery/AJAX. In the below, we have a button click handler that loads the url for the action from a data attribute on the button and fires off a GET request to replace the DIV contained in the partial view with the updated contents.
$('.js-reload-details').on('click', function(evt) {
evt.preventDefault();
evt.stopPropagation();
var $detailDiv = $('#detailsDiv'),
url = $(this).data('url');
$.get(url, function(data) {
$detailDiv.replaceWith(data);
});
});
where the user controller has an action named details that does:
public ActionResult Details( int id )
{
var model = ...get user from db using id...
return PartialView( "UserDetails", model );
}
This is assuming that your partial view is a container with the id detailsDiv
so that you just replace the entire thing with the contents of the result of the call.
Parent View Button
<button data-url='@Url.Action("details","user", new { id = Model.ID } )'
class="js-reload-details">Reload</button>
User
is controller name and details
is action name in @Url.Action()
.
UserDetails partial view
<div id="detailsDiv">
<!-- ...content... -->
</div>
.mouseover()
.hover()
Bind one or two handlers
to the matched elements, to be executed when the mouse pointer
enters and leaves the elements.
Calling $(selector).hover(handlerIn, handlerOut)
is shorthand for:
$(selector).mouseenter(handlerIn).mouseleave(handlerOut);
Bind an event handler to be fired when the mouse enters an element, or trigger that handler on an element.
mouseover
fires when the pointer moves into the child element as
well, while mouseenter
fires only when the pointer moves into the
bound element.
Because of this, .mouseover()
is not the same as .hover()
, for the same reason .mouseover()
is not the same as .mouseenter()
.
$('selector').mouseover(over_function) // may fire multiple times
// enter and exit functions only called once per element per entry and exit
$('selector').hover(enter_function, exit_function)
Similar to npocmaka's solution, if you are having more than one line of batch code in your batch file besides the python code, check this out: http://lallouslab.net/2017/06/12/batchography-embedding-python-scripts-in-your-batch-file-script/
@echo off
rem = """
echo some batch commands
echo another batch command
python -x "%~f0" %*
echo some more batch commands
goto :eof
"""
# Anything here is interpreted by Python
import platform
import sys
print("Hello world from Python %s!\n" % platform.python_version())
print("The passed arguments are: %s" % sys.argv[1:])
What this code does is it runs itself as a python file by putting all the batch code into a multiline string. The beginning of this string is in a variable called rem, to make the batch code read it as a comment. The first line containing @echo off
is ignored in the python code because of the -x
parameter.
it is important to mention that if you want to use \
in your batch code, for example in a file path, you'll have to use r"""..."""
to surround it to use it as a raw string without escape sequences.
@echo off
rem = r"""
...
"""
This typically stems from a bug in revision control system, or similar. This was a product from CVS, if a file was checked in from Windows to Unix server, and then checked out again...
In other words, it is just broken...
To see the index for a specific table use SHOW INDEX:
SHOW INDEX FROM yourtable;
To see indexes for all tables within a specific schema you can use the STATISTICS table from INFORMATION_SCHEMA:
SELECT DISTINCT
TABLE_NAME,
INDEX_NAME
FROM INFORMATION_SCHEMA.STATISTICS
WHERE TABLE_SCHEMA = 'your_schema';
Removing the where clause will show you all indexes in all schemas.
You can refer this following link for using strptime
function from datetime.datetime
, to convert date from any format along with time zone.
https://docs.python.org/3/library/datetime.html#strftime-and-strptime-behavior
Your code can get messy fast when dealing with CSS3 transitions. I would recommend using a plugin such as jQuery Transit that handles the complexity of CSS3 animations/transitions.
Moreover, the plugin uses webkit-transform rather than webkit-transition, which allows for mobile devices to use hardware acceleration in order to give your web apps that native look and feel when the animations occur.
Javascript:
$("#startTransition").on("click", function()
{
if( $(".boxOne").is(":visible"))
{
$(".boxOne").transition({ x: '-100%', opacity: 0.1 }, function () { $(".boxOne").hide(); });
$(".boxTwo").css({ x: '100%' });
$(".boxTwo").show().transition({ x: '0%', opacity: 1.0 });
return;
}
$(".boxTwo").transition({ x: '-100%', opacity: 0.1 }, function () { $(".boxTwo").hide(); });
$(".boxOne").css({ x: '100%' });
$(".boxOne").show().transition({ x: '0%', opacity: 1.0 });
});
Most of the hard work of getting cross-browser compatibility is done for you as well and it works like a charm on mobile devices.
Navigate to your play page:
https://play.google.com/store/apps/details?id=com.yourpackage
Using a standard HTTP GET. Now the following jQuery finds important info for you:
$("[itemprop='softwareVersion']").text()
$(".recent-change").each(function() { all += $(this).text() + "\n"; })
Now that you can extract these information manually, simply make a method in your app that executes this for you.
public static String[] getAppVersionInfo(String playUrl) {
HtmlCleaner cleaner = new HtmlCleaner();
CleanerProperties props = cleaner.getProperties();
props.setAllowHtmlInsideAttributes(true);
props.setAllowMultiWordAttributes(true);
props.setRecognizeUnicodeChars(true);
props.setOmitComments(true);
try {
URL url = new URL(playUrl);
URLConnection conn = url.openConnection();
TagNode node = cleaner.clean(new InputStreamReader(conn.getInputStream()));
Object[] new_nodes = node.evaluateXPath("//*[@class='recent-change']");
Object[] version_nodes = node.evaluateXPath("//*[@itemprop='softwareVersion']");
String version = "", whatsNew = "";
for (Object new_node : new_nodes) {
TagNode info_node = (TagNode) new_node;
whatsNew += info_node.getAllChildren().get(0).toString().trim()
+ "\n";
}
if (version_nodes.length > 0) {
TagNode ver = (TagNode) version_nodes[0];
version = ver.getAllChildren().get(0).toString().trim();
}
return new String[]{version, whatsNew};
} catch (IOException | XPatherException e) {
e.printStackTrace();
return null;
}
}
Uses HtmlCleaner
Below is a batch file that will wait for 1 minute, check the day, and then perform an action. It uses PING.EXE, but requires no files that aren't included with Windows.
@ECHO OFF
:LOOP
ECHO Waiting for 1 minute...
PING -n 60 127.0.0.1>nul
IF %DATE:~0,3%==Mon CALL SomeOtherFile.cmd
IF %DATE:~0,3%==Tue CALL SomeOtherFile.cmd
IF %DATE:~0,3%==Wed CALL SomeOtherFile.cmd
IF %DATE:~0,3%==Thu CALL WootSomeOtherFile.cmd
IF %DATE:~0,3%==Fri CALL SomeOtherFile.cmd
IF %DATE:~0,3%==Sat ECHO Saturday...nothing to do.
IF %DATE:~0,3%==Sun ECHO Sunday...nothing to do.
GOTO LOOP
It could be improved upon in many ways, but it might get you started.
- Can someone give a simple definition of what
Record
is?
A Record<K, T>
is an object type whose property keys are K
and whose property values are T
. That is, keyof Record<K, T>
is equivalent to K
, and Record<K, T>[K]
is (basically) equivalent to T
.
- Is
Record<K,T>
merely a way of saying "all properties on this object will have typeT
"? Probably not all objects, sinceK
has some purpose...
As you note, K
has a purpose... to limit the property keys to particular values. If you want to accept all possible string-valued keys, you could do something like Record<string, T>
, but the idiomatic way of doing that is to use an index signature like { [k: string]: T }
.
- Does the
K
generic forbid additional keys on the object that are notK
, or does it allow them and just indicate that their properties are not transformed toT
?
It doesn't exactly "forbid" additional keys: after all, a value is generally allowed to have properties not explicitly mentioned in its type... but it wouldn't recognize that such properties exist:
declare const x: Record<"a", string>;
x.b; // error, Property 'b' does not exist on type 'Record<"a", string>'
and it would treat them as excess properties which are sometimes rejected:
declare function acceptR(x: Record<"a", string>): void;
acceptR({a: "hey", b: "you"}); // error, Object literal may only specify known properties
and sometimes accepted:
const y = {a: "hey", b: "you"};
acceptR(y); // okay
With the given example:
type ThreeStringProps = Record<'prop1' | 'prop2' | 'prop3', string>
Is it exactly the same as this?:
type ThreeStringProps = {prop1: string, prop2: string, prop3: string}
Yes!
Hope that helps. Good luck!
Pretending you are displaying a list of customer objects with "customerName" and "customerId" properties:
listBox.DataSource = customerListObject;
listBox.DataTextField = "customerName";
listBox.DataValueField = "customerId";
listBox.DataBind();
Edit: I know this works in asp.net - if you are doing a winforms app, it should be pretty similar (I hope...)
You want vars()
mixed with pprint()
:
from pprint import pprint
pprint(vars(your_object))
usage: ./my_add_user.sh USER PASSWD
code:
#!/bin/bash
# my_add_user.sh
if [ "$#" -lt 2 ]
then
echo "$0 username passwd"
exit
fi
user=$1
passwd=$2
useradd $user -d /data/home/$user -m ;
echo $passwd | passwd $user --stdin;
I'm using Notepad 7.6 with "Plugin Admin" and I could not find XML Tools.
I had to install it manually like @some-java-guy did in his answer except that my plugins folder was located here: C:\Users\<my username>\AppData\Local\Notepad++\plugins
In that directory I created a new directory (named XmlTools) and copied XMLTools.dll there. (And I copied all dependencies to the Notepad++ directory in Program files.)
The answer of driblio can be made a little shorter (though not much readable)
@echo off
:: Calculate the start timestamp
set _time=%time%
set /a _hours=100%_time:~0,2%%%100,_min=100%_time:~3,2%%%100,_sec=100%_time:~6,2%%%100,_cs=%_time:~9,2%
set /a _started=_hours*60*60*100+_min*60*100+_sec*100+_cs
:: yourCommandHere
:: Calculate the difference in cSeconds
set _time=%time%
set /a _hours=100%_time:~0,2%%%100,_min=100%_time:~3,2%%%100,_sec=100%_time:~6,2%%%100,_cs=%_time:~9,2%
set /a _duration=_hours*60*60*100+_min*60*100+_sec*100+_cs-_started
:: Populate variables for rendering (100+ needed for padding)
set /a _hours=_duration/60/60/100,_min=100+_duration/60/100%%60,_sec=100+(_duration/100%%60%%60),_cs=100+_duration%%100
echo Done at: %_time% took : %_hours%:%_min:~-2%:%_sec:~-2%.%_cs:~-2%
::prints something like:
::Done at: 12:37:53,70 took: 0:02:03.55
To the remark of Luke Sampson this version is octal safe, though the task should be completed in 24 hours.
Note to readers: Several commenters have pointed out some problems in this answer (related particularly to the first suggestion). Refer to the comments section for more information.
DateTime.UtcNow.ToString("yyyy-MM-ddTHH\\:mm\\:ss.fffffffzzz");
This gives you a date similar to 2008-09-22T13:57:31.2311892-04:00.
Another way is:
DateTime.UtcNow.ToString("o");
which gives you 2008-09-22T14:01:54.9571247Z
To get the specified format, you can use:
DateTime.UtcNow.ToString("yyyy-MM-ddTHH:mm:ssZ")
Not for entire application or particular class.
CurrentUICulture and CurrentCulture are settable per thread as discussed here Is there a way of setting culture for a whole application? All current threads and new threads?. You can't change InvariantCulture
at all.
Sample code to change cultures for current thread:
CultureInfo ci = new CultureInfo(theCultureString);
Thread.CurrentThread.CurrentCulture = ci;
Thread.CurrentThread.CurrentUICulture = ci;
For class you can set/restore culture inside critical methods, but it would be significantly safe to use appropriate overrides for most formatting related methods that take culture as one of arguments:
(3.3).ToString(new CultureInfo("fr-FR"))
1) add the "libxml2.dylib" library to my project's TARGET (Build Phases -> Link Binary With Libraries)
2) add "$(SDKROOT)/usr/include/libxml2" to the Header Search Paths on the TARGET (Build Settings -> Header Search Paths)
After this, the target should build successfully.
In my opinion, deferreds/promises (as you have mentionned) is the way to go, rather than using timeouts.
Here is an example I have just written to demonstrate how you could do it using deferreds/promises.
Take some time to play around with deferreds. Once you really understand them, it becomes very easy to perform asynchronous tasks.
Hope this helps!
$(function(){
function1().done(function(){
// function1 is done, we can now call function2
console.log('function1 is done!');
function2().done(function(){
//function2 is done
console.log('function2 is done!');
});
});
});
function function1(){
var dfrd1 = $.Deferred();
var dfrd2= $.Deferred();
setTimeout(function(){
// doing async stuff
console.log('task 1 in function1 is done!');
dfrd1.resolve();
}, 1000);
setTimeout(function(){
// doing more async stuff
console.log('task 2 in function1 is done!');
dfrd2.resolve();
}, 750);
return $.when(dfrd1, dfrd2).done(function(){
console.log('both tasks in function1 are done');
// Both asyncs tasks are done
}).promise();
}
function function2(){
var dfrd1 = $.Deferred();
setTimeout(function(){
// doing async stuff
console.log('task 1 in function2 is done!');
dfrd1.resolve();
}, 2000);
return dfrd1.promise();
}
I got this problem, and tried many ways to solve it. Finally, it turned out that make clean
and make
again solved it. The reason is:
I got the source code together with object files compiled previously with an old gcc version. When my newer gcc version wants to link that old object files, it can't resolve some function in there. It happens to me several times that the source code distributors do not clean up before packing, so a make clean
saved the day.
Assuming you are using debian linux (I'm using Linux mint 12, problem was on Ubuntu 12.04.1 LTS server I ssh'ed into.)
I suggest taking @dkamins advice and making sure you have mcrypt installed and active on your php5 install. Use "sudo apt-get install php5-mcrypt" to install. My notes below.
Using PHP version PHP Version 5.3.10-1ubuntu3.4
, if you open phpinfo() as suggested by @John Conde, which you do by creating test file on web server (e.g. create status page testphp.php with just the contents "" anywhere accessible on the server via browser)
I found no presence of enabled or disabled status on the status page when opened in browser. When I then opened the php.ini file, mentioned by @Anthony Forloney, thinking to uncomment ;extension=php_mcrypt.dll to extension=php_mcrypt.dll
I toggled that back and forth and restarted Apache (I'm running Apache2 and you can restart in my setup with sudo /etc/init.d/apache2 restart
or when you are in that directory just sudo restart
I believe)
with change and without change but all no go. I took @dkamins advice and went to install the package with "sudo apt-get install php5-mcrypt" and then restarted apache as above. Then my error was gone and my application worked fine.
You may try with the below code
override func viewDidAppear(_ animated: Bool) {
self.navigationController?.isNavigationBarHidden = true
}
If you want to keep same screen size, you can consider using crf factor: https://trac.ffmpeg.org/wiki/Encode/H.264
Here is the command which works for me: (on mac you need to add -strict -2
to be able to use aac audio codec.
ffmpeg -i input.mp4 -c:v libx264 -crf 24 -b:v 1M -c:a aac output.mp4
No need for that much code.
You can do all this stuff without coding so much by using only viewpager
with tablayout
.
Your main Layout:
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<android.support.v4.view.ViewPager
android:id="@+id/pager"
android:layout_width="match_parent"
android:layout_height="match_parent">
</android.support.v4.view.ViewPager>
<android.support.design.widget.TabLayout
android:id="@+id/tabDots"
android:layout_alignParentBottom="true"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:tabBackground="@drawable/tab_selector"
app:tabGravity="center"
app:tabIndicatorHeight="0dp"/>
</RelativeLayout>
Hook up your UI elements inactivity or fragment as follows:
Java Code:
mImageViewPager = (ViewPager) findViewById(R.id.pager);
TabLayout tabLayout = (TabLayout) findViewById(R.id.tabDots);
tabLayout.setupWithViewPager(mImageViewPager, true);
That's it, you are good to go.
You will need to create the following xml resource file in the drawable folder.
tab_indicator_selected.xml
<?xml version="1.0" encoding="utf-8"?>
<shape
android:innerRadius="0dp"
android:shape="ring"
android:thickness="4dp"
android:useLevel="false"
xmlns:android="http://schemas.android.com/apk/res/android">
<solid android:color="@color/colorAccent"/>
</shape>
tab_indicator_default.xml
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:innerRadius="0dp"
android:shape="oval"
android:thickness="2dp"
android:useLevel="false">
<solid android:color="@android:color/darker_gray"/>
</shape>
tab_selector.xml
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="@drawable/tab_indicator_selected"
android:state_selected="true"/>
<item android:drawable="@drawable/tab_indicator_default"/>
</selector>
Feeling as lazy as I am? Well, all the above code is converted into a library!
Usage
Add the following in your gradle:
implementation 'com.chabbal:slidingdotsplash:1.0.2'
Add the following to your Activity or Fragment layout.
<com.chabbal.slidingdotsplash.SlidingSplashView
android:id="@+id/splash"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:imageResources="@array/img_id_arr"/>
Create an integer array in strings.xml
e.g.
<integer-array name="img_id_arr">
<item>@drawable/img1</item>
<item>@drawable/img2</item>
<item>@drawable/img3</item>
<item>@drawable/img4</item>
</integer-array>
Done!
Extra in order to listen page changes use addOnPageChangeListener(listener);
Github link.
code {_x000D_
background: black;_x000D_
color: white;_x000D_
display: inline-block;_x000D_
vertical-align: middle;_x000D_
}
_x000D_
<p>Some text <code>A<br />B<br />C<br />D</code> continues afterward.</p>
_x000D_
Tested and works in Safari 5 and IE6+.
A lib is a unit of code that is bundled within your application executable.
A dll is a standalone unit of executable code. It is loaded in the process only when a call is made into that code. A dll can be used by multiple applications and loaded in multiple processes, while still having only one copy of the code on the hard drive.
Dll pros: can be used to reuse/share code between several products; load in the process memory on demand and can be unloaded when not needed; can be upgraded independently of the rest of the program.
Dll cons: performance impact of the dll loading and code rebasing; versioning problems ("dll hell")
Lib pros: no performance impact as code is always loaded in the process and is not rebased; no versioning problems.
Lib cons: executable/process "bloat" - all the code is in your executable and is loaded upon process start; no reuse/sharing - each product has its own copy of the code.
<head>
<script type="text/javascript">
function test(x, y)
{
var cc = "";
for (var i = 0; i < x.length; i++)
{
cc += x[i];
}
cc += "\ny: " + y;
return cc;
}
</script>
</head>
<body>
<form id="form1" runat="server">
<asp:Button ID="Button1" runat="server" Text="Button" />
<p>
<asp:TextBox ID="TextBox1" Name="TextBox1" runat="server" AutoPostBack="True" TextMode="MultiLine"></asp:TextBox>
</p>
</form>
</body>
protected void Page_Load(object sender, EventArgs e)
{
int[] x = new int[] { 1, 2, 3, 4, 5 };
int[] y = new int[] { 1, 2, 3, 4, 5 };
string xStr = getArrayString(x); // converts {1,2,3,4,5} to [1,2,3,4,5]
string yStr = getArrayString(y);
string script = String.Format(" var y = test({0},{1}) ; ", xStr, yStr);
script += String.Format(" document.getElementById(\"TextBox1\").value = y ");
this.Page.ClientScript.RegisterStartupScript(this.GetType(), "testFunction", script, true);
// this.Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "testFunction", script, true); // different result
}
private string getArrayString(int[] array)
{
StringBuilder sb = new StringBuilder();
for (int i = 0; i < array.Length; i++)
{
sb.Append(array[i] + ",");
}
string arrayStr = string.Format("[{0}]", sb.ToString().TrimEnd(','));
return arrayStr;
}
Here's a very simple awk script that takes into account all common pitfalls listed in the other answers:
getent passwd | awk -F: -v group_name="wheel" '
BEGIN {
"getent group " group_name | getline groupline;
if (!groupline) exit 1;
split(groupline, groupdef, ":");
guid = groupdef[3];
split(groupdef[4], users, ",");
for (k in users) print users[k]
}
$4 == guid {print $1}'
I'm using this with my ldap-enabled setup, runs on anything with standards-compliant getent & awk, including solaris 8+ and hpux.
I got the same error. I have been using select2-3.5.2
This was my code which had error
$('#carstatus-select').select2().val([1,2])
Below code fixed the issue.
$('#carstatus-select').val([1,2]);
My situation was that I have a bare repo that the team pushes to, and a clone of that sitting right next to it. This set of lines in a Makefile work correctly for me:
git reset --hard
git remote update --prune
git pull --rebase --all
git cherry-pick -n remotes/origin/$(BRANCH)
By keeping the master of the bare repo up to date, we are able to cherry-pick a proposed change published to the bare repo. We also have a (more complicated) way to cherry-pick multiple braches for consolidated review and testing.
If "knows nothing" means "can't be used as a remote", then this doesn't help, but this SO question came up as I was googling around to come up with this workflow so I thought I'd contribute back.
Do not always use Redirect permanent
(or why it may cause issues in future)
If there is a chance that you will add subdomains later, do not use redirect permanent
.
Because if a client has used a subdomain that wasn't registred as VirtualHost
he may also never reach this subdomain even when it is registred later.
redirect permanent
sends an HTTP 301 Moved Permanently
to the client (browser) and a lot of them cache this response for ever (until cache is cleared [manually]). So using that subdomain will always autoredirect to www.*** without requesting the server again.
see How long do browsers cache HTTP 301s?
So just use Redirect
<VirtualHost *:80>
ServerName example.com
Redirect / http://www.example.com/
</VirtualHost>
Simple and straight forward way to create ArrayList of String
List<String> category = Arrays.asList("everton", "liverpool", "swansea", "chelsea");
Cheers
For python3.5.3, pip3 is also installed when you install python. When you install it you may not select the add to path. Then you can find where the pip3 located and add it to path manually.
In DefaultAppPool set NetworkService in the Identity property and in Sql Server add User Network Service and give it the appropiate permissions to your database, that's work very well for me, I've tested locally but I think this is the best configuration for connecting from any other computer in the network. when you set LocalSystem in the Identity in IIS that's work well and it is not necessary to create any other user in Sql Server but I think that will not work in a network environment.
Both representations are useful. I had used singular for convenience for quite some time, inflection can be difficult. My experience in developing strictly singular REST APIs, the developers consuming the endpoint lack certainty in what the shape of the result may be. I now prefer to use the term that best describes the shape of the response.
If all of your resources are top level, then you can get away with singular representations. Avoiding inflection is a big win.
If you are doing any sort of deep linking to represent queries on relations, then developers writing against your API can be aided by having a stricter convention.
My convention is that each level of depth in a URI is describing an interaction with the parent resource, and the full URI should implicitly describe what is being retrieved.
Suppose we have the following model.
interface User {
<string>id;
<Friend[]>friends;
<Manager>user;
}
interface Friend {
<string>id;
<User>user;
...<<friendship specific props>>
}
If I needed to provide a resource that allows a client to get the manager of a particular friend of a particular user, it might look something like:
GET /users/{id}/friends/{friendId}/manager
The following are some more examples:
GET /users
- list the user resources in the global users collectionPOST /users
- create a new user in the global users collectionGET /users/{id}
- retrieve a specific user from the global users collectionGET /users/{id}/manager
- get the manager of a specific userGET /users/{id}/friends
- get the list of friends of a userGET /users/{id}/friends/{friendId}
- get a specific friend of a userLINK /users/{id}/friends
- add a friend association to this userUNLINK /users/{id}/friends
- remove a friend association from this userNotice how each level maps to a parent that can be acted upon. Using different parents for the same object is counterintuitive. Retrieving a resource at GET /resource/123
leaves no indication that creating a new resource should be done at POST /resources
To access a specific option you need to provide the nth-child() selector:
ptor.findElement(protractor.By.css('select option:nth-child(1)')).click();
After having seen the answers at floor 3, I tried to figure out what the relationship of setting up the separator between TableView & TableViewCell and did some test. Here are my conclusions:
we can consider that setting the cell's separator to zero has to move the separator in two steps: first step is to set cell's separatorinset to zero. second step is to set cell's marginlayout to zero.
set the TableView's separatorinset and marginlayout can affect the Cell's separatorinset. However, from the test, I find that the TableView's separatorinset seem to be useless, TableView's marginlayout can actually affect cell's marginlayout.
set Cell's PreservesSuperviewLayoutMargins = false, can cut off TableView's marginlayout effect on Cells.
one of the solutions:
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
var cell = UITableViewCell()
cell.preservesSuperviewLayoutMargins = false
cell.separatorInset = UIEdgeInsetsZero
cell.layoutMargins = UIEdgeInsetsZero
return cell
}
We got this error when reusing the ConnectionString from EntityFramework connection. We have Username and Password in the connection string but didn't specify "Persist Security Info=True". Thus, the credentials were removed from the connection string after establishing the connection (so we reused an incomplete connection string). Of course, we always have to think twice when using this setting, but in this particular case, it was ok.
Quite simple:
$input = array(
array(
'tag_name' => 'google'
),
array(
'tag_name' => 'technology'
)
);
echo implode(', ', array_map(function ($entry) {
return $entry['tag_name'];
}, $input));
and new in php v5.5.0, array_column
:
echo implode(', ', array_column($input, 'tag_name'));
Try Logic Friday 1
It includes tools from the Univerity of California (Espresso and misII) and makes them usable with a GUI. You can enter boolean equations and truth tables as desired. It also features a graphical gate diagram input and output.
The minimization can be carried out two-level or multi-level. The two-level form yields a minimized sum of products. The multi-level form creates a circuit composed out of logical gates. The types of gates can be restricted by the user.
Your expression simplifies to C
.
I know this question is a bit old, but I'd use a jQuery template and a $.ajax call:
ASPX:
<select id="mySelect" name="mySelect>
<option value="0">-select-</option>
</select>
<script id="mySelectTemplate" type="text/x-jquery-tmpl">
<option value="${CityId}">${CityName}</option>
</script>
JS:
$.ajax({
url: location.pathname + '/GetCities',
type: 'POST',
contentType: 'application/json; charset=utf-8',
dataType: 'json',
success: function (response) {
$('#mySelectTemplate').tmpl(response.d).appendTo('#mySelect');
}
});
In addition to the above you'll need a web method (GetCities) that returns a list of objects that include the data elements you're using in your template. I often use Entity Framework and my web method will call a manager class that is getting values from the database using linq. By doing that you can have your input save to the database and refreshing your select list is as simple as calling the databind in JS in the success of your save.
I generally use array split because it's easier simple syntax and scales better with more than 2 partitions.
import numpy as np
partitions = 2
dfs = np.array_split(df, partitions)
np.split(df, [100,200,300], axis=0]
wants explicit index numbers which may or may not be desirable.
This Function will probably list all the file name and its path from its directory and its subdirectories.
public void listFile(String pathname) {
File f = new File(pathname);
File[] listfiles = f.listFiles();
for (int i = 0; i < listfiles.length; i++) {
if (listfiles[i].isDirectory()) {
File[] internalFile = listfiles[i].listFiles();
for (int j = 0; j < internalFile.length; j++) {
System.out.println(internalFile[j]);
if (internalFile[j].isDirectory()) {
String name = internalFile[j].getAbsolutePath();
listFile(name);
}
}
} else {
System.out.println(listfiles[i]);
}
}
}
I used Matchers.refEq
for this.
Here's a list of differences. I've highlighted Oracle-specific features, and hopefully the community can add in other vendors' specific difference also. Differences that are common to most vendors can go directly below the headings, with differences highlighted below.
If you want to quickly delete all of the rows from a table, and you're really sure that you want to do it, and you do not have foreign keys against the tables, then a TRUNCATE is probably going to be faster than a DELETE.
Various system-specific issues have to be considered, as detailed below.
Delete is DML, Truncate is DDL (What is DDL and DML?)
Variable by vendor
SQL*Server
Truncate can be rolled back.
PostgreSQL
Truncate can be rolled back.
Oracle
Because a TRUNCATE is DDL it involves two commits, one before and one after the statement execution. Truncate can therefore not be rolled back, and a failure in the truncate process will have issued a commit anyway.
However, see Flashback below.
Delete does not recover space, Truncate recovers space
Oracle
If you use the REUSE STORAGE clause then the data segments are not de-allocated, which can be marginally more efficient if the table is to be reloaded with data. The high water mark is reset.
Delete can be used to remove all rows or only a subset of rows. Truncate removes all rows.
Oracle
When a table is partitioned, the individual partitions can be truncated in isolation, thus a partial removal of all the table's data is possible.
Delete can be applied to tables and tables inside a cluster. Truncate applies only to tables or the entire cluster. (May be Oracle specific)
Oracle
Delete does not affect the data object id, but truncate assigns a new data object id unless there has never been an insert against the table since its creation Even a single insert that is rolled back will cause a new data object id to be assigned upon truncation.
Flashback works across deletes, but a truncate prevents flashback to states prior to the operation.
However, from 11gR2 the FLASHBACK ARCHIVE feature allows this, except in Express Edition
Use of FLASHBACK in Oracle http://docs.oracle.com/cd/E11882_01/appdev.112/e41502/adfns_flashback.htm#ADFNS638
Variable
Oracle
Delete can be granted on a table to another user or role, but truncate cannot be without using a DROP ANY TABLE grant.
Delete generates a small amount of redo and a large amount of undo. Truncate generates a negligible amount of each.
Oracle
A truncate operation renders unusable indexes usable again. Delete does not.
A truncate cannot be applied when an enabled foreign key references the table. Treatment with delete depends on the configuration of the foreign keys.
Oracle
Truncate requires an exclusive table lock, delete requires a shared table lock. Hence disabling table locks is a way of preventing truncate operations on a table.
DML triggers do not fire on a truncate.
Oracle
DDL triggers are available.
Oracle
Truncate cannot be issued over a database link.
SQL*Server
Truncate resets the sequence for IDENTITY column types, delete does not.
In most implementations, a DELETE
statement can return to the client the rows that were deleted.
e.g. in an Oracle PL/SQL subprogram you could:
DELETE FROM employees_temp
WHERE employee_id = 299
RETURNING first_name,
last_name
INTO emp_first_name,
emp_last_name;
One classic approach to this problem is to use the "decorate, sort, undecorate" idiom, which is especially simple using python's built-in zip
function:
>>> list1 = [3,2,4,1, 1]
>>> list2 = ['three', 'two', 'four', 'one', 'one2']
>>> list1, list2 = zip(*sorted(zip(list1, list2)))
>>> list1
(1, 1, 2, 3, 4)
>>> list2
('one', 'one2', 'two', 'three', 'four')
These of course are no longer lists, but that's easily remedied, if it matters:
>>> list1, list2 = (list(t) for t in zip(*sorted(zip(list1, list2))))
>>> list1
[1, 1, 2, 3, 4]
>>> list2
['one', 'one2', 'two', 'three', 'four']
It's worth noting that the above may sacrifice speed for terseness; the in-place version, which takes up 3 lines, is a tad faster on my machine for small lists:
>>> %timeit zip(*sorted(zip(list1, list2)))
100000 loops, best of 3: 3.3 us per loop
>>> %timeit tups = zip(list1, list2); tups.sort(); zip(*tups)
100000 loops, best of 3: 2.84 us per loop
On the other hand, for larger lists, the one-line version could be faster:
>>> %timeit zip(*sorted(zip(list1, list2)))
100 loops, best of 3: 8.09 ms per loop
>>> %timeit tups = zip(list1, list2); tups.sort(); zip(*tups)
100 loops, best of 3: 8.51 ms per loop
As Quantum7 points out, JSF's suggestion is a bit faster still, but it will probably only ever be a little bit faster, because Python uses the very same DSU idiom internally for all key-based sorts. It's just happening a little closer to the bare metal. (This shows just how well optimized the zip
routines are!)
I think the zip
-based approach is more flexible and is a little more readable, so I prefer it.
var hiddenFieldID = "input[id$=" + hiddenField + "]";
var requiredVal= $(hiddenFieldID).val();
CSS "classes" are not OOP "classes". The inheritance works the other way around.
A DOM element can have many classes, either directly or inherited or otherwise associated, which will all be applied in order, overriding earlier defined properties:
<div class="foo bar">
.foo {
color: blue;
width: 200px;
}
.bar {
color: red;
}
The div will be 200px wide and have the color red.
You override properties of DOM elements with different classes, not properties of CSS classes. CSS "classes" are rulesets, the same way ids or tags can be used as rulesets.
Note that the order in which the classes are applied depends on the precedence and specificity of the selector, which is a complex enough topic in itself.
The probably only way which is marginally faster than
d = [[] for x in xrange(n)]
is
from itertools import repeat
d = [[] for i in repeat(None, n)]
It does not have to create a new int
object in every iteration and is about 15 % faster on my machine.
Edit: Using NumPy, you can avoid the Python loop using
d = numpy.empty((n, 0)).tolist()
but this is actually 2.5 times slower than the list comprehension.
You don't need to create the SSH keys on the Jenkins server, nor do you need to store the SSH keys on the Jenkins server's filesystem. This bit of information is crucial in environments where Jenkins servers instances may be created and destroyed frequently.
On any machine (Windows, Linux, MacOS ...doesn't matter) generate an SSH key pair. Use this article as guide:
On the target server, you will need to place the content of the public key (id_rsa.pub
per the above article) into the .ssh/authorized_keys
file under the home directory of the user which Jenkins will be using for deployment.
Ref: https://plugins.jenkins.io/publish-over-ssh/
Visit: Jenkins
> Manage Jenkins
> Configure System
> Publish over SSH
id_rsa
per the above article) into the "Key" fieldVisit: Jenkins
> Credentials
> System
> Global credentials (unrestricted)
> Add Credentials
id_rsa
per the above article)]func timeStringFromUnixTime(unixTime: Double) -> String {
let date = NSDate(timeIntervalSince1970: unixTime)
// Returns date formatted as 12 hour time.
dateFormatter.dateFormat = "hh:mm a"
return dateFormatter.stringFromDate(date)
}
func dayStringFromTime(unixTime: Double) -> String {
let date = NSDate(timeIntervalSince1970: unixTime)
dateFormatter.locale = NSLocale(localeIdentifier: NSLocale.currentLocale().localeIdentifier)
dateFormatter.dateFormat = "EEEE"
return dateFormatter.stringFromDate(date)
}
I have tried this code and It's working fine in my case.
DELETE FROM NG_USR_0_CLIENT_GRID_NEW WHERE rowid IN
( SELECT rowid FROM
(
SELECT wi_name, relationship, ROW_NUMBER() OVER (ORDER BY rowid DESC) RN
FROM NG_USR_0_CLIENT_GRID_NEW
WHERE wi_name = 'NB-0000001385-Process'
)
WHERE RN=2
);
paste this command -
Remove-Item (Get-PSReadlineOption).HistorySavePath
in your powershell and start new powershell and its found cleared
for further details check this link @ https://www.shellhacks.com/clear-history-powershell/
I'm not sure that i know exactly what you mean.
But to get the length of an initialized array,
doesn't strlen(string) work ??
@Ciro
You can break the inline svg code with back-slash "\"
Tested with the code below in Chrome 54 and Firefox 50
body {
background: transparent;
background-attachment:fixed;
background-image: url(
"data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg' version='1.1' width='170px' height='50px'> \
<rect x='0' y='0' width='170' height='50' style='stroke:white; fill:gray; stroke-opacity: 0.3; stroke-width: 3px; fill-opacity: 0.7; stroke-dasharray: 10 5; stroke-linecap=round; '/> \
<text x='85' y='30' style='fill:lightBlue; text-anchor: middle' font-size='16' transform='rotate(10,85,25)'>I love SVG!</text></svg>");
}
I even Tested this,
background-image: url("\
data:image/svg+xml;utf8, \
<svg xmlns='http://www.w3.org/2000/svg' version='1.1' width='170px' height='50px'> \
<rect x='0' y='0' width='170' height='50'\
style='stroke:white; stroke-width: 3px; stroke-opacity: 0.3; \
stroke-dasharray: 10 5; stroke-linecap=round; \
fill:gray; fill-opacity: 0.7; '/> \
<text x='85' y='30' \
style='fill:lightBlue; text-anchor: middle' font-size='16' \
transform='rotate(10,85,25)'> \
I love SVG! \
</text> \
</svg>\
");
and it works (at least in Chrome 54 & Firefox 50 ==> usage in NWjs & Electron guarenteed)
Above screenshot taken from this live example: https://regex101.com/r/cU5lC2/1
I'll be using the phpsh interactive shell on Ubuntu 12.10 to demonstrate the PCRE regex engine through the method known as preg_match
Start phpsh, put some content into a variable, match on word.
el@apollo:~/foo$ phpsh
php> $content1 = 'badger'
php> $content2 = '1234'
php> $content3 = '$%^&'
php> echo preg_match('(\w+)', $content1);
1
php> echo preg_match('(\w+)', $content2);
1
php> echo preg_match('(\w+)', $content3);
0
The preg_match method used the PCRE engine within the PHP language to analyze variables: $content1
, $content2
and $content3
with the (\w)+
pattern.
$content1 and $content2 contain at least one word, $content3 does not.
el@apollo:~/foo$ phpsh
php> $gun1 = 'dart gun';
php> $gun2 = 'fart gun';
php> $gun3 = 'darty gun';
php> $gun4 = 'unicorn gun';
php> echo preg_match('(dart|fart)', $gun1);
1
php> echo preg_match('(dart|fart)', $gun2);
1
php> echo preg_match('(dart|fart)', $gun3);
1
php> echo preg_match('(dart|fart)', $gun4);
0
Variables gun1
and gun2
contain the string dart
or fart
which is correct, but gun3 contains darty
and still matches, that is the problem. So onto the next example.
Word Boundaries can be force matched with \b
, see:
Regex Visual Image acquired from http://jex.im/regulex and https://github.com/JexCheng/regulex Example:
el@apollo:~/foo$ phpsh
php> $gun1 = 'dart gun';
php> $gun2 = 'fart gun';
php> $gun3 = 'darty gun';
php> $gun4 = 'unicorn gun';
php> echo preg_match('(\bdart\b|\bfart\b)', $gun1);
1
php> echo preg_match('(\bdart\b|\bfart\b)', $gun2);
1
php> echo preg_match('(\bdart\b|\bfart\b)', $gun3);
0
php> echo preg_match('(\bdart\b|\bfart\b)', $gun4);
0
The \b
asserts that we have a word boundary, making sure " dart " is matched, but " darty " isn't.
Following on @Fowl's answer, you can improve it with a timeout to only appear for 10 seconds using the following:
mshta "javascript:var sh=new ActiveXObject( 'WScript.Shell' ); sh.Popup( 'Message!', 10, 'Title!', 64 );close()"
See here for more details.
A good way is to derive from TcpClient and override the Disposing(bool) method:
class MyClient : TcpClient {
public bool IsDead { get; set; }
protected override void Dispose(bool disposing) {
IsDead = true;
base.Dispose(disposing);
}
}
Which won't work if the other code created the instance. Then you'll have to do something desperate like using Reflection to get the value of the private m_CleanedUp member. Or catch the exception.
Frankly, none is this is likely to come to a very good end. You really did want to write to the TCP port. But you won't, that buggy code you can't control is now in control of your code. You've increased the impact of the bug. Talking to the owner of that code and working something out is by far the best solution.
EDIT: A reflection example:
using System.Reflection;
public static bool SocketIsDisposed(Socket s)
{
BindingFlags bfIsDisposed = BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.GetProperty;
// Retrieve a FieldInfo instance corresponding to the field
PropertyInfo field = s.GetType().GetProperty("CleanedUp", bfIsDisposed);
// Retrieve the value of the field, and cast as necessary
return (bool)field.GetValue(s, null);
}
If you use Custom Actions written in .NET as part of your MSI installer then you have another problem.
The 'shim' that runs these custom actions is always 32bit then your custom action will run 32bit as well, despite what target you specify.
More info & some ninja moves to get around (basically change the MSI to use the 64 bit version of this shim)
Building an MSI in Visual Studio 2005/2008 to work on a SharePoint 64
This error occurs when you compile a java program using classes that support the Servlet API. The compiler searches for the library (included in a .jar file) by using the CLASSPATH. You can specify this when you compile using -classpath
or -cp
options as noted in other responses, but you should set up your environment to define the classpath as needed.
Set the CLASSPATH environment variable to reference the location of servlet-api.jar
, which depends on your setup (OS, how you installed, etc.)
Assuming you're using Tomcat and have installed it in one of 20 possible ways, the APIs used by servlets will be installed on your system, relative to wherever Tomcat is installed. For historical reasons, Tomcat is also known as "Catalina", so you can use the command "catalina" to run certain commands, and alone, it will report, amongst other things the CATALINA_BASE
. For example on my Mac using Tomcat installed using homebrew it's
Using CATALINA_BASE: /usr/local/Cellar/tomcat/8.5.9/libexec
The location of the Tomcat servlet libraries is under this in the lib
directory.
Set CATALINA_BASE, then set CLASSPATH using the base as a start, for example for Linux or OSX you might set this in .profile
, or .bash_profile
like so:
export CATALINA_BASE=/usr/local/Cellar/tomcat/8.5.9/libexec
export CLASSPATH=$CATALINA_BASE/lib/servlet-api.jar:$CLASSPATH
Exit the terminal/shell and come back in to run the profile. You should be able to see that the variable is set by using the echo
command, e.g.
echo $CLASSPATH
or in Windows
echo %CLASSPATH%
If it displays the full path to the jar `javac WebTest.java' compile your class.
Other answers are correct -- set up your IDE (Eclipse, IntelliJ) to know about Tomcat or build with Maven and you'll save pain.
Solved: If you want to "Create project from existing source", you need to create a new directory and then put the project directory tree into that new directory. Then point to the new directory when importing.
These files will successfully open sshd and run service so you can ssh in locally. (you are using cyberduck aren't you?)
Dockerfile
FROM swiftdocker/swift
MAINTAINER Nobody
RUN apt-get update && apt-get -y install openssh-server supervisor
RUN mkdir /var/run/sshd
RUN echo 'root:password' | chpasswd
RUN sed -i 's/PermitRootLogin without-password/PermitRootLogin yes/' /etc/ssh/sshd_config
# SSH login fix. Otherwise user is kicked off after login
RUN sed 's@session\s*required\s*pam_loginuid.so@session optional pam_loginuid.so@g' -i /etc/pam.d/sshd
ENV NOTVISIBLE "in users profile"
RUN echo "export VISIBLE=now" >> /etc/profile
COPY supervisord.conf /etc/supervisor/conf.d/supervisord.conf
EXPOSE 22
CMD ["/usr/bin/supervisord"]
supervisord.conf
[supervisord]
nodaemon=true
[program:sshd]
command=/usr/sbin/sshd -D
to build / run start daemon / jump into shell.
docker build -t swift3-ssh .
docker run -p 2222:22 -i -t swift3-ssh
docker ps # find container id
docker exec -i -t <containerid> /bin/bash
With SmartGit, you can also edit them by going to Project > Repository settings and hitting the "Commit" tab (make sure to have "Remember as default" selected).
Generally speaking, people refer to an application's presentation layer as its front end, its persistence layer (database, usually) as the back end, and anything between as middle tier. This set of ideas is often referred to as 3-tier architecture. They let you separate your application into more easily comprehensible (and testable!) chunks; you can also reuse lower-tier code more easily in higher tiers.
Which code is part of which tier is somewhat subjective; graphic designers tend to think of everything that isn't presentation as the back end, database people think of everything in front of the database as the front end, and so on.
Not all applications need to be separated out this way, though. It's certainly more work to have 3 separate sub-projects than it is to just open index.php and get cracking; depending on (1) how long you expect to have to maintain the app (2) how complex you expect the app to get, you may want to forgo the complexity.
You can set the default like this:
b = models.CharField(max_length=7,default="foobar")
and then you can hide the field with your model's Admin class like this:
class SomeModelAdmin(admin.ModelAdmin):
exclude = ("b")
While onclick
works in all browsers, addEventListener
does not work in older versions of Internet Explorer, which uses attachEvent
instead.
The downside of onclick
is that there can only be one event handler, while the other two will fire all registered callbacks.
I had the same problem and it might look so easy but it solved my problem. I have tried all the solutions recommended here but there was no problem just a day ago. So I thought the problem might be about the Session data. I tried to stop and run apache and mysql services but it didn't work also. Then I realized there are buttons on phpMyAdmin just below its logo on the left side. The button next to "Home"; "Empty Session Data" solved all of my problems.
Edit: In Bootstrap 4, native classes can produce full-height columns (DEMO) because they changed their grid system to flexbox. (Read on for Bootstrap 3)
<header>Header</header>
<div class="container">
<div class="row">
<div class="col-md-3 no-float">Navigation</div>
<div class="col-md-9 no-float">Content</div>
</div>
</div>
html,body,.container {
height:100%;
}
.container {
display:table;
width: 100%;
margin-top: -50px;
padding: 50px 0 0 0; /*set left/right padding according to needs*/
box-sizing: border-box;
}
.row {
height: 100%;
display: table-row;
}
.row .no-float {
display: table-cell;
float: none;
}
The above code will achieve full-height columns (due to the custom css-table properties which we added) and with ratio 1:3 (Navigation:Content) for medium screen widths and above - (due to bootstrap's default classes: col-md-3 and col-md-9)
NB:
1) In order not to mess up bootstrap's native column classes we add another class like no-float
in the markup and only set display:table-cell
and float:none
on this class (as apposed to the column classes themselves).
2) If we only want to use the css-table code for a specific break-point (say medium screen widths and above) but for mobile screens we want to default back to the usual bootstrap behavior than we can wrap our custom CSS within a media query, say:
@media (min-width: 992px) {
.row .no-float {
display: table-cell;
float: none;
}
}
Now, for smaller screens, the columns will behave like default bootstrap columns (each getting full width).
3) If the 1:3 ratio is necessary for all screen widths - then it's probably a better to remove bootstrap's col-md-* classes from the markup because that's not how they are meant to be used.
It seems that the problem with IE comes when you try and access the iframe via the document.frames object - if you store a reference to the created iframe in a variable then you can access the injected iframe via the variable (my_iframe in the code below).
I've gotten this to work in IE6/7/8
var my_iframe;
var iframeId = "my_iframe_name"
if (navigator.userAgent.indexOf('MSIE') !== -1) {
// IE wants the name attribute of the iframe set
my_iframe = document.createElement('<iframe name="' + iframeId + '">');
} else {
my_iframe = document.createElement('iframe');
}
iframe.setAttribute("src", "javascript:void(0);");
iframe.setAttribute("scrolling", "no");
iframe.setAttribute("frameBorder", "0");
iframe.setAttribute("name", iframeId);
var is = iframe.style;
is.border = is.width = is.height = "0px";
if (document.body) {
document.body.appendChild(my_iframe);
} else {
document.appendChild(my_iframe);
}
If you are using ASP.NET Core with the Startup.cs
convention, you can access and set the query command timeout option like this:
public void ConfigureServices(IServiceCollection services)
{
services.AddDbContextPool<MyDbContext>(_ =>
{
_.UseSqlServer(Configuration.GetConnectionString("MyConnectionString"), options =>
{
options.CommandTimeout(180); // 3 minutes
});
});
}
using System.Reflection;
using System.Collections.Generic;
//...
static List<string> GetClasses(string nameSpace)
{
Assembly asm = Assembly.GetExecutingAssembly();
List<string> namespacelist = new List<string>();
List<string> classlist = new List<string>();
foreach (Type type in asm.GetTypes())
{
if (type.Namespace == nameSpace)
namespacelist.Add(type.Name);
}
foreach (string classname in namespacelist)
classlist.Add(classname);
return classlist;
}
NB: The above code illustrates what's going on. Were you to implement it, a simplified version can be used:
using System.Linq;
using System.Reflection;
using System.Collections.Generic;
//...
static IEnumerable<string> GetClasses(string nameSpace)
{
Assembly asm = Assembly.GetExecutingAssembly();
return asm.GetTypes()
.Where(type => type.Namespace == nameSpace)
.Select(type => type.Name);
}
I was able to hide the scrollbar but still be able to scroll with mouse wheel with this solution:
html {overflow: -moz-scrollbars-none;}
Download the plugin https://github.com/brandonaaron/jquery-mousewheel and include this function:
jQuery('html,body').bind('mousewheel', function(event) {
event.preventDefault();
var scrollTop = this.scrollTop;
this.scrollTop = (scrollTop + ((event.deltaY * event.deltaFactor) * -1));
//console.log(event.deltaY, event.deltaFactor, event.originalEvent.deltaMode, event.originalEvent.wheelDelta);
});
Have you tried plt.tight_layout()
?
with plt.tight_layout()
without it:
Or: something like this (use add_axes
)
left=[0.1,0.3,0.5,0.7]
width=[0.2,0.2, 0.2, 0.2]
rectLS=[]
for x in left:
for y in left:
rectLS.append([x, y, 0.2, 0.2])
axLS=[]
fig=plt.figure()
axLS.append(fig.add_axes(rectLS[0]))
for i in [1,2,3]:
axLS.append(fig.add_axes(rectLS[i],sharey=axLS[-1]))
axLS.append(fig.add_axes(rectLS[4]))
for i in [1,2,3]:
axLS.append(fig.add_axes(rectLS[i+4],sharex=axLS[i],sharey=axLS[-1]))
axLS.append(fig.add_axes(rectLS[8]))
for i in [5,6,7]:
axLS.append(fig.add_axes(rectLS[i+4],sharex=axLS[i],sharey=axLS[-1]))
axLS.append(fig.add_axes(rectLS[12]))
for i in [9,10,11]:
axLS.append(fig.add_axes(rectLS[i+4],sharex=axLS[i],sharey=axLS[-1]))
If you don't need to share axes, then simply axLS=map(fig.add_axes, rectLS)
Try this ..
txtview.setCompoundDrawablesWithIntrinsicBounds(
R.drawable.image, 0, 0, 0);
Also see this.. http://developer.android.com/reference/android/widget/TextView.html
Try this in xml file
<TextView
android:id="@+id/txtStatus"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:drawableLeft="@drawable/image"
android:drawablePadding="5dp"
android:maxLines="1"
android:text="@string/name"/>
parseDouble() method is used to initialise a STRING (which should contains some numerical value)....the value it returns is of primitive data type, like int, float, etc.
But valueOf() creates an object of Wrapper class. You have to unwrap it in order to get the double value. It can be compared with a chocolate. The manufacturer wraps the chocolate with some foil or paper to prevent from pollution. The user takes the chocolate, removes and throws the wrapper and eats it.
Observe the following conversion.
int k = 100;
Integer it1 = new Integer(k);
The int data type k is converted into an object, it1 using Integer class. The it1 object can be used in Java programming wherever k is required an object.
The following code can be used to unwrap (getting back int from Integer object) the object it1.
int m = it1.intValue();
System.out.println(m*m); // prints 10000
//intValue() is a method of Integer class that returns an int data type.
You just add this code
$clasa = (object) array(
'e1' => array('nume' => 'Nitu', 'prenume' => 'Andrei', 'sex' => 'm', 'varsta' => 23),
'e2' => array('nume' => 'Nae', 'prenume' => 'Ionel', 'sex' => 'm', 'varsta' => 27),
'e3' => array('nume' => 'Noman', 'prenume' => 'Alice', 'sex' => 'f', 'varsta' => 22),
'e4' => array('nume' => 'Geangos', 'prenume' => 'Bogdan', 'sex' => 'm', 'varsta' => 23),
'e5' => array('nume' => 'Vasile', 'prenume' => 'Mihai', 'sex' => 'm', 'varsta' => 25)
);
If you want to see is this stdClass object just call this
print_r($clasa);
If you want to convert an array to object code will be
$arr = array('a'=>'apple','b'=>'ball');
$arr = (object) $arr;
You don't need to use stdClass. It will automatically converted to stdClass
Just want to share what worked on my end, in case it would be able to help someone else too. Alternatively based on Paty Lustosa's answer above, please allow me to add another approach derived from this site where he used an ajax approach for the source method
http://salman-w.blogspot.ca/2013/12/jquery-ui-autocomplete-examples.html#example-3
The kicker is the resulting "string" or json format from your php script (listing.php below) that derives the result set to be shown in the autocomplete field should follow something like this:
{"list":[
{"value": 1, "label": "abc"},
{"value": 2, "label": "def"},
{"value": 3, "label": "ghi"}
]}
Then on the source portion of the autocomplete method:
source: function(request, response) {
$.getJSON("listing.php", {
term: request.term
}, function(data) {
var array = data.error ? [] : $.map(data.list, function(m) {
return {
label: m.label,
value: m.value
};
});
response(array);
});
},
select: function (event, ui) {
$("#autocomplete_field").val(ui.item.label); // display the selected text
$("#field_id").val(ui.item.value); // save selected id to hidden input
return false;
}
Hope this helps... all the best!
Latest version of SpringBoot makes uploading multiple files very easy also. On the browser side you just need the standard HTML upload form, but with multiple input elements (one per file to upload, which is very important), all having the same element name (name="files" for the example below)
Then in your Spring @Controller class on the server all you need is something like this:
@RequestMapping(value = "/upload", method = RequestMethod.POST)
public @ResponseBody ResponseEntity<?> upload(
@RequestParam("files") MultipartFile[] uploadFiles) throws Exception
{
...now loop over all uploadFiles in the array and do what you want
return new ResponseEntity<>(HttpStatus.OK);
}
Those are the tricky parts. That is, knowing to create multiple input elements each named "files", and knowing to use a MultipartFile[] (array) as the request parameter are the tricky things to know, but it's just that simple. I won't get into how to process a MultipartFile entry, because there's plenty of docs on that already.
This error is usually caused by the missing Visual C++ Redistributable file
, which is a required dependency for most of the application on Windows Computer.
Download Visual C++ Redistributable from here and install it. After installing this, Reboot the system.
It is quite easy to solve your task. You should create and use a new variable for summing values of the "Doctor Payment" column.
In your case the variable can be declared like this:
<variable name="total" class="java.lang.Integer" calculation="Sum">
<variableExpression><![CDATA[$F{payment}]]></variableExpression>
</variable>
The working example.
CSV datasource:
doctor_id,payment A1,123 B1,223 C2,234 D3,678 D1,343
The template:
<?xml version="1.0" encoding="UTF-8"?>
<jasperReport ...>
<queryString>
<![CDATA[]]>
</queryString>
<field name="doctor_id" class="java.lang.String"/>
<field name="payment" class="java.lang.Integer"/>
<variable name="total" class="java.lang.Integer" calculation="Sum">
<variableExpression><![CDATA[$F{payment}]]></variableExpression>
</variable>
<columnHeader>
<band height="20" splitType="Stretch">
<staticText>
<reportElement x="0" y="0" width="100" height="20"/>
<box leftPadding="10"/>
<textElement textAlignment="Center" verticalAlignment="Middle">
<font size="10" isBold="true" isItalic="true"/>
</textElement>
<text><![CDATA[Doctor ID]]></text>
</staticText>
<staticText>
<reportElement x="100" y="0" width="100" height="20"/>
<box leftPadding="10"/>
<textElement textAlignment="Center" verticalAlignment="Middle">
<font size="10" isBold="true" isItalic="true"/>
</textElement>
<text><![CDATA[Doctor Payment]]></text>
</staticText>
</band>
</columnHeader>
<detail>
<band height="20" splitType="Stretch">
<textField>
<reportElement x="0" y="0" width="100" height="20"/>
<box leftPadding="10"/>
<textElement/>
<textFieldExpression><![CDATA[$F{doctor_id}]]></textFieldExpression>
</textField>
<textField>
<reportElement x="100" y="0" width="100" height="20"/>
<box leftPadding="10"/>
<textElement/>
<textFieldExpression><![CDATA[$F{payment}]]></textFieldExpression>
</textField>
</band>
</detail>
<summary>
<band height="20">
<staticText>
<reportElement x="0" y="0" width="100" height="20"/>
<box leftPadding="10"/>
<textElement>
<font isBold="true"/>
</textElement>
<text><![CDATA[Total]]></text>
</staticText>
<textField>
<reportElement x="100" y="0" width="100" height="20"/>
<box leftPadding="10"/>
<textElement>
<font isBold="true" isItalic="true"/>
</textElement>
<textFieldExpression><![CDATA[$V{total}]]></textFieldExpression>
</textField>
</band>
</summary>
</jasperReport>
The result will be:
You can find a lot of info in the JasperReports Ultimate Guide.
I believe best practice these days is H/5 * * * *
, which means every 5 minutes with a hashing factor to avoid all jobs starting at EXACTLY the same time.
Preferred way to change the appearance/whatever of row views once the ListView is drawn is to change something in the data ListView draws from (the array of objects that is passed into your Adapter) and make sure to account for that in your getView() function, then redraw the ListView by calling
notifyDataSetChanged();
EDIT: while there is a way to do this, if you need to do this chances are doing something wrong. While are few edge cases I can think about, generally using notifyDataSetChanged()
and other built in mechanisms is a way to go.
EDIT 2: One of the common mistakes people make is trying to come up with their own way to respond to user clicking/selecting a row in the ListView, as in one of the comments to this post. There is an existing way to do this. Here's how:
mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
/* Parameters
parent: The AdapterView where the click happened.
view: The view within the AdapterView that was clicked (this will be a view provided by the adapter)
position: The position of the view in the adapter.
id: The row id of the item that was clicked. */
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
//your code here
}
});
ListView has a lot of build-in functionality and there is no need to reinvent the wheel for simpler cases. Since ListView extends AdapterView, you can set the same Listeners, such as OnItemClickListener as in the example above.
You are after implicit make rules.
Just pass your regression model into the following function:
plot_coeffs <- function(mlr_model) {
coeffs <- coefficients(mlr_model)
mp <- barplot(coeffs, col="#3F97D0", xaxt='n', main="Regression Coefficients")
lablist <- names(coeffs)
text(mp, par("usr")[3], labels = lablist, srt = 45, adj = c(1.1,1.1), xpd = TRUE, cex=0.6)
}
Use as follows:
model <- lm(Petal.Width ~ ., data = iris)
plot_coeffs(model)
You can use .filter()
method of the Array
object:
var filtered = workItems.filter(function(element) {
// Create an array using `.split()` method
var cats = element.category.split(' ');
// Filter the returned array based on specified filters
// If the length of the returned filtered array is equal to
// length of the filters array the element should be returned
return cats.filter(function(cat) {
return filtersArray.indexOf(cat) > -1;
}).length === filtersArray.length;
});
Some old browsers like IE8 doesn't support .filter()
method of the Array
object, if you are using jQuery you can use .filter()
method of jQuery object.
jQuery version:
var filtered = $(workItems).filter(function(i, element) {
var cats = element.category.split(' ');
return $(cats).filter(function(_, cat) {
return $.inArray(cat, filtersArray) > -1;
}).length === filtersArray.length;
});
Target parameters:
float width = 1024;
float height = 768;
var brush = new SolidBrush(Color.Black);
Your original file:
var image = new Bitmap(file);
Target sizing (scale factor):
float scale = Math.Min(width / image.Width, height / image.Height);
The resize including brushing canvas first:
var bmp = new Bitmap((int)width, (int)height);
var graph = Graphics.FromImage(bmp);
// uncomment for higher quality output
//graph.InterpolationMode = InterpolationMode.High;
//graph.CompositingQuality = CompositingQuality.HighQuality;
//graph.SmoothingMode = SmoothingMode.AntiAlias;
var scaleWidth = (int)(image.Width * scale);
var scaleHeight = (int)(image.Height * scale);
graph.FillRectangle(brush, new RectangleF(0, 0, width, height));
graph.DrawImage(image, ((int)width - scaleWidth)/2, ((int)height - scaleHeight)/2, scaleWidth, scaleHeight);
And don't forget to do a bmp.Save(filename)
to save the resulting file.
Even though the above solutions do work,This answer is for you in case you want to reverse the clock instead of undoing a git pull.I mean if you want to get your exact repo the way it was X
Mins back then run the command
git reset --hard branchName@{"X Minutes ago"}
Note: before you actually go ahead and run this command please only try this command if you are sure about the time you want to go back to and heres about my situation.
I was currently on a branch develop
, I was supposed to checkout to a new branch and pull in another branch lets say Branch A
but I accidentally ran
git pull origin B
before checking out.
so to undo this change I tried this command
git reset --hard develop@{"10 Minutes ago"}
if you are on windows cmd and get error: unknown switch `e
try adding quotes like this
git reset --hard 'develop@{"10 Minutes ago"}'
I use RegexBuddy for debbuging my regexes it has almost all languages very usefull. Than copy/paste for the targeted language. Terrific tool and not very expensive.
So I copy/pasted your regex and your issue is that [,] are special characters in regex, so you need to escape them. So the regex should be : /!@#$^&%*()+=-[\x5B\x5D]\/{}|:<>?,./im
bash -n scriptname
Perhaps an obvious caveat: this validates syntax but won't check if your bash script tries to execute a command that isn't in your path, like ech hello
instead of echo hello
.
MS Expression Encoder can do mp4/h.264. not sure about ogg though.
This code:
import os
dn = os.path.dirname(os.path.realpath(__file__))
sets "dn" to the name of the directory containing the currently executing script. This code:
fn = os.path.join(dn,"vcb.init")
fp = open(fn,"r")
sets "fn" to "script_dir/vcb.init" (in a platform independent manner) and opens that file for reading by the currently executing script.
Note that "the currently executing script" is somewhat ambiguous. If your whole program consists of 1 script, then that's the currently executing script and the "sys.path[0]" solution works fine. But if your app consists of script A, which imports some package "P" and then calls script "B", then "P.B" is currently executing. If you need to get the directory containing "P.B", you want the "os.path.realpath(__file__)
" solution.
"__file__
" just gives the name of the currently executing (top-of-stack) script: "x.py". It doesn't
give any path info. It's the "os.path.realpath" call that does the real work.
The difference between constructor
and getInitialState
is the difference between ES6 and ES5 itself.
getInitialState
is used with React.createClass
and
constructor
is used with React.Component
.
Hence the question boils down to advantages/disadvantages of using ES6 or ES5.
Let's look at the difference in code
ES5
var TodoApp = React.createClass({
propTypes: {
title: PropTypes.string.isRequired
},
getInitialState () {
return {
items: []
};
}
});
ES6
class TodoApp extends React.Component {
constructor () {
super()
this.state = {
items: []
}
}
};
There is an interesting reddit thread regarding this.
React community is moving closer to ES6. Also it is considered as the best practice.
There are some differences between React.createClass
and React.Component
. For instance, how this
is handled in these cases. Read more about such differences in this blogpost and facebook's content on autobinding
constructor
can also be used to handle such situations. To bind methods to a component instance, it can be pre-bonded in the constructor
. This is a good material to do such cool stuff.
Some more good material on best practices
Best Practices for Component State in React.js
Converting React project from ES5 to ES6
Update: April 9, 2019,:
With the new changes in Javascript class API, you don't need a constructor.
You could do
class TodoApp extends React.Component {
this.state = {items: []}
};
This will still get transpiled to constructor format, but you won't have to worry about it. you can use this format that is more readable.
With React Hooks
From React version 16.8, there's a new API Called hooks.
Now, you don't even need a class component to have a state. It can even be done in a functional component.
import React, { useState } from 'react';
function TodoApp () {
const items = useState([]);
Note that the initial state is passed as an argument to useState
; useState([])
Read more about react hooks from the official docs
first, give the div an id. Then, call function appendClass:
<script language="javascript">
function appendClass(elementId, classToAppend){
var oldClass = document.getElementById(elementId).getAttribute("class");
if (oldClass.indexOf(classToAdd) == -1)
{
document.getElementById(elementId).setAttribute("class", classToAppend);
}
}
</script>
I modifie this list and add a List to the samples try this
Pseudocode
Sample {
List<String> values;
List<String> getList() {
return values}
}
for(Sample s : list) {
if(s.getString.getList.contains("three") {
return s;
}
}
To say "nodemon" would answer the question.
But on how only to kill (all) node demon(s), the following works for me:
pkill -HUP node
Here's the complete answer for the future reader. Note that this is only possible in Laravel 5+.
First of all you'll need the doctrine/dbal package:
composer require doctrine/dbal
Now in your migration you can do this to make the column nullable:
public function up()
{
Schema::table('users', function (Blueprint $table) {
// change() tells the Schema builder that we are altering a table
$table->integer('user_id')->unsigned()->nullable()->change();
});
}
You may be wondering how to revert this operation. Sadly this syntax is not supported:
// Sadly does not work :'(
$table->integer('user_id')->unsigned()->change();
This is the correct syntax to revert the migration:
$table->integer('user_id')->unsigned()->nullable(false)->change();
Or, if you prefer, you can write a raw query:
public function down()
{
/* Make user_id un-nullable */
DB::statement('UPDATE `users` SET `user_id` = 0 WHERE `user_id` IS NULL;');
DB::statement('ALTER TABLE `users` MODIFY `user_id` INTEGER UNSIGNED NOT NULL;');
}
Hopefully you'll find this answer useful. :)
http://www.youtube.com/watch?v=a59LvC6BOuk
Use the above link
private void btnopen_Click(object sender, EventArgs e){
OpenFileDialog openFileDialog1 = new OpenFileDialog();
if (openFileDialog1.ShowDialog() == System.Windows.Forms.DialogResult.OK){
axAcroPDF1.src = openFileDialog1.FileName;
}
}
You can add Row in a single line
DataTable table = new DataTable();
table.Columns.Add("Dosage", typeof(int));
table.Columns.Add("Drug", typeof(string));
table.Columns.Add("Patient", typeof(string));
table.Columns.Add("Date", typeof(DateTime));
// Here we add five DataRows.
table.Rows.Add(25, "Indocin", "David", DateTime.Now);
table.Rows.Add(50, "Enebrel", "Sam", DateTime.Now);
table.Rows.Add(10, "Hydralazine", "Christoff", DateTime.Now);
table.Rows.Add(21, "Combivent", "Janet", DateTime.Now);
table.Rows.Add(100, "Dilantin", "Melanie", DateTime.Now);
If you are using LoaderManager try with this statement:
getLoaderManager().restartLoader(0, null, this);
Quick work around
Simply enclose the list within a new list, as done for col2 in the data frame below. The reason it works is that python takes the outer list (of lists) and converts it into a column as if it were containing normal scalar items, which is lists in our case and not normal scalars.
mydict={'col1':[1,2,3],'col2':[[1, 4], [2, 5], [3, 6]]}
data=pd.DataFrame(mydict)
data
col1 col2
0 1 [1, 4]
1 2 [2, 5]
2 3 [3, 6]
I managed to find the correct one. It is below.
bool val1 = System.Web.HttpContext.Current.User.Identity.IsAuthenticated
EDIT
The credit of this edit goes to @Gianpiero Caretti who suggested this in comment.
bool val1 = (System.Web.HttpContext.Current.User != null) && System.Web.HttpContext.Current.User.Identity.IsAuthenticated
VAR="$(cat <<'VAREOF'
abc'asdf"
$(dont-execute-this)
foo"bar"''
VAREOF
)"
echo "$(cat <<'SQLEOF'
xxx''xxx'xxx'xx 123123 123123
abc'asdf"
$(dont-execute-this)
foo"bar"''
SQLEOF
)"
You can use TIMESTAMPDIFF(unit, datetime_expr1, datetime_expr2)
function:
SELECT TIMESTAMPDIFF(YEAR, '1970-02-01', CURDATE()) AS age
use .something without td or th
<!DOCTYPE html>_x000D_
<html lang="en">_x000D_
<head>_x000D_
<title>Bootstrap Example</title> _x000D_
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css"> _x000D_
<style>_x000D_
.something {_x000D_
width: 90px;_x000D_
background: red;_x000D_
}_x000D_
</style>_x000D_
</head>_x000D_
<body>_x000D_
_x000D_
<div class="container">_x000D_
<h2>Fixed width column</h2> _x000D_
<table class="table table-bordered">_x000D_
<thead>_x000D_
<tr>_x000D_
<th class="something">Firstname</th>_x000D_
<th>Lastname</th>_x000D_
<th>Email</th>_x000D_
</tr>_x000D_
</thead>_x000D_
<tbody>_x000D_
<tr>_x000D_
<td>John</td>_x000D_
<td>Doe</td>_x000D_
<td>[email protected]</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>Mary</td>_x000D_
<td>Moe</td>_x000D_
<td>[email protected]</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>July</td>_x000D_
<td>Dooley</td>_x000D_
<td>[email protected]</td>_x000D_
</tr>_x000D_
</tbody>_x000D_
</table>_x000D_
</div>_x000D_
_x000D_
</body>_x000D_
</html>
_x000D_
I am not sure if this was possible in TypeScript when the question was originally asked, but my preferred solution is with generics:
class Zoo<T extends Animal> {
constructor(public readonly AnimalClass: new () => T) {
}
}
This way variables penguin
and lion
infer concrete type Penguin
or Lion
even in the TypeScript intellisense.
const penguinZoo = new Zoo(Penguin);
const penguin = new penguinZoo.AnimalClass(); // `penguin` is of `Penguin` type.
const lionZoo = new Zoo(Lion);
const lion = new lionZoo.AnimalClass(); // `lion` is `Lion` type.
Here I am going to export 3 tables from database named myDB in an sql file named table.sql
mysqldump -u root -p myDB table1 table2 table3 > table.sql
There are three ways to save objects from your R session:
The save.image()
function will save all objects currently in your R session:
save.image(file="1.RData")
These objects can then be loaded back into a new R session using the load()
function:
load(file="1.RData")
If you want to save some, but not all objects, you can use the save()
function:
save(city, country, file="1.RData")
Again, these can be reloaded into another R session using the load()
function:
load(file="1.RData")
If you want to save a single object you can use the saveRDS()
function:
saveRDS(city, file="city.rds")
saveRDS(country, file="country.rds")
You can load these into your R session using the readRDS()
function, but you will need to assign the result into a the desired variable:
city <- readRDS("city.rds")
country <- readRDS("country.rds")
But this also means you can give these objects new variable names if needed (i.e. if those variables already exist in your new R session but contain different objects):
city_list <- readRDS("city.rds")
country_vector <- readRDS("country.rds")
If I understand your problem correctly, you are calling a method instead of passing it as a parameter. Try the following:
myTimer.Elapsed += PlayMusicEvent;
where
public void PlayMusicEvent(object sender, ElapsedEventArgs e)
{
music.player.Stop();
System.Timers.Timer myTimer = (System.Timers.Timer)sender;
myTimer.Stop();
}
But you need to think about where to store your note.
According to nginx documentation
there is no syntax for NOT matching a regular expression. Instead, match the target regular expression and assign an empty block, then use location / to match anything else
So you could define something like
location ~ (dir1|file2\.php) {
# empty
}
location / {
rewrite ^/(.*) http://example.com/$1 permanent;
}
In my case after getting this message I did the checkout command and was given this message:
Your branch is based on 'origin/myBranch', but the upstream is gone.
(use "git branch --unset-upstream" to fixup)
After running this command I was back to normal.
$this->db->like()
This method enables you to generate LIKE clauses, useful for doing searches.
$this->db->like('title', 'match');
Produces: WHERE title
LIKE '%match%'
If you want to control where the wildcard (%) is placed, you can use an optional third argument. Your options are ‘before’, ‘after’, ‘none’ and ‘both’ (which is the default).
$this->db->like('title', 'match', 'before');
Produces: WHERE title
LIKE '%match'
$this->db->like('title', 'match', 'after');
Produces: WHERE title
LIKE 'match%'
$this->db->like('title', 'match', 'none');
Produces: WHERE title
LIKE 'match'
$this->db->like('title', 'match', 'both');
Produces: WHERE title
LIKE '%match%'
In the child
<input
type="number"
class="form-control"
id="phoneNumber"
placeholder
v-model="contact_number"
v-on:input="(event) => this.$emit('phoneNumber', event.target.value)"
/>
data(){
return {
contact_number : this.contact_number_props
}
},
props : ['contact_number_props']
In parent
<contact-component v-on:phoneNumber="eventPhoneNumber" :contact_number_props="contact_number"></contact-component>
methods : {
eventPhoneNumber (value) {
this.contact_number = value
}
match_parent, which means that the view wants to be as big as its parent (minus padding).
wrap_content, which means that the view wants to be just big enough to enclose its content (plus padding)
For sake of better illustration, I have created a sample layout that demonstrate this concept. To see it's effect, I added a border of each textView content.
In "Match parent" textView content, we can see it's layout width spread out of it's parent whole length.
But we can see in "Wrap Content" textView content, it's layout width wrapped in of it's content(Wrap Content) length.
Lets see what happens if we won't use $this and try to have instance variables and constructor arguments with the same name with the following code snippet
<?php
class Student {
public $name;
function __construct( $name ) {
$name = $name;
}
};
$tom = new Student('Tom');
echo $tom->name;
?>
It echos nothing but
<?php
class Student {
public $name;
function __construct( $name ) {
$this->name = $name; // Using 'this' to access the student's name
}
};
$tom = new Student('Tom');
echo $tom->name;
?>
this echoes 'Tom'
The bottom statement is equivalent to:
.half {
flex-grow: 0;
flex-shrink: 0;
flex-basis: 50%;
}
Which, in this case, would be equivalent as the box is not allowed to flex and therefore retains the initial width set by flex-basis.
Flex-basis defines the default size of an element before the remaining space is distributed so if the element were allowed to flex (grow/shrink) it may not be 50% of the width of the page.
I've found that I regularly return to https://css-tricks.com/snippets/css/a-guide-to-flexbox/ for help regarding flexbox :)
I just happened to look for something similar and came up with this:
std::cout << std::setfill(' ') << std::setw(n) << ' ';
You can use native bootstrap validation states (No Custom CSS!):
<div class="form-group has-feedback">
<label class="control-label" for="inputSuccess2">Name</label>
<input type="text" class="form-control" id="inputSuccess2"/>
<span class="glyphicon glyphicon-search form-control-feedback"></span>
</div>
For a full discussion, see my answer to Add a Bootstrap Glyphicon to Input Box
You can use the .input-group
class like this:
<div class="input-group">
<input type="text" class="form-control"/>
<span class="input-group-addon">
<i class="fa fa-search"></i>
</span>
</div>
For a full discussion, see my answer to adding Twitter Bootstrap icon to Input box
You can still use .input-group
for positioning but just override the default styling to make the two elements appear separate.
Use a normal input group but add the class input-group-unstyled
:
<div class="input-group input-group-unstyled">
<input type="text" class="form-control" />
<span class="input-group-addon">
<i class="fa fa-search"></i>
</span>
</div>
Then change the styling with the following css:
.input-group.input-group-unstyled input.form-control {
-webkit-border-radius: 4px;
-moz-border-radius: 4px;
border-radius: 4px;
}
.input-group-unstyled .input-group-addon {
border-radius: 4px;
border: 0px;
background-color: transparent;
}
Also, these solutions work for any input size
In python, A dynamic array is an 'array' from the array module. E.g.
from array import array
x = array('d') #'d' denotes an array of type double
x.append(1.1)
x.append(2.2)
x.pop() # returns 2.2
This datatype is essentially a cross between the built-in 'list' type and the numpy 'ndarray' type. Like an ndarray, elements in arrays are C types, specified at initialization. They are not pointers to python objects; this may help avoid some misuse and semantic errors, and modestly improves performance.
However, this datatype has essentially the same methods as a python list, barring a few string & file conversion methods. It lacks all the extra numerical functionality of an ndarray.
See https://docs.python.org/2/library/array.html for details.
If you have 2 installations of the JVM. Place the version upfront. Linux : export PATH=/usr/lib/jvm/java-8-oracle/bin:$PATH
This eliminates the ambiguity.
I think Amith Koujalgi is correct but also, in cases where the webservice responses are in JSON then it might be more useful to see the results in a clean JSON format instead of a very long string. Just add | grep }| python -mjson.tool to the end of curl commands here is two examples:
GET approach with JSON result
curl -i -H "Accept: application/json" http://someHostName/someEndpoint | grep }| python -mjson.tool
POST approach with JSON result
curl -X POST -H "Accept: Application/json" -H "Content-Type: application/json" http://someHostName/someEndpoint -d '{"id":"IDVALUE","name":"Mike"}' | grep }| python -mjson.tool
Thanks to a comment by zerkms, I was able to notice my stupid mistake:
I had onItemClick(e, item)
when I should have had onItemClick(item, e)
.
under etc/apache2/apache2.conf
, you can find one or more blocks that describe the server directories and permissions
As an example, this is the default configuration
<Directory /var/www/>
Options Indexes FollowSymLinks
AllowOverride None
Require all granted
</Directory>
you can replicate this but change the directory path /var/www/
with the new directory.
Finally, you need to restart the apache server, you can do that from a terminal with the command: sudo service apache2 restart
I had an issue where one of the nested dependency had an npm audit vulnerability, but I still wanted to maintain the parent dependency version. the npm shrinkwrap solution didn't work for me, so what I did to override the nested dependency version:
Try to give max-content
for parent's height.
.parent{
height: max-content;
}
Is there a simple way to convert a LocalDate (introduced with Java 8) to java.util.Date object? By 'simple', I mean simpler than this
Nope. You did it properly, and as concisely as possible.
java.util.Date.from( // Convert from modern java.time class to troublesome old legacy class. DO NOT DO THIS unless you must, to inter operate with old code not yet updated for java.time.
myLocalDate // `LocalDate` class represents a date-only, without time-of-day and without time zone nor offset-from-UTC.
.atStartOfDay( // Let java.time determine the first moment of the day on that date in that zone. Never assume the day starts at 00:00:00.
ZoneId.of( "America/Montreal" ) // Specify time zone using proper name in `continent/region` format, never 3-4 letter pseudo-zones such as “PST”, “CST”, “IST”.
) // Produce a `ZonedDateTime` object.
.toInstant() // Extract an `Instant` object, a moment always in UTC.
)
Read below for issues, and then think about it. How could it be simpler? If you ask me what time does a date start, how else could I respond but ask you “Where?”?. A new day dawns earlier in Paris FR than in Montréal CA, and still earlier in Kolkata IN, and even earlier in Auckland NZ, all different moments.
So in converting a date-only (LocalDate
) to a date-time we must apply a time zone (ZoneId
) to get a zoned value (ZonedDateTime
), and then move into UTC (Instant
) to match the definition of a java.util.Date
.
Firstly, avoid the old legacy date-time classes such as java.util.Date
whenever possible. They are poorly designed, confusing, and troublesome. They were supplanted by the java.time classes for a reason, actually, for many reasons.
But if you must, you can convert to/from java.time types to the old. Look for new conversion methods added to the old classes.
java.util.Date
? java.time.LocalDate
Keep in mind that a java.util.Date
is a misnomer as it represents a date plus a time-of-day, in UTC. In contrast, the LocalDate
class represents a date-only value without time-of-day and without time zone.
Going from java.util.Date
to java.time means converting to the equivalent class of java.time.Instant
. The Instant
class represents a moment on the timeline in UTC with a resolution of nanoseconds (up to nine (9) digits of a decimal fraction).
Instant instant = myUtilDate.toInstant();
The LocalDate
class represents a date-only value without time-of-day and without time zone.
A time zone is crucial in determining a date. For any given moment, the date varies around the globe by zone. For example, a few minutes after midnight in Paris France is a new day while still “yesterday” in Montréal Québec.
So we need to move that Instant
into a time zone. We apply ZoneId
to get a ZonedDateTime
.
ZoneId z = ZoneId.of( "America/Montreal" );
ZonedDateTime zdt = instant.atZone( z );
From there, ask for a date-only, a LocalDate
.
LocalDate ld = zdt.toLocalDate();
java.time.LocalDate
? java.util.Date
To move the other direction, from a java.time.LocalDate
to a java.util.Date
means we are going from a date-only to a date-time. So we must specify a time-of-day. You probably want to go for the first moment of the day. Do not assume that is 00:00:00
. Anomalies such as Daylight Saving Time (DST) means the first moment may be another time such as 01:00:00
. Let java.time determine that value by calling atStartOfDay
on the LocalDate
.
ZonedDateTime zdt = myLocalDate.atStartOfDay( z );
Now extract an Instant
.
Instant instant = zdt.toInstant();
Convert that Instant
to java.util.Date
by calling from( Instant )
.
java.util.Date d = java.util.Date.from( instant );
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date
, Calendar
, & SimpleDateFormat
.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.*
classes. Hibernate 5 & JPA 2.2 support java.time.
Where to obtain the java.time classes?
The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval
, YearWeek
, YearQuarter
, and more.