In this context, the word "stub" is used in place of "mock", but for the sake of clarity and precision, the author should have used "mock", because "mock" is a sort of stub, but for testing. To avoid further confusion, we need to define what a stub is.
In the general context, a stub is a piece of program (typically a function or an object) that encapsulates the complexity of invoking another program (usually located on another machine, VM, or process - but not always, it can also be a local object). Because the actual program to invoke is usually not located on the same memory space, invoking it requires many operations such as addressing, performing the actual remote invocation, marshalling/serializing the data/arguments to be passed (and same with the potential result), maybe even dealing with authentication/security, and so on. Note that in some contexts, stubs are also called proxies (such as dynamic proxies in Java).
A mock is a very specific and restrictive kind of stub, because a mock is a replacement of another function or object for testing. In practice we often use mocks as local programs (functions or objects) to replace a remote program in the test environment. In any case, the mock may simulate the actual behaviour of the replaced program in a restricted context.
Most famous kinds of stubs are obviously for distributed programming, when needing to invoke remote procedures (RPC) or remote objects (RMI, CORBA). Most distributed programming frameworks/libraries automate the generation of stubs so that you don't have to write them manually. Stubs can be generated from an interface definition, written with IDL for instance (but you can also use any language to define interfaces).
Typically, in RPC, RMI, CORBA, and so on, one distinguishes client-side stubs, which mostly take care of marshaling/serializing the arguments and performing the remote invocation, and server-side stubs, which mostly take care of unmarshaling/deserializing the arguments and actually execute the remote function/method. Obviously, client stubs are located on the client side, while sever stubs (often called skeletons) are located on the server side.
Writing good efficient and generic stubs becomes quite challenging when dealing with object references. Most distributed object frameworks such as RMI and CORBA deal with distributed objects references, but that's something most programmers avoid in REST environments for instance. Typically, in REST environments, JavaScript programmers make simple stub functions to encapsulate the AJAX invocations (object serialization being supported by JSON.parse
and JSON.stringify
). The Swagger Codegen project provides an extensive support for automatically generating REST stubs in various languages.
You can just use the column name directly:
df <- data.frame(A=1:10, B=2:11, C=3:12)
fun1 <- function(x, column){
max(x[,column])
}
fun1(df, "B")
fun1(df, c("B","A"))
There's no need to use substitute, eval, etc.
You can even pass the desired function as a parameter:
fun1 <- function(x, column, fn) {
fn(x[,column])
}
fun1(df, "B", max)
Alternatively, using [[
also works for selecting a single column at a time:
df <- data.frame(A=1:10, B=2:11, C=3:12)
fun1 <- function(x, column){
max(x[[column]])
}
fun1(df, "B")
Best way to upload a large file not use phpmyadmin . cause phpmyadin at first upload the file using php upload class then execute sql that cause most of the time its time out happened.
best way is : enter wamp folder>bin>mysql>bin dirrectory then write this line
mysql -u root -p listnames < latestdb.sql here listnames is the database name at first please create the empty database and the latestdb.sql is your sql file name where your data present .
but one important thing is if your database file has unicode data . you must need to open your latestdb.sql file and one line before any line . the line is :
SET NAMES utf8; then your command mode run this script code
BULK INSERT TextData
FROM 'E:\filefromabove.txt'
WITH
(
FIRSTROW = 2,
FIELDTERMINATOR = '|', --CSV field delimiter
ROWTERMINATOR = '\n', --Use to shift the control to next row
ERRORFILE = 'E:\ErrorRows.csv',
TABLOCK
)
islice
has the advantage that it doesn't need to copy part of the list
from itertools import islice
for day in islice(days, 1, None):
...
you can also use this code in your style.xml file so you don't need to write anything else in your activity.java
<!-- Base application theme. -->
<style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">
<!-- Customize your theme here. -->
<item name="colorPrimary">@color/colorPrimary</item>
<item name="colorPrimaryDark">@color/colorPrimaryDark</item>
<item name="colorAccent">@color/colorAccent</item>
<item name="android:windowAnimationStyle">@style/AppTheme.WindowTransition</item>
</style>
<!-- Setting window animation -->
<style name="AppTheme.WindowTransition">
<item name="android:windowEnterAnimation">@android:anim/fade_in</item>
<item name="android:windowExitAnimation">@android:anim/fade_out</item>
</style>
As Get-Date
returns a DateTime object you are able to compare them directly. An example:
(get-date 2010-01-02) -lt (get-date 2010-01-01)
will return false.
Taking a column is easy with the map function.
// a two-dimensional array
var two_d = [[1,2,3],[4,5,6],[7,8,9]];
// take the third column
var col3 = two_d.map(function(value,index) { return value[2]; });
Why bother with the slice at all? Just filter the matrix to find the rows of interest.
var interesting = two_d.filter(function(value,index) {return value[1]==5;});
// interesting is now [[4,5,6]]
Sadly, filter and map are not natively available on IE9 and lower. The MDN documentation provides implementations for browsers without native support.
While ireport does not officially support java8, there is a fairly simple way to make ireport (tested with ireport 5.1) work with Java 8. The problem is actually in netbeans. There is a very simple patch, assuming you don't care about the improved security in Java 8:
I didn't even use the exact netbeans source used by ireport. I just downloaded the latest WeakListenerImpl.java in full from the above repository, and compiled it in the ireport directory with platform9/lib/org-openide-util.jar in the compiler classpath
cd blah/blah/iReport-5.1.0
wget http://hg.netbeans.org/jet-main/raw-file/3238e03c676f/openide.util/src/org/openide/util/WeakListenerImpl.java
javac -d . -cp platform9/lib/org-openide-util.jar WeakListenerImpl.java
zip -r platform9/lib/org-openide-util.jar org
I am avoiding running eclipse just to edit jasper reports as long as I can. The netbeans based ireport is so much lighter weight. Running Eclipse is like using emacs.
The easiest solution in Bash:
$ s='"abc"'
$ echo $s
"abc"
$ echo "${s:1:-1}"
abc
This is called substring expansion (see Gnu Bash Manual and search for ${parameter:offset:length}
). In this example it takes the substring from s
starting at position 1 and ending at the second last position. This is due to the fact that if length
is a negative value it is interpreted as a backwards running offset from the end of parameter
.
Using hr
created two lines for me, one solid and one dotted.
I found that this worked quite well:
div {
border-top: 1px dotted #cccccc;
color: #ffffff;
background-color: #ffffff;
height: 1px;
width: 95%;
}
Plus, because you can make the width a percentage, it will always have some space on either side (even when you resize the window).
Next matches all greater or equal to 11100
:
^([1-9][1-9][1-9]\d{2}\d*|[1-9][2-9]\d{3}\d*|[2-9]\d{4}\d*|\d{6}\d*)$
^([5-9]\d{1}\d*|\d{3}\d*)$
See pattern and modify to any number. Also it would be great to find some recursive forward/backward operators for large numbers.
I use
barbeque
, it's great, and supports a very wide range of different barcode formats.
See if you like
its API
.
Sample API:
public static Barcode createCode128(java.lang.String data) throws BarcodeException
Creates a Code 128 barcode that dynamically switches between character sets to give the smallest possible encoding. This will encode all numeric characters, upper and lower case alpha characters and control characters from the standard ASCII character set. The size of the barcode created will be the smallest possible for the given data, and use of this "optimal" encoding will generally give smaller barcodes than any of the other 3 "vanilla" encodings.
@Cascade(org.hibernate.annotations.CascadeType.DELETE_ORPHAN)
Given annotation worked for me. Can have a try
For Example :-
public class Parent{
@Id
@GeneratedValue(strategy=GenerationType.AUTO)
@Column(name="cct_id")
private Integer cct_id;
@OneToMany(cascade=CascadeType.REMOVE, fetch=FetchType.EAGER,mappedBy="clinicalCareTeam", orphanRemoval=true)
@Cascade(org.hibernate.annotations.CascadeType.DELETE_ORPHAN)
private List<Child> childs;
}
public class Child{
@ManyToOne(fetch=FetchType.EAGER)
@JoinColumn(name="cct_id")
private Parent parent;
}
redirect with query string
$('#results').on('click', '.item', function () {
var NestId = $(this).data('id');
// var url = '@Url.Action("Details", "Artists",new { NestId = '+NestId+' })';
var url = '@ Url.Content("~/Artists/Details?NestId =' + NestId + '")'
window.location.href = url;
})
Since I wanted my kafka broker to connect with remote producers and consumers, So I don't want advertised.listener
to be commented out. In my case, (running kafka on kubernetes), I found out that my kafka pod was not assigned any Cluster IP. By removing the line clusterIP: None
from services.yml, the kubernetes assigns an internal-ip to kafka pod. This resolved my issue of LEADER_NOT_AVAILABLE and also remote connection of kafka producers/consumers.
You have to add header,or you will get http 400 error. The code works well on python2.6,centos5.4
code:
import urllib2,json
url = 'http://www.google.com/someservice'
postdata = {'key':'value'}
req = urllib2.Request(url)
req.add_header('Content-Type','application/json')
data = json.dumps(postdata)
response = urllib2.urlopen(req,data)
copy con
to write text, It so easy to write a long textExample:
C:\COPY CON [drive:][path][File name]
.... Content
F6
1 file(s) is copied
In my case password was expired. Change the password and try the step again.
Subscribing to the IUS Community Project Repository
cd ~
curl 'https://setup.ius.io/' -o setup-ius.sh
Run the script:
sudo bash setup-ius.sh
Upgrading mod_php with Apache
This section describes the upgrade process for a system using Apache as the web server and mod_php to execute PHP code. If, instead, you are running Nginx and PHP-FPM, skip ahead to the next section.
Begin by removing existing PHP packages. Press y and hit Enter to continue when prompted.
sudo yum remove php-cli mod_php php-common
Install the new PHP 7 packages from IUS. Again, press y and Enter when prompted.
sudo yum install mod_php70u php70u-cli php70u-mysqlnd
Finally, restart Apache to load the new version of mod_php:
sudo apachectl restart
You can check on the status of Apache, which is managed by the httpd systemd unit, using systemctl:
systemctl status httpd
You would need to manage the referential constraint across databases using a Trigger.
Basically you create an insert, update trigger to verify the existence of the Key in the Primary key table. If the key does not exist then revert the insert or update and then handle the exception.
Example:
Create Trigger dbo.MyTableTrigger ON dbo.MyTable, After Insert, Update
As
Begin
If NOT Exists(select PK from OtherDB.dbo.TableName where PK in (Select FK from inserted) BEGIN
-- Handle the Referential Error Here
END
END
Edited: Just to clarify. This is not the best approach with enforcing referential integrity. Ideally you would want both tables in the same db but if that is not possible. Then the above is a potential work around for you.
This will inspect the docker image and print the layers:
$ docker image inspect nginx -f '{{.RootFS.Layers}}'
[sha256:d626a8ad97a1f9c1f2c4db3814751ada64f60aed927764a3f994fcd88363b659 sha256:82b81d779f8352b20e52295afc6d0eab7e61c0ec7af96d85b8cda7800285d97d sha256:7ab428981537aa7d0c79bc1acbf208c71e57d9678f7deca4267cc03fba26b9c8]
Check out the moment.js
library. It works with browsers as well as with Node.JS. Allows you to write
moment().hour();
or
moment().hours();
without prior writing of any functions.
Given a data URL, you can create an image (either on the page or purely in JS) by setting the src
of the image to your data URL. For example:
var img = new Image;
img.src = strDataURI;
The drawImage()
method of HTML5 Canvas Context lets you copy all or a portion of an image (or canvas, or video) onto a canvas.
You might use it like so:
var myCanvas = document.getElementById('my_canvas_id');
var ctx = myCanvas.getContext('2d');
var img = new Image;
img.onload = function(){
ctx.drawImage(img,0,0); // Or at whatever offset you like
};
img.src = strDataURI;
Edit: I previously suggested in this space that it might not be necessary to use the onload
handler when a data URI is involved. Based on experimental tests from this question, it is not safe to do so. The above sequence—create the image, set the onload
to use the new image, and then set the src
—is necessary for some browsers to surely use the results.
Almost all answers I searched for this issue say that Python on Windows comes with tkinter and tcl already installed, and I had no luck trying to download or install them using pip, or actviestate.com site. I eventually found that when I was installing python using the binary installer, I had unchecked the module related to TCL and tkinter. So, I ran the binary installer again and chose to modify my python version by this time selecting this option. No need to do anything manually then. If you go to your python terminal, then the following commands should show you version of tkinter installed with your Python:
import tkinter
import _tkinter
tkinter._test()
You probably just need to see the ASCII
and EXTENDED ASCII
character sets. As far as I know any of these are allowed in a char
/varchar
field.
If you use nchar
/nvarchar
then it's pretty much any character in any unicode set in the world.
rm -rf *
Don't do it! It's dangerous! MAKE SURE YOU'RE IN THE RIGHT DIRECTORY!
I had this trouble when I moved to Microsoft.EntityFrameworkCore.SqlServer v3.0.0 and Microsoft.EntityFrameworkCore.Tools v3.0.0
When I changed back to v2.2.6 on both libraries, the error went away. This is more of a workaround than a solution but it'll get you up and running till the issue is fixed.
You can create a stored procedure and put the table names in a cursor, then loop through your table names to show the data.
Getting started with stored procedure: http://www.mysqltutorial.org/getting-started-with-mysql-stored-procedures.aspx
Creating a cursor: http://www.mysqltutorial.org/mysql-cursor/
For example,
CREATE PROCEDURE `ShowFromTables`()
BEGIN
DECLARE v_finished INTEGER DEFAULT 0;
DECLARE c_table varchar(100) DEFAULT "";
DECLARE table_cursor CURSOR FOR
SELECT table_name FROM information_schema.tables WHERE table_name like 'wp_1%';
DECLARE CONTINUE HANDLER
FOR NOT FOUND SET v_finished = 1;
OPEN table_cursor;
get_data: LOOP
FETCH table_cursor INTO c_table;
IF v_finished = 1 THEN
LEAVE get_data;
END IF;
SET @s=CONCAT("SELECT * FROM ",c_table,";");
PREPARE stmt FROM @s;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
END LOOP get_data;
CLOSE table_cursor;
END
Then call the stored procedure:
CALL ShowFromTables();
Since Android Studio 3.2 and Android Emulator 27.3.8 - the android emulator is supported by Windows Hypervisor Platform and as stated in the official android developer blog - there is mac support (since OS X v10.10 Yosemite) and windows support (since April 2018 Update). You may find further instructions on the developer blog.
In my opinion, the performance is significantly better than all previous workarounds.
I do believe that putting a regular expression in the str.split parentheses should solve the issue. The Java String.split() method is based upon regular expressions so what you need is:
str = "Hello I'm your String";
String[] splitStr = str.split("\\s+");
What it does
Maven is a "build management tool", it is for defining how your .java
files get compiled to .class
, packaged into .jar
(or .war
or .ear
) files, (pre/post)processed with tools, managing your CLASSPATH
, and all others sorts of tasks that are required to build your project. It is similar to Apache Ant or Gradle or Makefiles in C/C++, but it attempts to be completely self-contained in it that you shouldn't need any additional tools or scripts by incorporating other common tasks like downloading & installing necessary libraries etc.
It is also designed around the "build portability" theme, so that you don't get issues as having the same code with the same buildscript working on one computer but not on another one (this is a known issue, we have VMs of Windows 98 machines since we couldn't get some of our Delphi applications compiling anywhere else). Because of this, it is also the best way to work on a project between people who use different IDEs since IDE-generated Ant scripts are hard to import into other IDEs, but all IDEs nowadays understand and support Maven (IntelliJ, Eclipse, and NetBeans). Even if you don't end up liking Maven, it ends up being the point of reference for all other modern builds tools.
Why you should use it
There are three things about Maven that are very nice.
Maven will (after you declare which ones you are using) download all the libraries that you use and the libraries that they use for you automatically. This is very nice, and makes dealing with lots of libraries ridiculously easy. This lets you avoid "dependency hell". It is similar to Apache Ant's Ivy.
It uses "Convention over Configuration" so that by default you don't need to define the tasks you want to do. You don't need to write a "compile", "test", "package", or "clean" step like you would have to do in Ant or a Makefile. Just put the files in the places in which Maven expects them and it should work off of the bat.
Maven also has lots of nice plug-ins that you can install that will handle many routine tasks from generating Java classes from an XSD schema using JAXB to measuring test coverage with Cobertura. Just add them to your pom.xml
and they will integrate with everything else you want to do.
The initial learning curve is steep, but (nearly) every professional Java developer uses Maven or wishes they did. You should use Maven on every project although don't be surprised if it takes you a while to get used to it and that sometimes you wish you could just do things manually, since learning something new sometimes hurts. However, once you truly get used to Maven you will find that build management takes almost no time at all.
How to Start
The best place to start is "Maven in 5 Minutes". It will get you start with a project ready for you to code in with all the necessary files and folders set-up (yes, I recommend using the quickstart archetype, at least at first).
After you get started you'll want a better understanding over how the tool is intended to be used. For that "Better Builds with Maven" is the most thorough place to understand the guts of how it works, however, "Maven: The Complete Reference" is more up-to-date. Read the first one for understanding, but then use the second one for reference.
You can check out this solution by AJ. It's pretty straightforward, just copy and paste the following lines of code.
jQuery.browser = {};
(function () {
jQuery.browser.msie = false;
jQuery.browser.version = 0;
if (navigator.userAgent.match(/MSIE ([0-9]+)\./)) {
jQuery.browser.msie = true;
jQuery.browser.version = RegExp.$1;
}
})();
Reference:
$("#myTable").offset().top;
This will give you the computed offset (relative to document) of any object.
Use jquery event call. Write the below line where you want to trigger onChange of any element.
$("#element_id").change();
element_id is the ID of the element whose onChange you want to trigger.
Avoid the use of
element.fireEvent("onchange");
Because it has very less support. Refer this document for its support.
Personally I think Thread.Sleep
is a poor implementation. It locks the UI etc. I personally like timer implementations since it waits then fires.
Usage: DelayFactory.DelayAction(500, new Action(() => { this.RunAction(); }));
//Note Forms.Timer and Timer() have similar implementations.
public static void DelayAction(int millisecond, Action action)
{
var timer = new DispatcherTimer();
timer.Tick += delegate
{
action.Invoke();
timer.Stop();
};
timer.Interval = TimeSpan.FromMilliseconds(millisecond);
timer.Start();
}
Did you check the small Mousetrap library?
Mousetrap is a simple library for handling keyboard shortcuts in JavaScript.
One thing I wish to point out here, and that is, despite what the Apple engineers have stated in their own WWDC 2015 video here:
https://developer.apple.com/videos/play/wwdc2015/407/
Apple keeps changing their mind on the subject, which tells us that there is no single right answer to this question. To show that even Apple engineers are split on this subject, take a look at Apple's most recent sample code, and you'll see some people use weak, and some don't.
This Apple Pay example uses weak: https://developer.apple.com/library/ios/samplecode/Emporium/Listings/Emporium_ProductTableViewController_swift.html#//apple_ref/doc/uid/TP40016175-Emporium_ProductTableViewController_swift-DontLinkElementID_8
As does this picture-in-picture example: https://developer.apple.com/library/ios/samplecode/AVFoundationPiPPlayer/Listings/AVFoundationPiPPlayer_PlayerViewController_swift.html#//apple_ref/doc/uid/TP40016166-AVFoundationPiPPlayer_PlayerViewController_swift-DontLinkElementID_4
As does the Lister example: https://developer.apple.com/library/ios/samplecode/Lister/Listings/Lister_ListCell_swift.html#//apple_ref/doc/uid/TP40014701-Lister_ListCell_swift-DontLinkElementID_57
As does the Core Location example: https://developer.apple.com/library/ios/samplecode/PotLoc/Listings/Potloc_PotlocViewController_swift.html#//apple_ref/doc/uid/TP40016176-Potloc_PotlocViewController_swift-DontLinkElementID_6
As does the view controller previewing example: https://developer.apple.com/library/ios/samplecode/ViewControllerPreviews/Listings/Projects_PreviewUsingDelegate_PreviewUsingDelegate_DetailViewController_swift.html#//apple_ref/doc/uid/TP40016546-Projects_PreviewUsingDelegate_PreviewUsingDelegate_DetailViewController_swift-DontLinkElementID_5
As does the HomeKit example: https://developer.apple.com/library/ios/samplecode/HomeKitCatalog/Listings/HMCatalog_Homes_Action_Sets_ActionSetViewController_swift.html#//apple_ref/doc/uid/TP40015048-HMCatalog_Homes_Action_Sets_ActionSetViewController_swift-DontLinkElementID_23
All those are fully updated for iOS 9, and all use weak outlets. From this we learn that A. The issue is not as simple as some people make it out to be. B. Apple has changed their mind repeatedly, and C. You can use whatever makes you happy :)
Special thanks to Paul Hudson (author of www.hackingwithsift.com) who gave me the clarification, and references for this answer.
I hope this clarifies the subject a bit better!
Take care.
this version works for primitive types and for classes (short test-method included)
' TODO: change this to the name of your module
Private Const sMODULE As String = "MVbaUtils"
Public Function ExistsInCollection(oCollection As Collection, sKey As String) As Boolean
Const scSOURCE As String = "ExistsInCollection"
Dim lErrNumber As Long
Dim sErrDescription As String
lErrNumber = 0
sErrDescription = "unknown error occurred"
Err.Clear
On Error Resume Next
' note: just access the item - no need to assign it to a dummy value
' and this would not be so easy, because we would need different
' code depending on the type of object
' e.g.
' Dim vItem as Variant
' If VarType(oCollection.Item(sKey)) = vbObject Then
' Set vItem = oCollection.Item(sKey)
' Else
' vItem = oCollection.Item(sKey)
' End If
oCollection.Item sKey
lErrNumber = CLng(Err.Number)
sErrDescription = Err.Description
On Error GoTo 0
If lErrNumber = 5 Then ' 5 = not in collection
ExistsInCollection = False
ElseIf (lErrNumber = 0) Then
ExistsInCollection = True
Else
' Re-raise error
Err.Raise lErrNumber, mscMODULE & ":" & scSOURCE, sErrDescription
End If
End Function
Private Sub Test_ExistsInCollection()
Dim asTest As New Collection
Debug.Assert Not ExistsInCollection(asTest, "")
Debug.Assert Not ExistsInCollection(asTest, "xx")
asTest.Add "item1", "key1"
asTest.Add "item2", "key2"
asTest.Add New Collection, "key3"
asTest.Add Nothing, "key4"
Debug.Assert ExistsInCollection(asTest, "key1")
Debug.Assert ExistsInCollection(asTest, "key2")
Debug.Assert ExistsInCollection(asTest, "key3")
Debug.Assert ExistsInCollection(asTest, "key4")
Debug.Assert Not ExistsInCollection(asTest, "abcx")
Debug.Print "ExistsInCollection is okay"
End Sub
I found out how to do this on the Android emulator itself (Menu, "Settings" App - not the settings of the emulator outside). All you need to do is:
open settings app -> Language & Input -> Go to the "Keyboard & Input Methods -> click Default
This will bring up a Dialog in which case you can then disable the Hardware Keyboard by switching the hardware keyboard from on to off. This will disable the Hardware keyboard and enable the softkeyboard.
Much simpler:
position: relative;
left: 50%;
transform: translateX(-50%);
You are now centered in your parent element. You can do that vertically too.
You mean this?
from string import punctuation, digits
takeout = punctuation + digits
turnthis = "(fjskl) 234 = -345 089 abcdef"
turnthis = turnthis.translate(None, takeout)[::-1]
print turnthis
$count = DB::table('category_issue')->count();
will give you the number of items.
For more detailed information check Fluent Query Builder section in beautiful Laravel Documentation.
Depends on what you're doing.
For instance:
//bankers' rounding - midpoint goes to nearest even
GetIntPart(2.5) >> 2
GetIntPart(5.5) >> 6
GetIntPart(-6.5) >> -6
or
//arithmetic rounding - midpoint goes away from zero
GetIntPart(2.5) >> 3
GetIntPart(5.5) >> 6
GetIntPart(-6.5) >> -7
The default is always the former, which can be a surprise but makes very good sense.
Your explicit cast will do:
int intPart = (int)343564564.5
// intPart will be 343564564
int intPart = (int)343564565.5
// intPart will be 343564566
From the way you've worded the question it sounds like this isn't what you want - you want to floor it every time.
I would do:
Math.Floor(Math.Abs(number));
Also check the size of your decimal
- they can be quite big, so you may need to use a long
.
Look at my version :)
- (void)keyboardWasShown:(NSNotification *)aNotification
{
NSDictionary* info = [aNotification userInfo];
CGSize kbSize = [[info objectForKey:UIKeyboardFrameBeginUserInfoKey] CGRectValue].size;
CGRect bkgndRect = cellSelected.superview.frame;
bkgndRect.size.height += kbSize.height;
[cellSelected.superview setFrame:bkgndRect];
[tableView setContentOffset:CGPointMake(0.0, cellSelected.frame.origin.y-kbSize.height) animated:YES];
}
- (void)keyboardWasHidden:(NSNotification *)aNotification
{
[tableView setContentOffset:CGPointMake(0.0, 0.0) animated:YES];
}
I recommend that you get in the habit, right now, of using ANSI-style joins, meaning you should use the INNER JOIN
, LEFT OUTER JOIN
, RIGHT OUTER JOIN
, FULL OUTER JOIN
, and CROSS JOIN
elements in your SQL statements rather than using the "old-style" joins where all the tables are named together in the FROM
clause and all the join conditions are put in the the WHERE
clause. ANSI-style joins are easier to understand and less likely to be miswritten and/or misinterpreted than "old-style" joins.
I'd rewrite your query as:
SELECT bc.firstname,
bc.lastname,
b.title,
TO_CHAR(bo.orderdate, 'MM/DD/YYYY') "Order Date",
p.publishername
FROM BOOK_CUSTOMER bc
INNER JOIN books b
ON b.BOOK_ID = bc.BOOK_ID
INNER JOIN book_order bo
ON bo.BOOK_ID = b.BOOK_ID
INNER JOIN publisher p
ON p.PUBLISHER_ID = b.PUBLISHER_ID
WHERE p.publishername = 'PRINTING IS US';
Share and enjoy.
For Internet Explorer 9:
a:active, a:focus {
outline: none;
ie-dummy: expression(this.hideFocus=true);
}
There are 2 ways for using Gradle behind a proxy :
(From Guillaume Berche's post)
Add these arguments in your gradle command :
-Dhttp.proxyHost=your_proxy_http_host -Dhttp.proxyPort=your_proxy_http_port
or these arguments if you are using https :
-Dhttps.proxyHost=your_proxy_https_host -Dhttps.proxyPort=your_proxy_https_port
in gradle.properties
add the following lines :
systemProp.http.proxyHost=your_proxy_http_host
systemProp.http.proxyPort=your_proxy_http_port
systemProp.https.proxyHost=your_proxy_https_host
systemProp.https.proxyPort=your_proxy_https_port
(for gradle.properties
file location, please refer to official documentation https://docs.gradle.org/current/userguide/build_environment.html
EDIT : as said by @Joost :
A small but important detail that I initially overlooked: notice that the actual host name does NOT contain http://
protocol part of the URL...
I'm running BS3 on a dev site and the following produces the effect/layout you're requesting. Of course you'll need the glyphicons set up in BS3.
<div class="navbar navbar-inverse navbar-static-top" role="navigation">
<div class="navbar-header">
<button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-ex1-collapse">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a class="navbar-brand" rel="home" href="/" title="Aahan Krish's Blog - Homepage">ITSMEEE</a>
</div>
<div class="collapse navbar-collapse navbar-ex1-collapse">
<ul class="nav navbar-nav">
<li><a href="/topic/notes/">/notes</a></li>
<li><a href="/topic/dev/">/dev</a></li>
<li><a href="/topic/good-reads/">/good-reads</a></li>
<li><a href="/topic/art/">/art</a></li>
<li><a href="/topic/bookmarks/">/bookmarks</a></li>
<li><a href="/all-topics/">/all</a></li>
</ul>
<div class="col-sm-3 col-md-3 pull-right">
<form class="navbar-form" role="search">
<div class="input-group">
<input type="text" class="form-control" placeholder="Search" name="srch-term" id="srch-term">
<div class="input-group-btn">
<button class="btn btn-default" type="submit"><i class="glyphicon glyphicon-search"></i></button>
</div>
</div>
</form>
</div>
</div>
</div>
UPDATE: See JSFiddle
It may be called abc.py
from the main script as below:
#!/usr/bin/python
import abc
abc.py
may be something like this:
print'abc'
For those people using Python, you may consider using Selenium Wire, which can set request headers, as well as provide you with the ability to inspect requests and responses.
from seleniumwire import webdriver # Import from seleniumwire
# Create a new instance of the Firefox driver (or Chrome)
driver = webdriver.Firefox()
# Create a request interceptor
def interceptor(request):
del request.headers['Referer'] # Delete the header first
request.headers['Referer'] = 'some_referer'
# Set the interceptor on the driver
driver.request_interceptor = interceptor
# All requests will now use 'some_referer' for the referer
driver.get('https://mysite')
OK, let me put this bluntly: if you're putting user data, or anything derived from user data into a cookie for this purpose, you're doing something wrong.
There. I said it. Now we can move on to the actual answer.
What's wrong with hashing user data, you ask? Well, it comes down to exposure surface and security through obscurity.
Imagine for a second that you're an attacker. You see a cryptographic cookie set for the remember-me on your session. It's 32 characters wide. Gee. That may be an MD5...
Let's also imagine for a second that they know the algorithm that you used. For example:
md5(salt+username+ip+salt)
Now, all an attacker needs to do is brute force the "salt" (which isn't really a salt, but more on that later), and he can now generate all the fake tokens he wants with any username for his IP address! But brute-forcing a salt is hard, right? Absolutely. But modern day GPUs are exceedingly good at it. And unless you use sufficient randomness in it (make it large enough), it's going to fall quickly, and with it the keys to your castle.
In short, the only thing protecting you is the salt, which isn't really protecting you as much as you think.
But Wait!
All of that was predicated that the attacker knows the algorithm! If it's secret and confusing, then you're safe, right? WRONG. That line of thinking has a name: Security Through Obscurity, which should NEVER be relied upon.
The Better Way
The better way is to never let a user's information leave the server, except for the id.
When the user logs in, generate a large (128 to 256 bit) random token. Add that to a database table which maps the token to the userid, and then send it to the client in the cookie.
What if the attacker guesses the random token of another user?
Well, let's do some math here. We're generating a 128 bit random token. That means that there are:
possibilities = 2^128
possibilities = 3.4 * 10^38
Now, to show how absurdly large that number is, let's imagine every server on the internet (let's say 50,000,000 today) trying to brute-force that number at a rate of 1,000,000,000 per second each. In reality your servers would melt under such load, but let's play this out.
guesses_per_second = servers * guesses
guesses_per_second = 50,000,000 * 1,000,000,000
guesses_per_second = 50,000,000,000,000,000
So 50 quadrillion guesses per second. That's fast! Right?
time_to_guess = possibilities / guesses_per_second
time_to_guess = 3.4e38 / 50,000,000,000,000,000
time_to_guess = 6,800,000,000,000,000,000,000
So 6.8 sextillion seconds...
Let's try to bring that down to more friendly numbers.
215,626,585,489,599 years
Or even better:
47917 times the age of the universe
Yes, that's 47917 times the age of the universe...
Basically, it's not going to be cracked.
So to sum up:
The better approach that I recommend is to store the cookie with three parts.
function onLogin($user) {
$token = GenerateRandomToken(); // generate a token, should be 128 - 256 bit
storeTokenForUser($user, $token);
$cookie = $user . ':' . $token;
$mac = hash_hmac('sha256', $cookie, SECRET_KEY);
$cookie .= ':' . $mac;
setcookie('rememberme', $cookie);
}
Then, to validate:
function rememberMe() {
$cookie = isset($_COOKIE['rememberme']) ? $_COOKIE['rememberme'] : '';
if ($cookie) {
list ($user, $token, $mac) = explode(':', $cookie);
if (!hash_equals(hash_hmac('sha256', $user . ':' . $token, SECRET_KEY), $mac)) {
return false;
}
$usertoken = fetchTokenByUserName($user);
if (hash_equals($usertoken, $token)) {
logUserIn($user);
}
}
}
Note: Do not use the token or combination of user and token to lookup a record in your database. Always be sure to fetch a record based on the user and use a timing-safe comparison function to compare the fetched token afterwards. More about timing attacks.
Now, it's very important that the SECRET_KEY
be a cryptographic secret (generated by something like /dev/urandom
and/or derived from a high-entropy input). Also, GenerateRandomToken()
needs to be a strong random source (mt_rand()
is not nearly strong enough. Use a library, such as RandomLib or random_compat, or mcrypt_create_iv()
with DEV_URANDOM
)...
The hash_equals()
is to prevent timing attacks.
If you use a PHP version below PHP 5.6 the function hash_equals()
is not supported. In this case you can replace hash_equals()
with the timingSafeCompare function:
/**
* A timing safe equals comparison
*
* To prevent leaking length information, it is important
* that user input is always used as the second parameter.
*
* @param string $safe The internal (safe) value to be checked
* @param string $user The user submitted (unsafe) value
*
* @return boolean True if the two strings are identical.
*/
function timingSafeCompare($safe, $user) {
if (function_exists('hash_equals')) {
return hash_equals($safe, $user); // PHP 5.6
}
// Prevent issues if string length is 0
$safe .= chr(0);
$user .= chr(0);
// mbstring.func_overload can make strlen() return invalid numbers
// when operating on raw binary strings; force an 8bit charset here:
if (function_exists('mb_strlen')) {
$safeLen = mb_strlen($safe, '8bit');
$userLen = mb_strlen($user, '8bit');
} else {
$safeLen = strlen($safe);
$userLen = strlen($user);
}
// Set the result to the difference between the lengths
$result = $safeLen - $userLen;
// Note that we ALWAYS iterate over the user-supplied length
// This is to prevent leaking length information
for ($i = 0; $i < $userLen; $i++) {
// Using % here is a trick to prevent notices
// It's safe, since if the lengths are different
// $result is already non-0
$result |= (ord($safe[$i % $safeLen]) ^ ord($user[$i]));
}
// They are only identical strings if $result is exactly 0...
return $result === 0;
}
I think we also need to give the fpm container the volume, dont we? So =>
fpm:
image: php:fpm
volumes:
- ./:/var/www/test/
If i dont do this, i run into this exception when firing a request, as fpm cannot find requested file:
[error] 6#6: *4 FastCGI sent in stderr: "Primary script unknown" while reading response header from upstream, client: 172.17.42.1, server: localhost, request: "GET / HTTP/1.1", upstream: "fastcgi://172.17.0.81:9000", host: "localhost"
var date = new Date(date_string); var milliseconds = date.getTime();
This worked for me!
$(this)
and this
aren't the same. The first represents a jQuery object wrapped around your element. The second is just your element. The id
property exists on the element, but not the jQuery object. As such, you have a few options:
Access the property on the element directly:
this.id
Access it from the jQuery object:
$(this).attr("id")
Pull the object out of jQuery:
$(this).get(0).id; // Or $(this)[0].id
Get the id
from the event
object:
When events are raised, for instance a click event, they carry important information and references around with them. In your code above, you have a click event. This event object has a reference to two items: currentTarget
and target
.
Using target
, you can get the id
of the element that raised the event. currentTarget
would simply tell you which element the event is currently bubbling through. These are not always the same.
$("#button").on("click", function(e){ console.log( e.target.id ) });
Of all of these, the best option is to just access it directly from this
itself, unless you're engaged in a series of nested events, then it might be best to use the event
object of each nested event (give them all unique names) to reference elements in higher or lower scopes.
With Application Loader now gone from Xcode I had a look around to see how to upload an .ipa file, since I use UE4 and I don't touch Xcode at all during development. Turns out it's pretty hidden away, You need to go to Window, Organiser, Archives. The archive will only appear if you ticked the "Generate Xcode Archive Package" tickbox in Project Settings. Then you just click Distribute and it's just does it.
Update for 2019 -- Using Bootstrap 4
I found most of the answers seem to have a lot of unnecessary jQuery. To open a modal from another modal can be done simply by using the events that Bootstrap provides such as show.bs.modal
. You may also want some CSS to handle the backdrop overlays. Here are the 3 open modal from another scenarios...
Open modal from another modal (keep 1st modal open)
<a data-toggle="modal" href="#myModal" class="btn btn-primary">Launch modal</a>
<div class="modal" id="myModal">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h4 class="modal-title">Modal title</h4>
<button type="button" class="close" data-dismiss="modal">×</button>
</div><div class="container"></div>
<div class="modal-body">
...
<a data-toggle="modal" href="#myModal2" class="btn btn-primary">Open modal2</a>
</div>
<div class="modal-footer">
<a href="#" data-dismiss="modal" class="btn">Close</a>
</div>
</div>
</div>
</div>
<div class="modal" id="myModal2" data-backdrop="static">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h4 class="modal-title">2nd Modal title</h4>
<button type="button" class="close" data-dismiss="modal">×</button>
</div><div class="container"></div>
<div class="modal-body">
..
</div>
<div class="modal-footer">
<a href="#" data-dismiss="modal" class="btn">Close</a>
<a href="#" class="btn btn-primary">Save changes</a>
</div>
</div>
</div>
</div>
A potential issue in this case is that the backdrop from the 2nd modal hides the 1st modal. To prevent this, make the 2nd modal data-backdrop="static"
, and add some CSS to fix the z-indexes of the backdrops...
/* modal backdrop fix */
.modal:nth-of-type(even) {
z-index: 1052 !important;
}
.modal-backdrop.show:nth-of-type(even) {
z-index: 1051 !important;
}
https://www.codeply.com/go/NiFzSCukVl
Open modal from another modal (close 1st modal)
This is similar to the above scenario, but since we are closing the 1st modal when the 2nd is opened, there is no need for the backdrop CSS fix. A simple function that handles the 2nd modals show.bs.modal
event closes the 1st modal.
$("#myModal2").on('show.bs.modal', function (e) {
$("#myModal1").modal("hide");
});
https://codeply.com/go/ejaUJ4YANz
Open modal inside another modal
The last multiple modals scenario is opening the 2nd modal inside the 1st modal. In this case the markup for the 2nd is placed inside the 1st. No extra CSS or jQuery is needed.
<div class="modal" id="myModal1">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h4 class="modal-title">Modal title</h4>
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
</div>
<div class="container"></div>
<div class="modal-body">
...
<a data-toggle="modal" href="#myModal2" class="btn btn-primary">Launch modal 2</a>
</div>
<div class="modal-footer">
<a href="#" data-dismiss="modal" class="btn">Close</a>
</div>
</div>
</div>
<div class="modal" id="myModal2">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h4 class="modal-title">2nd Modal title</h4>
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
</div>
<div class="container"></div>
<div class="modal-body">
...
</div>
<div class="modal-footer">
<a href="#" data-dismiss="modal" class="btn">Close</a>
<a href="#" class="btn btn-primary">Save changes</a>
</div>
</div>
</div>
</div>
</div>
I use a function to store cookies with a custom expire time in days:
// use it like: writeCookie("mycookie", "1", 30)
// this will set a cookie for 30 days since now
function writeCookie(name,value,days) {
if (days) {
var date = new Date();
date.setTime(date.getTime()+(days*24*60*60*1000));
var expires = "; expires="+date.toGMTString();
}
else var expires = "";
document.cookie = name+"="+value+expires+"; path=/";
}
I'm not sure whether it's a good idea to use integers at all. Some numbers might contain special characters (# as part of the extension for example) which you should be able to handle too. So I would suggest using varchars instead.
You don't need to change the delimiter to display the right part of the string with cut
.
The -f
switch of the cut
command is the n-TH element separated by your delimiter : :
, so you can just type :
grep puddle2_1557936 | cut -d ":" -f2
Another solutions (adapt it a bit) if you want fun :
Using grep :
grep -oP 'puddle2_1557936:\K.*' <<< 'puddle2_1557936:/home/rogers.williams/folderz/puddle2'
/home/rogers.williams/folderz/puddle2
or still with look around regex
grep -oP '(?<=puddle2_1557936:).*' <<< 'puddle2_1557936:/home/rogers.williams/folderz/puddle2'
/home/rogers.williams/folderz/puddle2
or with perl :
perl -lne '/puddle2_1557936:(.*)/ and print $1' <<< 'puddle2_1557936:/home/rogers.williams/folderz/puddle2'
/home/rogers.williams/folderz/puddle2
or using ruby (thanks to glenn jackman)
ruby -F: -ane '/puddle2_1557936/ and puts $F[1]' <<< 'puddle2_1557936:/home/rogers.williams/folderz/puddle2'
/home/rogers.williams/folderz/puddle2
or with awk :
awk -F'puddle2_1557936:' '{print $2}' <<< 'puddle2_1557936:/home/rogers.williams/folderz/puddle2'
/home/rogers.williams/folderz/puddle2
or with python :
python -c 'import sys; print(sys.argv[1].split("puddle2_1557936:")[1])' 'puddle2_1557936:/home/rogers.williams/folderz/puddle2'
/home/rogers.williams/folderz/puddle2
or using only bash :
IFS=: read _ a <<< "puddle2_1557936:/home/rogers.williams/folderz/puddle2"
echo "$a"
/home/rogers.williams/folderz/puddle2
js<<EOF
var x = 'puddle2_1557936:/home/rogers.williams/folderz/puddle2'
print(x.substr(x.indexOf(":")+1))
EOF
/home/rogers.williams/folderz/puddle2
php -r 'preg_match("/puddle2_1557936:(.*)/", $argv[1], $m); echo "$m[1]\n";' 'puddle2_1557936:/home/rogers.williams/folderz/puddle2'
/home/rogers.williams/folderz/puddle2
I had the same problem because of an table column which was defined as ENUM('x','y','z') and later on I was trying to save the value 'a' into this column, thus I got the mentioned error.
Solved by altering the table column definition and added value 'a' into the enum set.
If you don't want 'a' in the index
In :
col = ['a','b','c']
data = DataFrame([[1,2,3],[10,11,12],[20,21,22]],columns=col)
data
Out:
a b c
0 1 2 3
1 10 11 12
2 20 21 22
In :
data2 = data.set_index('a')
Out:
b c
a
1 2 3
10 11 12
20 21 22
In :
data2.index.name = None
Out:
b c
1 2 3
10 11 12
20 21 22
The answers are OK if you only require those two fields, but for a more complex object, maybe this approach could be useful:
from x in db.Serials
group x by x.Serial_Number into g
orderby g.Key
select g.OrderByDescending(z => z.uid)
.FirstOrDefault()
... this will avoid the "select new"
REST is stateless and doesn’t maintain any states between the requests. Client cookies / headers are set to maintain the user state like authentication. Say Client username/password are validated by third part authentication mechanism – 2nd level OTP gerneation etc. Once user get authenticated – headers /cookies comes to rest service end point exposed and we can assume user as auth since user is coming with valid headers/cookies. Now certain info of user like IP is either maintained in the cache and after that if request is coming from same Ip (mac address) for listed resources User is allowed. And cache is maintained for some particular time which get invalidated once time lapses. So either cache can be used or DB entries can be used to persist info b/w the requests.
Probably the fastest way to access the PHP.ini for the currently loaded version of PHP in MAMP PRO (v.4.2.1):
You missed single quote sign:
SELECT *
FROM TABLENAME
WHERE DateTime >= '12/04/2011 12:00:00 AM' AND DateTime <= '25/05/2011 3:53:04 AM'
Also, it is recommended to use ISO8601 format YYYY-MM-DDThh:mm:ss.nnn[ Z ], as this one will not depend on your server's local culture.
SELECT *
FROM TABLENAME
WHERE
DateTime >= '2011-04-12T00:00:00.000' AND
DateTime <= '2011-05-25T03:53:04.000'
When you copy your project you will also need to delete the original remnant intermediate build (someActivity$4.class) files from the C:...\AndroidStudioProjects(project_name)\app\build\intermediates\classes\release... directories. Otherwise you will almost certainly have build failures for the new project if yo attempt to compile the copied project. Refactoring won't solve this.
Suppose you are running a test python file named request.py
In request.py, you write
import request
so this also most likely a circular import.
Solution:
Just change your test file to another name such as aaa.py
, other than request.py
.
Do not use names that are already used by other libs.
A solution in C# would be:
Helper class:
internal class DriverHelper
{
private IWebDriver Driver { get; set; }
private WebDriverWait Wait { get; set; }
public DriverHelper(string driverUrl, int timeoutInSeconds)
{
Driver = new ChromeDriver();
Driver.Url = driverUrl;
Wait = new WebDriverWait(Driver, TimeSpan.FromSeconds(timeoutInSeconds));
}
internal bool ClickElement(string cssSelector)
{
//Find the element
IWebElement element = Wait.Until(d=>ExpectedConditions.ElementIsVisible(By.CssSelector(cssSelector)))(Driver);
return Wait.Until(c => ClickElement(element, cssSelector));
}
private bool ClickElement(IWebElement element, string cssSelector)
{
try
{
//Check if element is still included in the dom
//If the element has changed a the OpenQA.Selenium.StaleElementReferenceException is thrown.
bool isDisplayed = element.Displayed;
element.Click();
return true;
}
catch (StaleElementReferenceException)
{
//wait until the element is visible again
element = Wait.Until(d => ExpectedConditions.ElementIsVisible(By.CssSelector(cssSelector)))(Driver);
return ClickElement(element, cssSelector);
}
catch (Exception)
{
return false;
}
}
}
Invocation:
DriverHelper driverHelper = new DriverHelper("http://www.seleniumhq.org/docs/04_webdriver_advanced.jsp", 10);
driverHelper.ClickElement("input[value='csharp']:first-child");
Similarly can be used for Java.
Well the closest thing I've been able to get with the StyledMarker is this.
The bullet in the middle isn't quite a big as the default one though. The StyledMarker class simply builds this url and asks the google api to create the marker.
From the class use example use "%E2%80%A2" as your text, as in:
var styleMaker2 = new StyledMarker({styleIcon:new StyledIcon(StyledIconTypes.MARKER,{text:"%E2%80%A2"},styleIconClass),position:new google.maps.LatLng(37.263477473067, -121.880502070713),map:map});
You will need to modifiy StyledMarker.js to comment out the lines:
if (text_) {
text_ = text_.substr(0,2);
}
as this will trim the text string to 2 characters.
Alternatively you could create custom marker images based on the default one with the colors you desire and override the default marker with code such as this:
marker = new google.maps.Marker({
map:map,
position: latlng,
icon: new google.maps.MarkerImage(
'http://www.gettyicons.com/free-icons/108/gis-gps/png/24/needle_left_yellow_2_24.png',
new google.maps.Size(24, 24),
new google.maps.Point(0, 0),
new google.maps.Point(0, 24)
)
});
when using (i.e.) getConstructor(String.lang)
the constructor has to be declared public.
Otherwise a NoSuchMethodException
is thrown.
if you want to access a non-public constructor you have to use instead (i.e.) getDeclaredConstructor(String.lang)
.
This is actually quite tricky. A different total number of days can result in the same result. For example:
19th June 2008 to 19th June 2010 = 2 years, but also 365 * 2 days
19th June 2006 to 19th June 2008 = 2 years, but also 365 + 366 days due to leap years
You may well want to subtract years until you get to the point where you've got two dates which are less than a year apart. Then subtract months until you get to the point where you've got two dates which are less than a month apart.
Further confusion: subtracting (or adding) months is tricky when you might start with a date of "30th March" - what's a month earlier than that?
Even further confusion (may not be relevant): even a day isn't always 24 hours. Daylight saving anyone?
Even further confusion (almost certainly not relevant): even a minute isn't always 60 seconds. Leap seconds are highly confusing...
I don't have the time to work out the exact right way of doing this right now - this answer is mostly to raise the fact that it's not nearly as simple as it might sound.
EDIT: Unfortunately I'm not going to have enough time to answer this fully. I would suggest you start off by defining a struct representing a Period
:
public struct Period
{
private readonly int days;
public int Days { get { return days; } }
private readonly int months;
public int Months { get { return months; } }
private readonly int years;
public int Years { get { return years; } }
public Period(int years, int months, int days)
{
this.years = years;
this.months = months;
this.days = days;
}
public Period WithDays(int newDays)
{
return new Period(years, months, newDays);
}
public Period WithMonths(int newMonths)
{
return new Period(years, newMonths, days);
}
public Period WithYears(int newYears)
{
return new Period(newYears, months, days);
}
public static DateTime operator +(DateTime date, Period period)
{
// TODO: Implement this!
}
public static Period Difference(DateTime first, DateTime second)
{
// TODO: Implement this!
}
}
I suggest you implement the + operator first, which should inform the Difference
method - you should make sure that first + (Period.Difference(first, second)) == second
for all first
/second
values.
Start with writing a whole slew of unit tests - initially "easy" cases, then move on to tricky ones involving leap years. I know the normal approach is to write one test at a time, but I'd personally brainstorm a bunch of them before you start any implementation work.
Allow yourself a day to implement this properly. It's tricky stuff.
Note that I've omitted weeks here - that value at least is easy, because it's always 7 days. So given a (positive) period, you'd have:
int years = period.Years;
int months = period.Months;
int weeks = period.Days / 7;
int daysWithinWeek = period.Days % 7;
(I suggest you avoid even thinking about negative periods - make sure everything is positive, all the time.)
You can use a little package called Mongoose Paginate that makes it easier.
$ npm install mongoose-paginate
After in your routes or controller, just add :
/**
* querying for `all` {} items in `MyModel`
* paginating by second page, 10 items per page (10 results, page 2)
**/
MyModel.paginate({}, 2, 10, function(error, pageCount, paginatedResults) {
if (error) {
console.error(error);
} else {
console.log('Pages:', pageCount);
console.log(paginatedResults);
}
}
The not straightforward way of doing it would be granting select on each table of the database:
postgres=# grant select on db_name.table_name to read_only_user;
You could automate that by generating your grant statements from the database metadata.
My first choice (even in C++11) would be
boost::counting_iterator
:
std::vector<int> ivec( boost::counting_iterator<int>( 0 ),
boost::counting_iterator<int>( n ) );
or if the vector was already constructed:
std::copy( boost::counting_iterator<int>( 0 ),
boost::counting_iterator<int>( ivec.size() ),
ivec.begin() );
If you can't use Boost: either std::generate
(as suggested in
other answers), or implement counting_iterator
yourself, if
you need it in various places. (With Boost, you can use
a transform_iterator
of a counting_iterator
to create all
sorts of interesting sequences. Without Boost, you can do a lot
of this by hand, either in the form of a generator object type
for std::generate
, or as something you can plug into a hand
written counting iterator.)
Dereferencing a pointer means getting the value that is stored in the memory location pointed by the pointer. The operator * is used to do this, and is called the dereferencing operator.
int a = 10;
int* ptr = &a;
printf("%d", *ptr); // With *ptr I'm dereferencing the pointer.
// Which means, I am asking the value pointed at by the pointer.
// ptr is pointing to the location in memory of the variable a.
// In a's location, we have 10. So, dereferencing gives this value.
// Since we have indirect control over a's location, we can modify its content using the pointer. This is an indirect way to access a.
*ptr = 20; // Now a's content is no longer 10, and has been modified to 20.
If you need any type of quoting (single, double, and triple for both) you can "combine"(0) the strings:
>>> raw_string_with_quotes = r'double"' r"single'" r'''double triple""" ''' r"""single triple''' """
>>> print raw_string_with_quotes
double"single'double triple""" single triple'''
You may also "combine"(0) raw strings with non-raw strings:
>>> r'raw_string\n' 'non-raw string\n'
'raw_string\\nnon-raw string\n'
(0): In fact, the Python parser joins the strings, and it does not create multiple strings. If you add the "+" operator, then multiple strings are created and combined.
I'm not certain, based on your question if you want numbered rows that will remember their numbers even if the underlying data changes (and gives a different ordering), but if you just want numbered rows - that reset on a change in customer ID, then try using the Partition by clause of row_number()
row_number() over(partition by CustomerID order by CustomerID)
Your code is blanking out your file:
import csv
workingdir = "C:\Mer\Ven\sample"
csvfile = workingdir+"\test3.csv"
f=open(csvfile,'wb') # opens file for writing (erases contents)
csv.writer(f, delimiter =' ',quotechar =',',quoting=csv.QUOTE_MINIMAL)
if you want to read the file in, you will need to use csv.reader and open the file for reading.
import csv
workingdir = "C:\Mer\Ven\sample"
csvfile = workingdir+"\test3.csv"
f=open(csvfile,'rb') # opens file for reading
reader = csv.reader(f)
for line in reader:
print line
If you want to write that back out to a new file with different delimiters, you can create a new file and specify those delimiters and write out each line (instead of printing the tuple).
To render SVG file you can use Macaw. Also Macaw supports transformations, user events, animation and various effects.
You can render SVG file with zero lines of code. For more info please check this article: Render SVG file with Macaw.
DISCLAIMER: I am affiliated with this project.
Rather than search it in full Body. One could just use dynamic title option already available in such scenarios I think:
$btn.tooltip({
title: function(){
return $(this).attr('title');
}
});
Your JAVA_HOME variable must be set to /usr/lib/jvm/java-6-openjdk and it must be available for the user that starts Jenkins.
From Kyle Strand comment:
As of April 2015 (I think), Jenkins requires Java7. Also note that the java binary path (JAVA) must be set to the correct version if the system default is still Java 6. Finally, for anyone wondering where these variables are set, it's in a config file listed with the installation instructions on the Jenkins webpage (e.g. for Debian it's /etc/default/jenkins).
Here's a slghtly different take using javascript's native confirm functionality and a custom Angular directive. It's super flexible and pretty lightweight:
Usage:
<button (hrsAreYouSure) (then)="confirm(arg1)" (else)="cancel(arg2)">
This will execute confirm if user presses Ok on the confirmation dialog, or cancel if they
hit Cancel
</button>
Directive:
import {Directive, ElementRef, EventEmitter, Inject, OnInit, Output} from '@angular/core';
@Directive({
selector: '[hrsAreYouSure]'
})
export class AreYouSureDirective implements OnInit {
@Output() then = new EventEmitter<boolean>();
@Output() else = new EventEmitter<boolean>();
constructor(@Inject(ElementRef) private element: ElementRef) { }
ngOnInit(): void {
const directive = this;
this.element.nativeElement.onclick = function() {
const result = confirm('Are you sure?');
if (result) {
directive.then.emit(true);
} else {
directive.else.emit(true);
}
};
}
}
In case of swift, this can be used
let string = "Package #23"
if string.containsString("Package #") {
//String contains substring
}
else {
//String does not contain substring
}
WebClient
doesn't have a direct support for form data, but you can send a HTTP post by using the UploadString method:
Using client as new WebClient
result = client.UploadString(someurl, "param1=somevalue¶m2=othervalue")
End Using
How are you calling the start function?
This should work (new is the key)
var o = new Request(destination, stay_open);
o.start();
If you directly call it like Request.prototype.start()
, this
will refer to the global context (window
in browsers).
Also, if this
is undefined, it results in an error. The if expression does not evaluate to false.
Update: this
object is not set based on declaration, but by invocation. What it means is that if you assign the function property to a variable like x = o.start
and call x()
, this
inside start no longer refers to o
. This is what happens when you do setTimeout
. To make it work, do this instead:
var o = new Request(...);
setTimeout(function() { o.start(); }, 1000);
According to the definition of getchar()
, it reads a character from the standard input. Unfortunately stdin
is mistaken for keyboard which might not be the case for getchar
. getchar
uses a buffer as stdin
and reads a single character at a time. In your case since there is no EOF
, the getchar
and putchar
are running multiple times and it looks to you as it the whole string is being printed out at a time. Make a small change and you will understand:
putchar(c);
printf("\n");
c = getchar();
Now look at the output compared to the original code.
Another example that will explain you the concept of getchar
and buffered stdin
:
void main(){
int c;
printf("Enter character");
c = getchar();
putchar();
c = getchar();
putchar();
}
Enter two characters in the first case. The second time when getchar
is running are you entering any character? NO but still putchar
works.
This ultimately means there is a buffer and when ever you are typing something and click enter this goes and settles in the buffer. getchar
uses this buffer as stdin
.
I tested this in android 4.0.3, only:
getWindow().getDecorView().getRootView()
give the same view what we get from
anyview.getRootView();
com.android.internal.policy.impl.PhoneWindow$DecorView@#########
and
getWindow().getDecorView().findViewById(android.R.id.content)
giving child of its
android.widget.FrameLayout@#######
Please confirm.
Solution: Remove STRICT_TRANS_TABLES
from sql_mode
To check your default setting,
mysql> set @@sql_mode =
'STRICT_TRANS_TABLES,NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION';
Query OK, 0 rows affected (0.00 sec)
mysql> select @@sql_mode;
+----------------------------------------------------------------+
| @@sql_mode |
+----------------------------------------------------------------+
| STRICT_TRANS_TABLES,NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION |
+----------------------------------------------------------------+
1 row in set (0.00 sec)
Run a sample query
mysql> INSERT INTO nb (id) VALUES(3);
ERROR 1364 (HY000): Field 'field' doesn't have a default value
Remove your STRICT_TRANS_TABLES
by resetting it to null.
mysql> set @@sql_mode = '';
Query OK, 0 rows affected (0.00 sec)
Now, run the same test query.
mysql> INSERT INTO nb (id) VALUES(3);
Query OK, 1 row affected, 1 warning (0.00 sec)
Source: https://netbeans.org/bugzilla/show_bug.cgi?id=190731
UPDATE
It seems now Chrome ignores the style="display: none;"
or style="visibility: hidden;
attributes.
You can change it to something like:
<input style="opacity: 0;position: absolute;">
<input type="password" style="opacity: 0;position: absolute;">
In my experience, Chrome only autocompletes the first <input type="password">
and the previous <input>
. So I've added:
<input style="display:none">
<input type="password" style="display:none">
To the top of the <form>
and the case was resolved.
To complement the previous answers, I whipped up a quick class to write to CSV files. It makes it easier to manage and close open files and achieve consistency and cleaner code if you have to deal with multiple files.
class CSVWriter():
filename = None
fp = None
writer = None
def __init__(self, filename):
self.filename = filename
self.fp = open(self.filename, 'w', encoding='utf8')
self.writer = csv.writer(self.fp, delimiter=';', quotechar='"', quoting=csv.QUOTE_ALL, lineterminator='\n')
def close(self):
self.fp.close()
def write(self, elems):
self.writer.writerow(elems)
def size(self):
return os.path.getsize(self.filename)
def fname(self):
return self.filename
Example usage:
mycsv = CSVWriter('/tmp/test.csv')
mycsv.write((12,'green','apples'))
mycsv.write((7,'yellow','bananas'))
mycsv.close()
print("Written %d bytes to %s" % (mycsv.size(), mycsv.fname()))
Have fun
As assembly is the smallest unit of versioning security, deployment and reusability of code in Microsoft.Net.
It contains:
- Assembly Identity
- Manifest
- Metadata
- MSIL Code
- Security Information
- Assembly Header
Check it with a regex.
Javascript regexen don't have POSIX character classes, so you have to write character ranges manually:
if (!input_string.match(/^[0-9a-z]+$/))
show_error_or_something()
Here ^
means beginning of string and $
means end of string, and [0-9a-z]+
means one or more of character from 0
to 9
OR from a
to z
.
More information on Javascript regexen here: https://developer.mozilla.org/en/JavaScript/Guide/Regular_Expressions
git submodule foreach --recursive git checkout .
This didn't do the trick for me but it gave me a list of files (in my case only one) that had been changed in the submodule (without me doing anything there).
So I could head over to the submodule and git status showed me that my HEAD was detached -> git checkout master, git status to see the modified file once again, git checkout >filename<, git pull and everything fine again.
Maybe, this approach is better, https://saucelabs.com/mobile, mobile testing in the cloud with selenium
Fusion charts has a new javascript/jquery library that looks promising.
It's worth noting that there is a sleep function built into Selenium.
driver.implicitly_wait(5)
For the ones that using Xamarin.IOS you can do like this:
new UIAlertView(null, message, null, "OK", null).Show();
using UIKit; is required.
Safe navigation operator or Existential Operator or Null Propagation Operator is supported in Angular Template. Suppose you have Component class
myObj:any = {
doSomething: function () { console.log('doing something'); return 'doing something'; },
};
myArray:any;
constructor() { }
ngOnInit() {
this.myArray = [this.myObj];
}
You can use it in template html file as following:
<div>test-1: {{ myObj?.doSomething()}}</div>
<div>test-2: {{ myArray[0].doSomething()}}</div>
<div>test-3: {{ myArray[2]?.doSomething()}}</div>
Note that all above answers are correct for Apache+mod-php setups. They're less likely to work with more current PHP-FPM setups. Those can typically only be defined in VirtualHost section, not .htaccess.
Again, this highly depends on how your hoster has configured PHP. Each domain/user will typically have it's own running PHP FPM instance. And subsequently a generic …/x-httpd-php52
type will not be recognized.
See ServerFault: Alias a FastCGI proxy protocol handler via Action/ScriptAlias/etc for some overview.
For Apache 2.4.10+/mod-proxy-fcgi configs you might be able to use something like:
AddHandler "proxy:unix:/var/run/php-fpm-usr123.sock|fcgi://localhost" .php
Or SetHandler
with name mapping from your .htaccess
. But again, consulting your hoster on the concrete FPM socket is unavoidable. There's no generic answer to this on modern PHP-FPM setups.
Another problem solved by the rubber duck:
The css is right but you still have to remember that the HTML elements order matters: the div has to come before the header. http://jsfiddle.net/Fq2Na/1/
Change your HTML code to have the div before the header:
<section>
<div><button>button</button></div>
<h1>some long long long long header, a whole line, 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6</h1>
</section>
And keep your CSS to the simple div { float: right; }
.
When running a single test I usually do:
go test -run TestSomethingReallyCool ./folder1/folder2/ -v -count 1
-count 1
also ensures that the test is ran every time instead of being cached. Useful when you are testing against race conditions and have a test that fails only sometimes. In Go versions not using modules the same could be achieved by setting GOCACHE=off
but this interacts poorly with Go modules.
Because you also ticked Scala, a solution without regex which easily deals with multiple quoted strings:
val text = "some string with 'the data i want' inside 'and even more data'"
text.split("'").zipWithIndex.filter(_._2 % 2 != 0).map(_._1)
res: Array[java.lang.String] = Array(the data i want, and even more data)
I do it the following way:
public static void main(String[] args) {
LinkedList list = new LinkedList();
list.insertFront(1);
list.insertFront(2);
list.insertFront(3);
System.out.println(list.toString());
}
String toString() {
StringBuilder result = new StringBuilder();
for(Object item:this) {
result.append(item.toString());
result.append("\n"); //optional
}
return result.toString();
}
Rewrite of a now-deleted answer by VonC.
Robert Gamble's succinct answer deals directly with the question. This one amplifies on some issues with filenames containing spaces.
See also: ${1:+"$@"} in /bin/sh
Basic thesis: "$@"
is correct, and $*
(unquoted) is almost always wrong.
This is because "$@"
works fine when arguments contain spaces, and
works the same as $*
when they don't.
In some circumstances, "$*"
is OK too, but "$@"
usually (but not
always) works in the same places.
Unquoted, $@
and $*
are equivalent (and almost always wrong).
So, what is the difference between $*
, $@
, "$*"
, and "$@"
? They are all related to 'all the arguments to the shell', but they do different things. When unquoted, $*
and $@
do the same thing. They treat each 'word' (sequence of non-whitespace) as a separate argument. The quoted forms are quite different, though: "$*"
treats the argument list as a single space-separated string, whereas "$@"
treats the arguments almost exactly as they were when specified on the command line.
"$@"
expands to nothing at all when there are no positional arguments; "$*"
expands to an empty string — and yes, there's a difference, though it can be hard to perceive it.
See more information below, after the introduction of the (non-standard) command al
.
Secondary thesis: if you need to process arguments with spaces and then
pass them on to other commands, then you sometimes need non-standard
tools to assist. (Or you should use arrays, carefully: "${array[@]}"
behaves analogously to "$@"
.)
Example:
$ mkdir "my dir" anotherdir
$ ls
anotherdir my dir
$ cp /dev/null "my dir/my file"
$ cp /dev/null "anotherdir/myfile"
$ ls -Fltr
total 0
drwxr-xr-x 3 jleffler staff 102 Nov 1 14:55 my dir/
drwxr-xr-x 3 jleffler staff 102 Nov 1 14:55 anotherdir/
$ ls -Fltr *
my dir:
total 0
-rw-r--r-- 1 jleffler staff 0 Nov 1 14:55 my file
anotherdir:
total 0
-rw-r--r-- 1 jleffler staff 0 Nov 1 14:55 myfile
$ ls -Fltr "./my dir" "./anotherdir"
./my dir:
total 0
-rw-r--r-- 1 jleffler staff 0 Nov 1 14:55 my file
./anotherdir:
total 0
-rw-r--r-- 1 jleffler staff 0 Nov 1 14:55 myfile
$ var='"./my dir" "./anotherdir"' && echo $var
"./my dir" "./anotherdir"
$ ls -Fltr $var
ls: "./anotherdir": No such file or directory
ls: "./my: No such file or directory
ls: dir": No such file or directory
$
Why doesn't that work?
It doesn't work because the shell processes quotes before it expands
variables.
So, to get the shell to pay attention to the quotes embedded in $var
,
you have to use eval
:
$ eval ls -Fltr $var
./my dir:
total 0
-rw-r--r-- 1 jleffler staff 0 Nov 1 14:55 my file
./anotherdir:
total 0
-rw-r--r-- 1 jleffler staff 0 Nov 1 14:55 myfile
$
This gets really tricky when you have file names such as "He said,
"Don't do this!"
" (with quotes and double quotes and spaces).
$ cp /dev/null "He said, \"Don't do this!\""
$ ls
He said, "Don't do this!" anotherdir my dir
$ ls -l
total 0
-rw-r--r-- 1 jleffler staff 0 Nov 1 15:54 He said, "Don't do this!"
drwxr-xr-x 3 jleffler staff 102 Nov 1 14:55 anotherdir
drwxr-xr-x 3 jleffler staff 102 Nov 1 14:55 my dir
$
The shells (all of them) do not make it particularly easy to handle such
stuff, so (funnily enough) many Unix programs do not do a good job of
handling them.
On Unix, a filename (single component) can contain any characters except
slash and NUL '\0'
.
However, the shells strongly encourage no spaces or newlines or tabs
anywhere in a path names.
It is also why standard Unix file names do not contain spaces, etc.
When dealing with file names that may contain spaces and other
troublesome characters, you have to be extremely careful, and I found
long ago that I needed a program that is not standard on Unix.
I call it escape
(version 1.1 was dated 1989-08-23T16:01:45Z).
Here is an example of escape
in use - with the SCCS control system.
It is a cover script that does both a delta
(think check-in) and a
get
(think check-out).
Various arguments, especially -y
(the reason why you made the change)
would contain blanks and newlines.
Note that the script dates from 1992, so it uses back-ticks instead of
$(cmd ...)
notation and does not use #!/bin/sh
on the first line.
: "@(#)$Id: delget.sh,v 1.8 1992/12/29 10:46:21 jl Exp $"
#
# Delta and get files
# Uses escape to allow for all weird combinations of quotes in arguments
case `basename $0 .sh` in
deledit) eflag="-e";;
esac
sflag="-s"
for arg in "$@"
do
case "$arg" in
-r*) gargs="$gargs `escape \"$arg\"`"
dargs="$dargs `escape \"$arg\"`"
;;
-e) gargs="$gargs `escape \"$arg\"`"
sflag=""
eflag=""
;;
-*) dargs="$dargs `escape \"$arg\"`"
;;
*) gargs="$gargs `escape \"$arg\"`"
dargs="$dargs `escape \"$arg\"`"
;;
esac
done
eval delta "$dargs" && eval get $eflag $sflag "$gargs"
(I would probably not use escape quite so thoroughly these days - it is
not needed with the -e
argument, for example - but overall, this is
one of my simpler scripts using escape
.)
The escape
program simply outputs its arguments, rather like echo
does, but it ensures that the arguments are protected for use with
eval
(one level of eval
; I do have a program which did remote shell
execution, and that needed to escape the output of escape
).
$ escape $var
'"./my' 'dir"' '"./anotherdir"'
$ escape "$var"
'"./my dir" "./anotherdir"'
$ escape x y z
x y z
$
I have another program called al
that lists its arguments one per line
(and it is even more ancient: version 1.1 dated 1987-01-27T14:35:49).
It is most useful when debugging scripts, as it can be plugged into a
command line to see what arguments are actually passed to the command.
$ echo "$var"
"./my dir" "./anotherdir"
$ al $var
"./my
dir"
"./anotherdir"
$ al "$var"
"./my dir" "./anotherdir"
$
[Added:
And now to show the difference between the various "$@"
notations, here is one more example:
$ cat xx.sh
set -x
al $@
al $*
al "$*"
al "$@"
$ sh xx.sh * */*
+ al He said, '"Don'\''t' do 'this!"' anotherdir my dir xx.sh anotherdir/myfile my dir/my file
He
said,
"Don't
do
this!"
anotherdir
my
dir
xx.sh
anotherdir/myfile
my
dir/my
file
+ al He said, '"Don'\''t' do 'this!"' anotherdir my dir xx.sh anotherdir/myfile my dir/my file
He
said,
"Don't
do
this!"
anotherdir
my
dir
xx.sh
anotherdir/myfile
my
dir/my
file
+ al 'He said, "Don'\''t do this!" anotherdir my dir xx.sh anotherdir/myfile my dir/my file'
He said, "Don't do this!" anotherdir my dir xx.sh anotherdir/myfile my dir/my file
+ al 'He said, "Don'\''t do this!"' anotherdir 'my dir' xx.sh anotherdir/myfile 'my dir/my file'
He said, "Don't do this!"
anotherdir
my dir
xx.sh
anotherdir/myfile
my dir/my file
$
Notice that nothing preserves the original blanks between the *
and */*
on the command line. Also, note that you can change the 'command line arguments' in the shell by using:
set -- -new -opt and "arg with space"
This sets 4 options, '-new
', '-opt
', 'and
', and 'arg with space
'.
]
Hmm, that's quite a long answer - perhaps exegesis is the better term.
Source code for escape
available on request (email to firstname dot
lastname at gmail dot com).
The source code for al
is incredibly simple:
#include <stdio.h>
int main(int argc, char **argv)
{
while (*++argv != 0)
puts(*argv);
return(0);
}
That's all. It is equivalent to the test.sh
script that Robert Gamble showed, and could be written as a shell function (but shell functions didn't exist in the local version of Bourne shell when I first wrote al
).
Also note that you can write al
as a simple shell script:
[ $# != 0 ] && printf "%s\n" "$@"
The conditional is needed so that it produces no output when passed no arguments. The printf
command will produce a blank line with only the format string argument, but the C program produces nothing.
We can use zPosition in ios
if we have a view named salonDetailView
eg : @IBOutlet weak var salonDetailView: UIView!
and have UIView for GMSMapView
eg : @IBOutlet weak var mapViewUI: GMSMapView!
To show the View salonDetailView upper of the mapViewUI
use zPosition as below
salonDetailView.layer.zPosition = 1
Running git pull
performs the following tasks, in order:
git fetch
git merge
The merge step combines branches that have been setup to be merged in your config. You want to undo the merge step, but probably not the fetch (doesn't make a lot of sense and shouldn't be necessary).
To undo the merge, use git reset --hard
to reset the local repository to a previous state; use git-reflog to find the SHA-1 of the previous state and then reset to it.
Warning
The commands listed in this section remove all uncommitted changes, potentially leading to a loss of work:
git reset --hard
Alternatively, reset to a particular point in time, such as:
git reset --hard master@{"10 minutes ago"}
How about this :
@client = TinyTds::Client.new(
:adapter => 'mysql2',
:host => 'host',
:database => 'siteconfig_development',
:username => 'username',
:password => 'password'
sql = "SELECT * FROM users"
result = @client.execute(sql)
results.each do |row|
puts row[0]
end
You need to have TinyTds gem installed, since you didn't specify it in your question I didn't use Active Record
Here's what I use to print a line of characters across the screen in linux (based on terminal/screen width)
printf '=%.0s' $(seq 1 $(tput cols))
Explanation:
Print an equal sign as many times as the given sequence:
printf '=%.0s' #sequence
Use the output of a command (this is a bash feature called Command Substitution):
$(example_command)
Give a sequence, I've used 1 to 20 as an example. In the final command the tput command is used instead of 20:
seq 1 20
Give the number of columns currently used in the terminal:
tput cols
i myself like setTimeout
more that setInterval
but didn't find a solution in class based component .you could use sth like this in class based components:
class Clock extends React.Component {
constructor(props) {
super(props);
this.state = {
date: new Date()
};
}
componentDidMount() {
this.timerID = setInterval(
() => this.tick(),
1000
);
}
componentWillUnmount() {
clearInterval(this.timerID);
}
tick() {
this.setState({
date: new Date()
});
}
render() {
return (
this.state.date.toLocaleTimeString()
);
}
}
ReactDOM.render(
<Clock / > ,
document.getElementById('app')
);
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
<div id="app" />
_x000D_
https://codesandbox.io/s/sweet-diffie-wsu1t?file=/src/index.js
if you want to get an attribute of an HTML element with jQuery you can use .attr();
so $('html').attr('someAttribute');
will give you the value of someAttribute
of the element html
there is a jQuery plugin here: http://plugins.jquery.com/project/getAttributes
that allows you to get all attributes from an HTML element
Looks like you have <authentication mode="Windows" />
in your web.config file but your hosting provider won't let you use that. Just remove that line.
I suggest the use of htop, as a better alternative to top.
As a general rule, converting a Web Forms or MVC5 application to ASP.NET Core will require a significant amount of refactoring.
HttpContext.Current
was removed in ASP.NET Core. Accessing the current HTTP context from a separate class library is the type of messy architecture that ASP.NET Core tries to avoid. There are a few ways to re-architect this in ASP.NET Core.
You can access the current HTTP context via the HttpContext
property on any controller. The closest thing to your original code sample would be to pass HttpContext
into the method you are calling:
public class HomeController : Controller
{
public IActionResult Index()
{
MyMethod(HttpContext);
// Other code
}
}
public void MyMethod(Microsoft.AspNetCore.Http.HttpContext context)
{
var host = $"{context.Request.Scheme}://{context.Request.Host}";
// Other code
}
If you're writing custom middleware for the ASP.NET Core pipeline, the current request's HttpContext
is passed into your Invoke
method automatically:
public Task Invoke(HttpContext context)
{
// Do something with the current HTTP context...
}
Finally, you can use the IHttpContextAccessor
helper service to get the HTTP context in any class that is managed by the ASP.NET Core dependency injection system. This is useful when you have a common service that is used by your controllers.
Request this interface in your constructor:
public MyMiddleware(IHttpContextAccessor httpContextAccessor)
{
_httpContextAccessor = httpContextAccessor;
}
You can then access the current HTTP context in a safe way:
var context = _httpContextAccessor.HttpContext;
// Do something with the current HTTP context...
IHttpContextAccessor
isn't always added to the service container by default, so register it in ConfigureServices
just to be safe:
public void ConfigureServices(IServiceCollection services)
{
services.AddHttpContextAccessor();
// if < .NET Core 2.2 use this
//services.TryAddSingleton<IHttpContextAccessor, HttpContextAccessor>();
// Other code...
}
ngRoute is a module built by the Angular team that provides basic client-side routing functionality. This module provides a fairly powerful base for routing, and can be built upon pretty easily to give solid routing functionality, as exemplified in this blog post (be sure to read the comment trail between Ward Bell and Ben Nadel, the author - they are a couple of Angular pros)
ui-router shifts the focus from url-centric routes to application "states", which may or may not be reflected in the url.
The primary features added by ui-router are nested states and named views.
Nested states allow you to separate controller logic for the various pieces of the application. A very simple example of this would be an app with primary navigation across the top, a secondary navigation list along the left, and content on the right. Without nested states, a single controller would typically have to handle the display logic for the secondary navigation as well as the content. Nested routing allows you to separate these concerns.
Named views are another additional feature of ui-router. With ngRoute, you can only have a single ngView directive on a page, whereas with named views in ui-router you can specify multiple ui-view directives, and then each state is able to affect the template and controller of the names views. A super simple example of this would be to have the main content of your app be the primary view, and then to also have a footer bar that would be a separate ui-view. In this scenario, the footer's controller no longer has to listen for state/route changes.
A good comparison of ngRoute and ui-router can be found on this podcast episode.
Just to make things more confusing, keep an eye on the new "official" routing module that the Angular team is expecting to release for versions 1.5 and 2.0 of Angular. This will be replacing the ngRoute module. Here is the current documentation for the new Router module - it is fairly sparse as of this posting since the implementation has not yet been finalized. Watch here for more news on when this module will actually be released.
Here is good example of the CRUD operation using fetch API:
“A practical ES6 guide on how to perform HTTP requests using the Fetch API” by Dler Ari https://link.medium.com/4ZvwCordCW
Here is the sample code I tried for PATCH or PUT
function update(id, data){
fetch(apiUrl + "/" + id, {
method: 'PATCH',
body: JSON.stringify({
data
})
}).then((response) => {
response.json().then((response) => {
console.log(response);
})
}).catch(err => {
console.error(err)
})
For DELETE:
function remove(id){
fetch(apiUrl + "/" + id, {
method: 'DELETE'
}).then(() => {
console.log('removed');
}).catch(err => {
console.error(err)
});
For more info visit Using Fetch - Web APIs | MDN https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch > Fetch_API.
Here is an answer using object-scan.
When accessing a single entry, this answer doesn't really provide much benefit over vanilla javascript. However interacting with multiple fields at the same time this answer can be more performant.
Here is how you could interact with a single field
// const objectScan = require('object-scan');
const data = { code: 42, items: [{ id: 1, name: 'foo' }, { id: 2, name: 'bar' }] };
const get = (haystack, needle) => objectScan([needle], {
abort: true,
rtn: 'value'
})(haystack);
const set = (haystack, needle, value) => objectScan([needle], {
abort: true,
rtn: 'bool',
filterFn: ({ parent, property }) => {
parent[property] = value;
return true;
}
})(haystack);
console.log(get(data, 'items[1].name'));
// => bar
console.log(set(data, 'items[1].name', 'foo2'));
// => true
console.log(data);
// => { code: 42, items: [ { id: 1, name: 'foo' }, { id: 2, name: 'foo2' } ] }
_x000D_
.as-console-wrapper {max-height: 100% !important; top: 0}
_x000D_
<script src="https://bundle.run/[email protected]"></script>
_x000D_
Disclaimer: I'm the author of object-scan
and here is how you could interact with multiple fields at the same time
// const objectScan = require('object-scan');
const data = { code: 42, items: [{ id: 1, name: 'foo' }, { id: 2, name: 'bar' }] };
const get = (haystack, ...needles) => objectScan(needles, {
joined: true,
rtn: 'entry'
})(haystack);
const set = (haystack, actions) => objectScan(Object.keys(actions), {
rtn: 'count',
filterFn: ({ matchedBy, parent, property }) => {
matchedBy.forEach((m) => {
parent[property] = actions[m];
})
return true;
}
})(haystack);
console.log(get(data, 'items[0].name', 'items[1].name'));
// => [ [ 'items[1].name', 'bar' ], [ 'items[0].name', 'foo' ] ]
console.log(set(data, {
'items[0].name': 'foo1',
'items[1].name': 'foo2'
}));
// => 2
console.log(data);
// => { code: 42, items: [ { id: 1, name: 'foo1' }, { id: 2, name: 'foo2' } ] }
_x000D_
.as-console-wrapper {max-height: 100% !important; top: 0}
_x000D_
<script src="https://bundle.run/[email protected]"></script>
_x000D_
Disclaimer: I'm the author of object-scan
And here is how one could find an entity in a deeply nested object searching by id (as asked in comment)
// const objectScan = require('object-scan');
const myData = { code: 42, items: [{ id: 1, name: 'aaa', items: [{ id: 3, name: 'ccc' }, { id: 4, name: 'ddd' }] }, { id: 2, name: 'bbb', items: [{ id: 5, name: 'eee' }, { id: 6, name: 'fff' }] }] };
const findItemById = (haystack, id) => objectScan(['**(^items$).id'], {
abort: true,
useArraySelector: false,
rtn: 'parent',
filterFn: ({ value }) => value === id
})(haystack);
console.log(findItemById(myData, 5));
// => { id: 5, name: 'eee' }
_x000D_
.as-console-wrapper {max-height: 100% !important; top: 0}
_x000D_
<script src="https://bundle.run/[email protected]"></script>
_x000D_
Disclaimer: I'm the author of object-scan
I would suggest
sapply(foo, typeof)
if you need the actual types of the vectors in the data frame. class()
is somewhat of a different beast.
If you don't need to get this information as a vector (i.e. you don't need it to do something else programmatically later), just use str(foo)
.
In both cases foo
would be replaced with the name of your data frame.
<!DOCTYPE html>
<html>
<head>
<style>img{ height: 100px; float: left; }</style>
<script src="http://code.jquery.com/jquery-latest.js"></script>
<title>An JSONP example </title>
</head>
<body>
<!-- DIV FOR SHOWING IMAGES -->
<div id="images">
</div>
<!-- SCRIPT FOR GETTING IMAGES FROM FLICKER.COM USING JSONP -->
<script>
$.getJSON("http://api.flickr.com/services/feeds/photos_public.gne?jsoncallback=?",
{
format: "json"
},
//RETURNED RESPONSE DATA IS LOOPED AND ONLY IMAGE IS APPENDED TO IMAGE DIV
function(data) {
$.each(data.items, function(i,item){
$("<img/>").attr("src", item.media.m).appendTo("#images");
});
});</script>
</body>
</html>
The above code helps in getting images from the Flicker API. This uses the GET method for getting images using JSONP. It can be found in detail in here
A few years later, but this uses Linq, returns -1 if not found, doesn't create extra objects, and should short-circuit when found [as opposed to iterating over the entire IEnumerable]:
public static int IndexOf<T>(this IEnumerable<T> list, T item)
{
return list.Select((x, index) => EqualityComparer<T>.Default.Equals(item, x)
? index
: -1)
.FirstOr(x => x != -1, -1);
}
Where 'FirstOr' is:
public static T FirstOr<T>(this IEnumerable<T> source, T alternate)
{
return source.DefaultIfEmpty(alternate)
.First();
}
public static T FirstOr<T>(this IEnumerable<T> source, Func<T, bool> predicate, T alternate)
{
return source.Where(predicate)
.FirstOr(alternate);
}
I found the default JS date formatting didn't work.
So I used toLocaleString
with options
const event = new Date();
const options = { dateStyle: 'short' };
const date = event.toLocaleString('en', options);
to get: DD/MM/YYYY format
See docs for more formatting options: https://www.w3schools.com/jsref/jsref_tolocalestring.asp
Try to run this command if you are using nohup -
nohup npm start 2>/dev/null 1>/dev/null&
You can also use forever to start server
forever start -c "npm start" ./
PM2 also supports npm start
pm2 start npm -- start
Another simple way:
$("#selectedID")[0].selectedIndex = -1
As of PowerShell 2, simple:
$recipients = $addresses -split "; "
Note that the right hand side is actually a case-insensitive regular expression, not a simple match. Use csplit
to force case-sensitivity. See about_Split for more details.
You can use TreeMap which internally implements the SortedMap below is the example
Sorting by ascending ordering :
Map<Float, String> ascsortedMAP = new TreeMap<Float, String>();
ascsortedMAP.put(8f, "name8");
ascsortedMAP.put(5f, "name5");
ascsortedMAP.put(15f, "name15");
ascsortedMAP.put(35f, "name35");
ascsortedMAP.put(44f, "name44");
ascsortedMAP.put(7f, "name7");
ascsortedMAP.put(6f, "name6");
for (Entry<Float, String> mapData : ascsortedMAP.entrySet()) {
System.out.println("Key : " + mapData.getKey() + "Value : " + mapData.getValue());
}
Sorting by descending ordering :
If you always want this create the map to use descending order in general, if you only need it once create a TreeMap with descending order and put all the data from the original map in.
// Create the map and provide the comparator as a argument
Map<Float, String> dscsortedMAP = new TreeMap<Float, String>(new Comparator<Float>() {
@Override
public int compare(Float o1, Float o2) {
return o2.compareTo(o1);
}
});
dscsortedMAP.putAll(ascsortedMAP);
for further information about SortedMAP read http://examples.javacodegeeks.com/core-java/util/treemap/java-sorted-map-example/
If the present data is not important for you, you can just take down your original migration using:
rake db:migrate:down VERSION='YOUR MIGRATION FILE VERSION HERE'
Without the quotes, then make changes in the original migration and run the up migration again by:
rake db:migrate
The standard option grep -l
(that is a lowercase L) could do this.
From the Unix standard:
-l
(The letter ell.) Write only the names of files containing selected
lines to standard output. Pathnames are written once per file searched.
If the standard input is searched, a pathname of (standard input) will
be written, in the POSIX locale. In other locales, standard input may be
replaced by something more appropriate in those locales.
You also do not need -H
in this case.
try this:
Dim ws as Worksheet
Set ws = Thisworkbook.Sheets("Sheet2")
With ws
.Range("E2").Formula = "=VLOOKUP(D2,Sheet1!$A:$C,1,0)"
End With
End Sub
This just the simplified version of what you want.
No need to use Application
if you will just output the answer in the Range("E2")
.
If you want to stick with your logic, declare the variables.
See below for example.
Sub Test()
Dim rng As Range
Dim ws1, ws2 As Worksheet
Dim MyStringVar1 As String
Set ws1 = ThisWorkbook.Sheets("Sheet1")
Set ws2 = ThisWorkbook.Sheets("Sheet2")
Set rng = ws2.Range("D2")
With ws2
On Error Resume Next 'add this because if value is not found, vlookup fails, you get 1004
MyStringVar1 = Application.WorksheetFunction.VLookup(rng, ws1.Range("A1:C65536").Value, 1, False)
On Error GoTo 0
If MyStringVar1 = "" Then MsgBox "Item not found" Else MsgBox MyStringVar1
End With
End Sub
Hope this get's you started.
I tried the win32com way and xlwings way but I didn't get any luck. I use PyCharm and didn't see the .WorkBook option in the autocompletion for win32com. I got the -2147352567 error when I tried to pass a workbook as variable.
Then, I found a work around using vba shell to run my Python script. Write something on the XLS file you are working with when everything is done. So that Excel knows that it's time to run the VBA macro.
But the vba Application.wait function will take up 100% cpu which is wierd. Some people said that using the windows Sleep function would fix it.
Import xlsxwriter
Shell "C:\xxxxx\python.exe
C:/Users/xxxxx/pythonscript.py"
exitLoop = 0
wait for Python to finish its work.
Do
waitTime = TimeSerial(Hour(Now), Minute(Now), Second(Now) + 30)
Application.Wait waitTime
Set wb2 = Workbooks.Open("D:\xxxxx.xlsx", ReadOnly:=True)
exitLoop = wb2.Worksheets("blablabla").Cells(50, 1)
wb2.Close exitLoop
Loop While exitLoop <> 1
Call VbaScript
get the latest version information from:
https://mvnrepository.com/artifact/org.apache.maven.plugins/maven-compiler-plugin
click on the latest version (or the one you'd like to use) and you'll see the the dependency info (as of 2019-05 it's 3.8.1):
<!-- https://mvnrepository.com/artifact/org.apache.maven.plugins/maven-compiler-plugin -->
<dependency>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.8.1</version>
</dependency>
you might want to use the version tag and the comment for your plugin tag.
<!-- https://mvnrepository.com/artifact/org.apache.maven.plugins/maven-compiler-plugin -->
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.8.1</version>
<configuration>
<source />
<target />
</configuration>
</plugin>
if you like you can modify your pom to have the version information in the properties tag as outlined in another answer.
Following is the function to resize bitmap by keeping the same Aspect Ratio. Here I have also written a detailed blog post on the topic to explain this method. Resize a Bitmap by Keeping the Same Aspect Ratio.
public static Bitmap resizeBitmap(Bitmap source, int maxLength) {
try {
if (source.getHeight() >= source.getWidth()) {
int targetHeight = maxLength;
if (source.getHeight() <= targetHeight) { // if image already smaller than the required height
return source;
}
double aspectRatio = (double) source.getWidth() / (double) source.getHeight();
int targetWidth = (int) (targetHeight * aspectRatio);
Bitmap result = Bitmap.createScaledBitmap(source, targetWidth, targetHeight, false);
if (result != source) {
}
return result;
} else {
int targetWidth = maxLength;
if (source.getWidth() <= targetWidth) { // if image already smaller than the required height
return source;
}
double aspectRatio = ((double) source.getHeight()) / ((double) source.getWidth());
int targetHeight = (int) (targetWidth * aspectRatio);
Bitmap result = Bitmap.createScaledBitmap(source, targetWidth, targetHeight, false);
if (result != source) {
}
return result;
}
}
catch (Exception e)
{
return source;
}
}
You can add this in yourProject/app/build.gradle
inside android{}
android {
packagingOptions {
exclude 'META-INF/DEPENDENCIES'
exclude 'META-INF/LICENSE'
exclude 'META-INF/LICENSE.txt'
exclude 'META-INF/license.txt'
exclude 'META-INF/NOTICE'
exclude 'META-INF/NOTICE.txt'
exclude 'META-INF/notice.txt'
exclude 'META-INF/ASL2.0'
exclude("META-INF/*.kotlin_module")
}
}
For .nupkg files I like to use:
Install-Package C:\Path\To\Some\File.nupkg
Try this
DECLARE @xml xml, @str varchar(100), @delimiter varchar(10)
SET @str = '1,2,3,4,5,6,7,8,9,10,11,12,13,14,15'
SET @delimiter = ','
SET @xml = cast(('<X>'+replace(@str, @delimiter, '</X><X>')+'</X>') as xml)
SELECT C.value('.', 'varchar(10)') as value FROM @xml.nodes('X') as X(C)
OR
DECLARE @str varchar(100), @delimiter varchar(10)
SET @str = '1,2,3,4,5,6,7,8,9,10,11,12,13,14,15'
SET @delimiter = ','
;WITH cte AS
(
SELECT 0 a, 1 b
UNION ALL
SELECT b, CHARINDEX(@delimiter, @str, b) + LEN(@delimiter)
FROM CTE
WHERE b > a
)
SELECT SUBSTRING(@str, a,
CASE WHEN b > LEN(@delimiter)
THEN b - a - LEN(@delimiter)
ELSE LEN(@str) - a + 1 END) value
FROM cte WHERE a > 0
Many more ways of doing the same is here How to split comma delimited string?
Yowsup provide best solution with example.you can download api from https://github.com/tgalal/yowsup let me know if you have any issue.
I had this error too, my problem was in some part of code I didn't close file descriptor and in other part, I tried to open that file!!
use close(fd)
system call after you finished working on a file.
<style>
.nowrap {
white-space: nowrap;
}
</style>
...
<label for="id1" class="nowrap">label1:
<input type="text" id="id1"/>
</label>
Wrap your inputs within the label tag
An initial reaction to this would be to ask and ensure that the two object files are being linked together. This is done at the compile stage by compiling both files at the same time:
gcc -o programName a.c b.c
Or if you want to compile separately, it would be:
gcc -c a.c
gcc -c b.c
gcc -o programName a.o b.o
You are confusing a Mock
with a Spy
.
In a mock all methods are stubbed and return "smart return types". This means that calling any method on a mocked class will do nothing unless you specify behaviour.
In a spy the original functionality of the class is still there but you can validate method invocations in a spy and also override method behaviour.
What you want is
MyProcessingAgent mockMyAgent = Mockito.spy(MyProcessingAgent.class);
A quick example:
static class TestClass {
public String getThing() {
return "Thing";
}
public String getOtherThing() {
return getThing();
}
}
public static void main(String[] args) {
final TestClass testClass = Mockito.spy(new TestClass());
Mockito.when(testClass.getThing()).thenReturn("Some Other thing");
System.out.println(testClass.getOtherThing());
}
Output is:
Some Other thing
NB: You should really try to mock the dependencies for the class being tested not the class itself.
Here is a decision that works for me. I guess it's very simple to understand and execute.
SELECT
field_1,
field_2,
field_2,
random() as ordering
FROM
big_table
WHERE
some_conditions
ORDER BY
ordering
LIMIT 1000;
The easiest way is probably with VLOOKUP()
. This will require the 2nd worksheet to have the employee number column sorted though. In newer versions of Excel, apparently sorting is no longer required.
For example, if you had a "Sheet2" with two columns - A = the employee number, B = the employee's name, and your current worksheet had employee numbers in column D and you want to fill in column E, in cell E2, you would have:
=VLOOKUP($D2, Sheet2!$A$2:$B$65535, 2, FALSE)
Then simply fill this formula down the rest of column D.
Explanation:
$D2
specifies the value to search for.Sheet2!$A$2:$B$65535
specifies the range of cells to search in. Excel will search for the value in the first column of this range (in this case Sheet2!A2:A65535
). Note I am assuming you have a header cell in row 1.2
specifies a 1-based index of the column to return from within the searched range. The value of 2
will return the second column in the range Sheet2!$A$2:$B$65535
, namely the value of the B
column.FALSE
says to only return exact matches.The below is my code from reading text file to excel file.
Sub openteatfile()
Dim i As Long, j As Long
Dim filepath As String
filepath = "C:\Users\TarunReddyNuthula\Desktop\sample.ctxt"
ThisWorkbook.Worksheets("Sheet4").Range("Al:L20").ClearContents
Open filepath For Input As #1
i = l
Do Until EOF(1)
Line Input #1, linefromfile
lineitems = Split(linefromfile, "|")
For j = LBound(lineitems) To UBound(lineitems)
ThisWorkbook.Worksheets("Sheet4").Cells(i, j + 1).value = lineitems(j)
Next j
i = i + 1
Loop
Close #1
End Sub
You could try this SendKeys jQuery plugin:
http://bililite.com/blog/2011/01/23/improved-sendkeys/
$(element).sendkeys(string)
inserts string at the insertion point in an input, textarea or other element with contenteditable=true. If the insertion point is not currently in the element, it remembers where the insertion point was when sendkeys was last called (if the insertion point was never in the element, it appends to the end).
Another way of doing this, in code only, is to detect if the process is running as admin like in the answer by @NG.. And then open the application again and close the current one.
I use this code when an application only needs admin privileges when run under certain conditions, such as when installing itself as a service. So it doesn't need to run as admin all the time like the other answers force it too.
Note in the below code NeedsToRunAsAdmin
is a method that detects if under current conditions admin privileges are required. If this returns false
the code will not elevate itself. This is a major advantage of this approach over the others.
Although this code has the advantages stated above, it does need to re-launch itself as a new process which isn't always what you want.
private static void Main(string[] args)
{
if (NeedsToRunAsAdmin() && !IsRunAsAdmin())
{
ProcessStartInfo proc = new ProcessStartInfo();
proc.UseShellExecute = true;
proc.WorkingDirectory = Environment.CurrentDirectory;
proc.FileName = Assembly.GetEntryAssembly().CodeBase;
foreach (string arg in args)
{
proc.Arguments += String.Format("\"{0}\" ", arg);
}
proc.Verb = "runas";
try
{
Process.Start(proc);
}
catch
{
Console.WriteLine("This application requires elevated credentials in order to operate correctly!");
}
}
else
{
//Normal program logic...
}
}
private static bool IsRunAsAdmin()
{
WindowsIdentity id = WindowsIdentity.GetCurrent();
WindowsPrincipal principal = new WindowsPrincipal(id);
return principal.IsInRole(WindowsBuiltInRole.Administrator);
}
Don't forget to call sizeToFit()
after you change image if you then use size of UIImageView to set UIScrollView contentSize and/or compute zoom scale
let image = UIImage(named: "testImage")
imageView.image = image
imageView.sizeToFit()
scrollView.contentSize = imageView.bounds.size
My not very revealing answer:
private String md5(String s) {
try {
MessageDigest m = MessageDigest.getInstance("MD5");
m.update(s.getBytes(), 0, s.length());
BigInteger i = new BigInteger(1,m.digest());
return String.format("%1$032x", i);
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
return null;
}
Quoting the Scheduling Repeating Alarms - Understand the Trade-offs docs:
A common scenario for triggering an operation outside the lifetime of your app is syncing data with a server. This is a case where you might be tempted to use a repeating alarm. But if you own the server that is hosting your app's data, using Google Cloud Messaging (GCM) in conjunction with sync adapter is a better solution than AlarmManager. A sync adapter gives you all the same scheduling options as AlarmManager, but it offers you significantly more flexibility.
So, based on this, the best way to schedule a server call is using Google Cloud Messaging (GCM) in conjunction with sync adapter.
Just piling on... similar to Feiyu Zhou's post. Here I'm adding the machine name.
public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
WebHost.CreateDefaultBuilder(args)
.ConfigureAppConfiguration((context, builder) =>
{
var env = context.HostingEnvironment;
var hostname = Environment.MachineName;
builder.AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
.AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true, reloadOnChange: true)
.AddJsonFile($"appsettings.{hostname}.json", optional: true, reloadOnChange: true);
builder.AddEnvironmentVariables();
if (args != null)
{
builder.AddCommandLine(args);
}
})
.UseStartup<Startup>();
}
You are missing setting what field is the Text and Value in the SelectList itself. That is why it does a .ToString()
on each object in the list. You could think that given it is a list of SelectListItem
it should be smart enough to detect this... but it is not.
u.UserTypeOptions = new SelectList(
new List<SelectListItem>
{
new SelectListItem { Selected = true, Text = string.Empty, Value = "-1"},
new SelectListItem { Selected = false, Text = "Homeowner", Value = ((int)UserType.Homeowner).ToString()},
new SelectListItem { Selected = false, Text = "Contractor", Value = ((int)UserType.Contractor).ToString()},
}, "Value" , "Text", 1);
BTW, you can use a list of array of any type... and then just set the name of the properties that will act as Text and Value.
I think it is better to do it like this:
u.UserTypeOptions = new SelectList(
new List<SelectListItem>
{
new SelectListItem { Text = "Homeowner", Value = ((int)UserType.Homeowner).ToString()},
new SelectListItem { Text = "Contractor", Value = ((int)UserType.Contractor).ToString()},
}, "Value" , "Text");
I removed the -1 item, and the setting of each items selected true/false.
Then, in your view:
@Html.DropDownListFor(m => m.UserType, Model.UserTypeOptions, "Select one")
This way, if you set the "Select one" item, and you don't set one item as selected in the SelectList, the UserType
will be null (the UserType
need to be int?
).
If you need to set one of the SelectList items as selected, you can use:
u.UserTypeOptions = new SelectList(options, "Value" , "Text", userIdToBeSelected);
Try the common syntax instead:
if (strlen($message)<140) {
echo "less than 140";
}
else
if (strlen($message)>140) {
echo "more than 140";
}
else {
echo "exactly 140";
}
Using docker links, you can link the upstream container to the nginx container. An added feature is that docker manages the host file, which means you'll be able to refer to the linked container using a name rather than the potentially random ip.
For regular Windows users who are not skilled with computers, it is practically not possible to install and use extensions from outside the Chrome Web Store.
Users of other operating systems (Linux, Mac, Chrome OS) can easily install unpacked extensions (in developer mode).
Windows users can also load an unpacked extension, but they will always see an information bubble with "Disable developer mode extensions" when they start Chrome or open a new incognito window, which is really annoying. The only way for Windows users to use unpacked extensions without such dialogs is to switch to Chrome on the developer channel, by installing https://www.google.com/chrome/browser/index.html?extra=devchannel#eula.
Extensions can be loaded in unpacked mode by following the following steps:
chrome://extensions
(via omnibox or menu -> Tools -> Extensions).If you have a crx
file, then it needs to be extracted first. CRX files are zip files with a different header. Any capable zip program should be able to open it. If you don't have such a program, I recommend 7-zip.
These steps will work for almost every extension, except extensions that rely on their extension ID. If you use the previous method, you will get an extension with a random extension ID. If it is important to preserve the extension ID, then you need to know the public key of your CRX file and insert this in your manifest.json. I have previously given a detailed explanation on how to get and use this key at https://stackoverflow.com/a/21500707.
SUBSTR(column, LENGTH(column) - 3, 4)
LENGTH
returns length of string and SUBSTR
returns 4 characters from "the position length - 4"
please close the android studio and remove the file
.gradle
and
.idea
file form your project .Hope so it is helpful
Location:Go to Android studio projects->your project ->see both file remove (.gradle
& .idea
)
you can write a generic method as (its too late but below code will help you/others)
public static FileInputStream getFile(File fileImport) throws IOException {
FileInputStream fileStream = null;
try {
PrintWriter writer = new PrintWriter(fileImport);
writer.print(StringUtils.EMPTY);
fileStream = new FileInputStream(fileImport);
} catch (Exception ex) {
ex.printStackTrace();
} finally {
writer.close();
}
return fileStream;
}
Here's a method that can do it for any Enum, and is case insensitive.
/**
* Finds the value of the given enumeration by name, case-insensitive.
* Throws an IllegalArgumentException if no match is found.
**/
public static <T extends Enum<T>> T valueOfIgnoreCase(
Class<T> enumeration, String name) {
for (T enumValue : enumeration.getEnumConstants()) {
if (enumValue.name().equalsIgnoreCase(name)) {
return enumValue;
}
}
throw new IllegalArgumentException(String.format(
"There is no value with name '%s' in Enum %s",
name, enumeration.getName()
));
}
unplug not necessary,just uninstall your port,restart and install driver again.you will see arduino COM port under the LPT & PORT section.
Your file structure says that folder name is Container
with a capital C. But you are trying to import it by container
with a lowercase c. You will need to change the import or the folder name because the paths are case sensitive.
// sample C#
public void populateButtons()
{
int xPos;
int yPos;
Random ranNum = new Random();
for (int i = 0; i < 50; i++)
{
Button foo = new Button();
Style buttonStyle = Window.Resources["CurvedButton"] as Style;
int sizeValue = ranNum.Next(50);
foo.Width = sizeValue;
foo.Height = sizeValue;
foo.Name = "button" + i;
xPos = ranNum.Next(300);
yPos = ranNum.Next(200);
foo.HorizontalAlignment = HorizontalAlignment.Left;
foo.VerticalAlignment = VerticalAlignment.Top;
foo.Margin = new Thickness(xPos, yPos, 0, 0);
foo.Style = buttonStyle;
foo.Click += new RoutedEventHandler(buttonClick);
LayoutRoot.Children.Add(foo);
}
}
private void buttonClick(object sender, EventArgs e)
{
//do something or...
Button clicked = (Button) sender;
MessageBox.Show("Button's name is: " + clicked.Name);
}
I am using ,Mongo 3.4.0
The $rename operator updates the name of a field and has the following form:
{$rename: { <field1>: <newName1>, <field2>: <newName2>, ... } }
for e.g
db.getCollection('user').update( { _id: 1 }, { $rename: { 'fname': 'FirstName', 'lname': 'LastName' } } )
The new field name must differ from the existing field name. To specify a in an embedded document, use dot notation.
This operation renames the field nmae to name for all documents in the collection:
db.getCollection('user').updateMany( {}, { $rename: { "add": "Address" } } )
db.getCollection('user').update({}, {$rename:{"name.first":"name.FirstName"}}, false, true);
In the method above false, true are: { upsert:false, multi:true }.To update all your records, You need the multi:true.
Rename a Field in an Embedded Document
db.getCollection('user').update( { _id: 1 }, { $rename: { "name.first": "name.fname" } } )
use link : https://docs.mongodb.com/manual/reference/operator/update/rename/
It depends on how and when you want to redirect the user to another page.
If you want to instantly redirect a user to another page without him seeing anything of a site in between, you should use the PHP header
redirect method.
If you have a Javascript and some action of the user has to result in him entering another page, that is when you should use window.location
.
The meta
tag refresh is often used on download sites whenever you see these "Your download should start automatically" messages. You can let the user load a page, wait for a certain amount of time, then redirect him (e.g. to a to-be-downloaded file) without Javascript.
I think that once you've imported it, the behaviour is the same (in the place your variable will be used outside source file).
The only difference would be if you try to reassign it before the end of this very file.
ModelAndView: The name itself explains it is data structure which contains Model and View data.
Map() model=new HashMap();
model.put("key.name", "key.value");
new ModelAndView("view.name", model);
// or as follows
ModelAndView mav = new ModelAndView();
mav.setViewName("view.name");
mav.addObject("key.name", "key.value");
if model contains only single value, we can write as follows:
ModelAndView("view.name","key.name", "key.value");
NSDate* now
and NSDate *now
are the same thing: a pointer to an NSDate object.
You probably want to use descriptionWithCalendarFormat:timeZone:locale: rather than dateWithCalendarFormat: — the latter returns an NSCalendarDate, which the docs say is scheduled to be deprecated at some point.
There are two useful tutorials about image picker with downloadable source code here:
How to Create Android Image Picker
How to Select and Crop Image on Android
However, the app will be forced to close sometime, you can fix it by adding android:configChanges attribute into main activity in Manifest file like as:
<activity android:name=".MainActivity"
android:label="@string/app_name" android:configChanges="keyboardHidden|orientation" >
It seems that the camera API lost control with orientation so this will help it. :)
I found a straight forward way of solving this, with the use of JSON.parse.
Let's assume the json below is inside the variable jsontext.
[
["Blankaholm", "Gamleby"],
["2012-10-23", "2012-10-22"],
["Blankaholm. Under natten har det varit inbrott", "E22 i med Gamleby. Singelolycka. En bilist har.],
["57.586174","16.521841"], ["57.893162","16.406090"]
]
The solution is this:
var parsedData = JSON.parse(jsontext);
Now I can access the elements the following way:
var cities = parsedData[0];
I have used in this way.. Working fine!
$inputs = request()->validate([
'name' => 'required | min:6 | max: 20',
'email' => 'required',
'password' => 'required| min:4| max:7 |confirmed',
'password_confirmation' => 'required| min:4'
]);
date('Y-m-d H:i:s')
. See the manual for more.
If you are using T-SQL then it appears from previous posts that UNION removes duplicates. But if you are not, you could use distinct. This doesn't quite feel right to me either but it could get you the result you are looking for
SELECT DISTINCT *
FROM
(
select * from calls
left join users a on calls.assigned_to= a.user_id
where a.dept = 4
union
select * from calls
left join users r on calls.requestor_id= r.user_id
where r.dept = 4
)a
You can create an extension function or just use setCompoundDrawablesWithIntrinsicBounds
directly.
fun TextView.leftDrawable(@DrawableRes id: Int = 0) {
this.setCompoundDrawablesWithIntrinsicBounds(id, 0, 0, 0)
}
If you need to resize the drawable, you can use this extension function.
textView.leftDrawable(R.drawable.my_icon, R.dimen.icon_size)
fun TextView.leftDrawable(@DrawableRes id: Int = 0, @DimenRes sizeRes: Int) {
val drawable = ContextCompat.getDrawable(context, id)
val size = resources.getDimensionPixelSize(sizeRes)
drawable?.setBounds(0, 0, size, size)
this.setCompoundDrawables(drawable, null, null, null)
}
To get really fancy, create a wrapper that allows size and/or color modification.
textView.leftDrawable(R.drawable.my_icon, colorRes = R.color.white)
fun TextView.leftDrawable(@DrawableRes id: Int = 0, @DimenRes sizeRes: Int = 0, @ColorInt color: Int = 0, @ColorRes colorRes: Int = 0) {
val drawable = drawable(id)
if (sizeRes != 0) {
val size = resources.getDimensionPixelSize(sizeRes)
drawable?.setBounds(0, 0, size, size)
}
if (color != 0) {
drawable?.setColorFilter(color, PorterDuff.Mode.SRC_ATOP)
} else if (colorRes != 0) {
val colorInt = ContextCompat.getColor(context, colorRes)
drawable?.setColorFilter(colorInt, PorterDuff.Mode.SRC_ATOP)
}
this.setCompoundDrawables(drawable, null, null, null)
}
The keyword var is used to define a variable whose value you can easily change like this:
var no1 = 1 // declaring the variable
no1 = 2 // changing the value since it is defined as a variable not a constant
However, the let keyword is only to create a constant used when you do not want to change the value of the constant again. If you were to try changing the value of the constant, you will get an error:
let no2 = 5 // declaring no2 as a constant
no2 = 8 // this will give an error as you cannot change the value of a constant
I think it is best approach,
public static byte[] addAll(final byte[] array1, byte[] array2) {
byte[] joinedArray = Arrays.copyOf(array1, array1.length + array2.length);
System.arraycopy(array2, 0, joinedArray, array1.length, array2.length);
return joinedArray;
}
You can try something like this....
Dim cbTime
Set cbTime = ActiveSheet.CheckBoxes.Add(100, 100, 50, 15)
With cbTime
.Name = "cbTime"
.Characters.Text = "Time"
End With
If ActiveSheet.CheckBoxes("cbTime").Value = 1 Then 'or just cbTime.Value
'checked
Else
'unchecked
End If
import os
for root, dirs, files in os.walk(top, topdown=False):
for name in dirs:
print os.path.join(root, name)
Walk is a good built-in for what you are doing
Disabling pyright worked perfectly for me on VS.
I faced the same problem. You just have to make it an array and moreover you have to put double squared brackets to make it a single element of the 2D array as first bracket initializes the array and the second makes it an element of that array.
So simply replace the last statement by:
print(clf.predict(np.array[[0.58,0.76]]))
This will select empty text inputs with an id that starts with "txt":
$(':text[value=""][id^=txt]')
You need to escape it with two backslashes
\\?
See this for more details:
http://www.trans4mind.com/personal_development/JavaScript/Regular%20Expressions%20Simple%20Usage.htm
You can copy the HTML code to the clipboard and paste special it back as Unicode text. Excel will render the HTML in the cell. Check out this post http://www.dailydoseofexcel.com/archives/2005/02/23/html-in-cells-ii/
The relevant macro code from the post:
Private Sub Worksheet_Change(ByVal Target As Range)
Dim objData As DataObject
Dim sHTML As String
Dim sSelAdd As String
Application.EnableEvents = False
If Target.Cells.Count = 1 Then
If LCase(Left(Target.Text, 6)) = "<html>" Then
Set objData = New DataObject
sHTML = Target.Text
objData.SetText sHTML
objData.PutInClipboard
sSelAdd = Selection.Address
Target.Select
Me.PasteSpecial "Unicode Text"
Me.Range(sSelAdd).Select
End If
End If
Application.EnableEvents = True
End Sub
Json.NET has a JsonPropertyAttribute
which allows you to specify the name of a JSON property, so your code should be:
public class TeamScore
{
[JsonProperty("eighty_min_score")]
public string EightyMinScore { get; set; }
[JsonProperty("home_or_away")]
public string HomeOrAway { get; set; }
[JsonProperty("score ")]
public string Score { get; set; }
[JsonProperty("team_id")]
public string TeamId { get; set; }
}
public class Team
{
public string v1 { get; set; }
[JsonProperty("attributes")]
public TeamScore TeamScores { get; set; }
}
public class RootObject
{
public List<Team> Team { get; set; }
}
Documentation: Serialization Attributes
git fetch origin our-team
or
git pull origin our-team
but first you should make sure that you already on the branch you want to update to (featurex).
I had from a totaly different reason the same notice "Value does not fall within the expected range" from the Visual studio 2008 while trying to use the: Tools -> Windows Embedded Silverlight Tools -> Update Silverlight For Windows Embedded Project.
After spending many ohurs I found out that the problem was that there wasn't a resource file and the update tool looks for the .RC file
Therefor the solution is to add to the resource folder a .RC file and than it works perfectly. I hope it will help someone out there
You can append the values in the query string for the next page to see and process. You can wrap them inside the link tags:
<a href="your_page.php?var1=value1&var2=value2">
You separate each of those values with the &
sign.
Or you can create this on a button click like this:
<input type="button" onclick="document.location.href = 'your_page.php?var1=value1&var2=value2';">
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:
Everything is great but none of you explained where to download the SDK build tools
.val()
always works with textarea
elements.
.text()
works sometimes and fails other times! It's not reliable (tested in Chrome 33)
What's best is that .val()
works seamlessly with other form elements too (like input
) whereas .text()
fails.
You have two options here, 1. Use for
instead for foreach
for iteration.But in your case the collection is IEnumerable and the upper limit of the collection is unknown so foreach will be the best option. so i prefer to use another integer variable to hold the iteration count: here is the code for that:
int i = 0; // for index
foreach (var row in list)
{
bool IsChecked;// assign value to this variable
if (IsChecked)
{
// use i value here
}
i++; // will increment i in each iteration
}
if you are using Eclipse. You should switch to DDMS perspective from top-right corner there after selecting your device you can see folder tree. to install apk manually you can use adb command
adb install apklocation.apk
As mentioned by others, this is used for front end cache busting. To implement this, I have personally find grunt-cache-bust npm package useful.
Depending on the libc release it could be needed to set both SO_REUSEADDR and SO_REUSEPORT socket options as explained in socket(7) documentation :
SO_REUSEPORT (since Linux 3.9) Permits multiple AF_INET or AF_INET6 sockets to be bound to an identical socket address. This option must be set on each socket (including the first socket) prior to calling bind(2) on the socket. To prevent port hijacking, all of the processes binding to the same address must have the same effective UID. This option can be employed with both TCP and UDP sockets.
As this socket option appears with kernel 3.9 and raspberry use 3.12.x, it will be needed to set SO_REUSEPORT.
You can set theses two options before calling bind like this :
int reuse = 1;
if (setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, (const char*)&reuse, sizeof(reuse)) < 0)
perror("setsockopt(SO_REUSEADDR) failed");
#ifdef SO_REUSEPORT
if (setsockopt(sockfd, SOL_SOCKET, SO_REUSEPORT, (const char*)&reuse, sizeof(reuse)) < 0)
perror("setsockopt(SO_REUSEPORT) failed");
#endif
There is a subtle differences between String object and string literal.
String s = "abc"; // creates one String object and one reference variable
In this simple case, "abc" will go in the pool and s will refer to it.
String s = new String("abc"); // creates two objects,and one reference variable
In this case, because we used the new
keyword, Java will create a new String object
in normal (non-pool) memory, and s will refer to it. In addition, the literal "abc" will
be placed in the pool.
Each project in Visual Studio has a "treat warnings as errors" option. Go through each of your projects and change that setting:
The location of this switch varies, depending on the type of project (class library vs. web application, for example).
And another useful command to do this (after git fetch) is:
git log origin/master ^master
This shows the commits that are in origin/master but not in master. You can also do it in opposite when doing git pull, to check what commits will be submitted to remote.
Why aren't we following the simplest method here "remove" looped inside while.
const foo = document.querySelector(".foo");
while (foo.firstChild) {
foo.firstChild.remove();
}
<div class="row">_x000D_
<div class="col-md-10 col-md-pull-2">_x000D_
col-md-10 col-md-pull-2_x000D_
</div>_x000D_
<div class="col-md-10 col-md-pull-2">_x000D_
col-md-10 col-md-pull-2_x000D_
</div>_x000D_
</div>
_x000D_
Here is a batch file that generates all 10.x.x.x addresses
@echo off
SET /A X=0
SET /A Y=0
SET /A Z=0
:loop
SET /A X+=1
echo 10.%X%.%Y%.%Z%
IF "%X%" == "256" (
GOTO end
) ELSE (
GOTO loop2
GOTO loop
)
:loop2
SET /A Y+=1
echo 10.%X%.%Y%.%Z%
IF "%Y%" == "256" (
SET /A Y=0
GOTO loop
) ELSE (
GOTO loop3
GOTO loop2
)
:loop3
SET /A Z+=1
echo 10.%X%.%Y%.%Z%
IF "%Z%" == "255" (
SET /A Z=0
GOTO loop2
) ELSE (
GOTO loop3
)
:end
just enhancing above solution.. so header it self resize its width in order to accommodate lengthy string like 12345
private void advancedDataGridView1_RowPostPaint(object sender, DataGridViewRowPostPaintEventArgs e)
{
var grid = sender as DataGridView;
var rowIdx = (e.RowIndex + 1).ToString();
var centerFormat = new StringFormat()
{
// right alignment might actually make more sense for numbers
Alignment = StringAlignment.Center,
LineAlignment = StringAlignment.Center
};
//get the size of the string
Size textSize = TextRenderer.MeasureText(rowIdx, this.Font);
//if header width lower then string width then resize
if (grid.RowHeadersWidth < textSize.Width + 40)
{
grid.RowHeadersWidth = textSize.Width + 40;
}
var headerBounds = new Rectangle(e.RowBounds.Left, e.RowBounds.Top, grid.RowHeadersWidth, e.RowBounds.Height);
e.Graphics.DrawString(rowIdx, this.Font, SystemBrushes.ControlText, headerBounds, centerFormat);
}
In order to hide the exception:
For Hibernate 5.2 (and Spring Boot 2.0), you can either use the use_jdbc_metadata_defaults property that the others pointed out:
# Meant to hide HHH000424: Disabling contextual LOB creation as createClob() method threw error
spring.jpa.properties.hibernate.temp.use_jdbc_metadata_defaults: false
Or, if you want to not have any side effects from the above setting (there's a comment warning us about some Oracle side effects, I don't know if it's valid or not), you can just disable the logging of the exception like this:
logging:
level:
# Hides HHH000424: Disabling contextual LOB creation as createClob() method threw error
org.hibernate.engine.jdbc.env.internal.LobCreatorBuilderImpl: WARN