Another correct way to get selected value would be using this selector:
$("option[value="0"]:selected")
Best for you!
I've done like this and it works:
$('[name="tcol1"]')
Just in case any dummies like me tried the suggestions here with a button and found nothing worked, you probably want this:
$(':button.myclass')
I found it best to just remove the DOM completely.
$(".form-group #selectId option[value='39']").remove();
Cross browser compatible. Works on IE11 too
you can use
$('option:selected').next('option')
or
$('option:selected + option')
And set the value:
var nextVal = $('option:selected + option').val();
$('select').val(nextVal);
When setting with JQM
, don't forget to update the UI
:
$('#selectId').val('newValue').selectmenu('refresh', true);
The W3C solution:
var len = document.getElementById("input1").length;
Replace this:
var cat = $.jqURL.get('category');
var $dd = $('#cbCategory');
var $options = $('option', $dd);
$options.each(function() {
if ($(this).text() == cat)
$(this).select(); // This is where my problem is
});
With this:
$('#cbCategory').val(cat);
Calling val()
on a select list will automatically select the option with that value, if any.
This worked:
$("#theSelectId").prepend("<option value='' selected='selected'></option>");
Firebug Output:
<select id="theSelectId">
<option selected="selected" value=""/>
<option value="volvo">Volvo</option>
<option value="saab">Saab</option>
<option value="mercedes">Mercedes</option>
<option value="audi">Audi</option>
</select>
You could also use .prependTo
if you wanted to reverse the order:
?$("<option>", { value: '', selected: true }).prependTo("#theSelectId");???????????
I've always had issues with prop('selected'), the following has always worked for me:
//first remove the current value
$("#selectBox").children().removeAttr("selected");
$("#selectBox").children().eq(index).attr('selected', 'selected');
If you'd like to know the value of the default selected radio button before a click event, try this:
alert($("input:radio:checked").val());
md5.h
also have MD5_*
functions very useful for big file
#include <openssl/md5.h>
#include <fstream>
.......
std::ifstream file(filename, std::ifstream::binary);
MD5_CTX md5Context;
MD5_Init(&md5Context);
char buf[1024 * 16];
while (file.good()) {
file.read(buf, sizeof(buf));
MD5_Update(&md5Context, buf, file.gcount());
}
unsigned char result[MD5_DIGEST_LENGTH];
MD5_Final(result, &md5Context);
Very simple, isn`t it? Convertion to string also very simple:
#include <sstream>
#include <iomanip>
.......
std::stringstream md5string;
md5string << std::hex << std::uppercase << std::setfill('0');
for (const auto &byte: result)
md5string << std::setw(2) << (int)byte;
return md5string.str();
.jar and .war are both zipped archived files. Both can have the optional META-INF/MANIFEST.MF manifest file which hold informative information like versioning, and instructional attributes like classpath and main-class for the JVM that will execute it.
.war file - Web Application Archive intended to be execute inside a 'Servlet Container' and may include other jar files (at WEB-INF/lib directory) compiled classes (at WEB-INF/classes (servlet goes there too)) .jsp files images, files etc. All WAR content that is there in order to create a self-contained module.
If you declare a DateTime, then the default value is DateTime.MinValue, and hence you have to check it like this:
DateTime dat = new DateTime();
if (dat==DateTime.MinValue)
{
//unassigned
}
If the DateTime is nullable, well that's a different story:
DateTime? dat = null;
if (!dat.HasValue)
{
//unassigned
}
I see a couple of issues.
First:
ser.read() is only going to return 1 byte at a time.
If you specify a count
ser.read(5)
it will read 5 bytes (less if timeout occurrs before 5 bytes arrive.)
If you know that your input is always properly terminated with EOL characters, better way is to use
ser.readline()
That will continue to read characters until an EOL is received.
Second:
Even if you get ser.read() or ser.readline() to return multiple bytes, since you are iterating over the return value, you will still be handling it one byte at a time.
Get rid of the
for line in ser.read():
and just say:
line = ser.readline()
It is because of CASCADE TYPE
if you put
@OneToOne(cascade=CascadeType.ALL)
You can just save your object like this
user.setCountry(country);
session.save(user)
but if you put
@OneToOne(cascade={
CascadeType.PERSIST,
CascadeType.REFRESH,
...
})
You need to save your object like this
user.setCountry(country);
session.save(country)
session.save(user)
Ok, you've declared junit
dependency for test
classes only (those that are in src/test/java
but you're trying to use it in main
classes (those that are in src/main/java
).
Either do not use it in main classes, or remove <scope>test</scope>
.
This worked for me:
This is the directory where all the APKs are stored:
cd /system/app
List them:
ls
Choose one to remove.
pm install -r <app_to_remove>.apk
Example:
$ pm install -r Google-Play-services.apk
pkg: Google-Play-services.apk
Success
Also, I noticed you might have to run (on a rooted device):
$ su
# mount -o remount +rw /
You can do something like this to read your nodes.
Also you can find some explanation in this page http://www.compoc.com/tuts/
<script type="text/javascript">
var markers = null;
$(document).ready(function () {
$.get("File.xml", {}, function (xml){
$('marker',xml).each(function(i){
markers = $(this);
});
});
});
</script>
If your server certificated file is not trusted, (for example, you may generate the keystore by yourself with keytool command in java), you should add the extra option rejectUnauthorized
var socket = io.connect('https://localhost', {rejectUnauthorized: false});
Replace next()
with nextLine()
:
String productDescription = input.nextLine();
Mac: Code -> Preferences -> Settings -> Type wordwrap in Search settings -> Change Editor: Word Wrap from off to on.
Windows: File -> Preferences -> Settings -> Type wordwrap in Search settings -> Change Editor: Word Wrap from off to on.
There are 3 scenarios, you describe:
.c
files and with int i;
in the header..c
files and with int i=100;
in the header (or any other value; that doesn't matter)..c
file and with int i=100;
in the header.In each scenario, imagine the contents of the header file inserted into the .c
file and this .c
file compiled into a .o
file and then these linked together.
Then following happens:
works fine because of the already mentioned "tentative definitions": every .o
file contains one of them, so the linker says "ok".
doesn't work, because both .o
files contain a definition with a value, which collide (even if they have the same value) - there may be only one with any given name in all .o
files which are linked together at a given time.
works of course, because you have only one .o
file and so no possibility for collision.
IMHO a clean thing would be
extern int i;
or just int i;
into the header file,int i = 100;
) into file1.c
. In this case, this initialization gets used at the start of the program and the corresponding line in main()
can be omitted. (Besides, I hope the naming is only an example; please don't name any global variables as i
in real programs.)You need the following permissions in your manifest file:
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE"></uses-permission>
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE"></uses-permission>
Then you can use the following in your activity class:
WifiManager wifiManager = (WifiManager) this.getApplicationContext().getSystemService(Context.WIFI_SERVICE);
wifiManager.setWifiEnabled(true);
wifiManager.setWifiEnabled(false);
Use the following to check if it's enabled or not
boolean wifiEnabled = wifiManager.isWifiEnabled()
You'll find a nice tutorial on the subject on this site.
From the link in the error message:
This occurs when the default configuration files log4j.properties and log4j.xml can not be found and the application performs no explicit configuration. log4j uses Thread.getContextClassLoader().getResource() to locate the default configuration files and does not directly check the file system. Knowing the appropriate location to place log4j.properties or log4j.xml requires understanding the search strategy of the class loader in use. log4j does not provide a default configuration since output to the console or to the file system may be prohibited in some environments. Also see FAQ: Why can't log4j find my properties in a J2EE or WAR application?.
The configuration file cannot be found. Are you using xml or a property file??
Also, use logback!
I got the color range to be asymmetric simply by changing the symkey argument to FALSE
symm=F,symkey=F,symbreaks=T, scale="none"
Solved the color issue with colorRampPalette with the breaks argument to specify the range of each color, e.g.
colors = c(seq(-3,-2,length=100),seq(-2,0.5,length=100),seq(0.5,6,length=100))
my_palette <- colorRampPalette(c("red", "black", "green"))(n = 299)
Altogether
heatmap.2(as.matrix(SeqCountTable), col=my_palette,
breaks=colors, density.info="none", trace="none",
dendrogram=c("row"), symm=F,symkey=F,symbreaks=T, scale="none")
If you need to join xpath-selected text nodes but can not use string-join
(when you are stuck with XSL 1.0) this might help:
<xsl:variable name="x">
<xsl:apply-templates select="..." mode="string-join-mode"/>
</xsl:variable>
joined and normalized: <xsl:value-of select="normalize-space($x)"/>
<xsl:template match="*" mode="string-join-mode">
<xsl:apply-templates mode="string-join-mode"/>
</xsl:template>
<xsl:template match="text()" mode="string-join-mode">
<xsl:value-of select="."/>
</xsl:template>
Setting of your PC -> Network And Internet Proxy -> Automatic Proxy Setup then set Automatically detect settings to off and clear the Script Address
When using spring boot, this link might be useful: https://docs.spring.io/spring-boot/docs/2.3.x/reference/html/howto.html#howto-properties-and-configuration
With spring-boot-starter-parent you just need to add the following to your application config file:
# get values from pom.xml
[email protected]@
After that the value is available like this:
@Value("${pom.version}")
private String pomVersion;
When you set maven scope as provided
, it means that when the plugin runs, the actual dependencies version used will depend on the version of Apache Maven you have installed.
- Line Feed and Carriage Return
These HTML entities will insert a new line or carriage return inside a text area.
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
If you don't want your new column to be of type IDENTITY
(auto-increment), or you want to be specific about the order in which your rows are numbered, you can add a column of type INT NULL
and then populate it like this. In my example, the new column is called MyNewColumn and the existing primary key column for the table is called MyPrimaryKey.
UPDATE MyTable
SET MyTable.MyNewColumn = AutoTable.AutoNum
FROM
(
SELECT MyPrimaryKey,
ROW_NUMBER() OVER (ORDER BY SomeColumn, SomeOtherColumn) AS AutoNum
FROM MyTable
) AutoTable
WHERE MyTable.MyPrimaryKey = AutoTable.MyPrimaryKey
This works in SQL Sever 2005 and later, i.e. versions that support ROW_NUMBER()
This might be helpful, in some way. Fixing some code from @diogo
$(window).on('load',function(){
// get the maxHeight using innerHeight() function
var maxHeight = Math.max.apply(null, $("div.panel").map(function () {
return $(this).innerHeight();
}).get());
// Set the height to all .panel elements
$("div.panel").height( maxHeight );
});
While "".join is more pythonic, and the correct answer for this problem, it is indeed possible to use a for loop.
If this is a homework assignment (please add a tag if this is so!), and you are required to use a for loop then what will work (although is not pythonic, and shouldn't really be done this way if you are a professional programmer writing python) is this:
endstring = ""
mylist = ['first', 'second', 'other']
for word in mylist:
print "This is the word I am adding: " + word
endstring = endstring + word
print "This is the answer I get: " + endstring
You don't need the 'prints', I just threw them in there so you can see what is happening.
You can also find useful information about getView at the Adapter interface in Adapter.java file. It says;
/**
* Get a View that displays the data at the specified position in the data set. You can either
* create a View manually or inflate it from an XML layout file. When the View is inflated, the
* parent View (GridView, ListView...) will apply default layout parameters unless you use
* {@link android.view.LayoutInflater#inflate(int, android.view.ViewGroup, boolean)}
* to specify a root view and to prevent attachment to the root.
*
* @param position The position of the item within the adapter's data set of the item whose view
* we want.
* @param convertView The old view to reuse, if possible. Note: You should check that this view
* is non-null and of an appropriate type before using. If it is not possible to convert
* this view to display the correct data, this method can create a new view.
* Heterogeneous lists can specify their number of view types, so that this View is
* always of the right type (see {@link #getViewTypeCount()} and
* {@link #getItemViewType(int)}).
* @param parent The parent that this view will eventually be attached to
* @return A View corresponding to the data at the specified position.
*/
View getView(int position, View convertView, ViewGroup parent);
Instead of using multiple CSS classes, to address your underlying problem you can use the :focus
pseudo-selector:
input[type="text"] {
border: 1px solid grey;
width: 40%;
height: 30px;
border-radius: 0;
}
input[type="text"]:focus {
border: 1px solid #5acdff;
}
var sels = //Here is your array of SELECTs
var json = { };
for(var i = 0, l = sels.length; i < l; i++) {
json[sels[i].id] = sels[i].value;
}
It sounds like you want to re-implement, or possibly extend, AuthorizeAttribute
. If so, you should make sure that you inherit that, and not ActionFilterAttribute
, in order to let ASP.NET MVC do more of the work for you.
Also, you want to make sure that you authorize before you do any of the real work in the action method - otherwise, the only difference between logged in and not will be what page you see when the work is done.
public class CustomAuthorizeAttribute : AuthorizeAttribute
{
public override void OnAuthorization(AuthorizationContext filterContext)
{
// Do whatever checking you need here
// If you want the base check as well (against users/roles) call
base.OnAuthorization(filterContext);
}
}
There is a good question with an answer with more details here on SO.
You can't compare array of characters using ==
operator. You have to use string compare functions. Take a look at Strings (c-faq).
The standard library's
strcmp
function compares two strings, and returns 0 if they are identical, or a negative number if the first string is alphabetically "less than" the second string, or a positive number if the first string is "greater."
With Swift 5.2 and iOS 13.4, according to your needs, you can use one of the following examples to align your VStack
with top leading constraints and a full size frame.
Note that the code snippets below all result in the same display, but do not guarantee the effective frame of the VStack
nor the number of View
elements that might appear while debugging the view hierarchy.
frame(minWidth:idealWidth:maxWidth:minHeight:idealHeight:maxHeight:alignment:)
methodThe simplest approach is to set the frame of your VStack
with maximum width and height and also pass the required alignment in frame(minWidth:idealWidth:maxWidth:minHeight:idealHeight:maxHeight:alignment:)
:
struct ContentView: View {
var body: some View {
VStack(alignment: .leading) {
Text("Title")
.font(.title)
Text("Content")
.font(.body)
}
.frame(
maxWidth: .infinity,
maxHeight: .infinity,
alignment: .topLeading
)
.background(Color.red)
}
}
As an alternative, if setting maximum frame with specific alignment for your View
s is a common pattern in your code base, you can create an extension method on View
for it:
extension View {
func fullSize(alignment: Alignment = .center) -> some View {
self.frame(
maxWidth: .infinity,
maxHeight: .infinity,
alignment: alignment
)
}
}
struct ContentView : View {
var body: some View {
VStack(alignment: .leading) {
Text("Title")
.font(.title)
Text("Content")
.font(.body)
}
.fullSize(alignment: .topLeading)
.background(Color.red)
}
}
Spacer
s to force alignmentYou can embed your VStack
inside a full size HStack
and use trailing and bottom Spacer
s to force your VStack
top leading alignment:
struct ContentView: View {
var body: some View {
HStack {
VStack(alignment: .leading) {
Text("Title")
.font(.title)
Text("Content")
.font(.body)
Spacer() // VStack bottom spacer
}
Spacer() // HStack trailing spacer
}
.frame(
maxWidth: .infinity,
maxHeight: .infinity
)
.background(Color.red)
}
}
ZStack
and a full size background View
This example shows how to embed your VStack
inside a ZStack
that has a top leading alignment. Note how the Color
view is used to set maximum width and height:
struct ContentView: View {
var body: some View {
ZStack(alignment: .topLeading) {
Color.red
.frame(maxWidth: .infinity, maxHeight: .infinity)
VStack(alignment: .leading) {
Text("Title")
.font(.title)
Text("Content")
.font(.body)
}
}
}
}
GeometryReader
GeometryReader
has the following declaration:
A container view that defines its content as a function of its own size and coordinate space. [...] This view returns a flexible preferred size to its parent layout.
The code snippet below shows how to use GeometryReader
to align your VStack
with top leading constraints and a full size frame:
struct ContentView : View {
var body: some View {
GeometryReader { geometryProxy in
VStack(alignment: .leading) {
Text("Title")
.font(.title)
Text("Content")
.font(.body)
}
.frame(
width: geometryProxy.size.width,
height: geometryProxy.size.height,
alignment: .topLeading
)
}
.background(Color.red)
}
}
overlay(_:alignment:)
methodIf you want to align your VStack
with top leading constraints on top of an existing full size View
, you can use overlay(_:alignment:)
method:
struct ContentView: View {
var body: some View {
Color.red
.frame(
maxWidth: .infinity,
maxHeight: .infinity
)
.overlay(
VStack(alignment: .leading) {
Text("Title")
.font(.title)
Text("Content")
.font(.body)
},
alignment: .topLeading
)
}
}
Display:
Compared to the methods listed here, I prefer the method that comes with the system. Here, I provide a better method without third-party libraries.
class colors: # You may need to change color settings
RED = '\033[31m'
ENDC = '\033[m'
GREEN = '\033[32m'
YELLOW = '\033[33m'
BLUE = '\033[34m'
print(colors.RED + "something you want to print in red color" + colors.ENDC)
print(colors.GREEN + "something you want to print in green color" + colors.ENDC)
print("something you want to print in system default color")
More color code , ref to : Printing Colored Text in Python
Enjoy yourself!
~50% faster
Go to the Android SDK root folder and navigate to extras\intel\Hardware_Accelerated_Execution_Manager. Execute file IntelHaxm.exe to install. (in Android Studio you can navigate to: Settings -> Android SDK -> SDK Tools -> Intel x86 Emulator Accelerator (HAXM installer))
Create AVD with "Intel atom x86" CPU/ABI
Also don't forget install this one
P.S. during AVD creation add emulation memory: Hardware/New/Device ram size/set up value 512 or more
P.S. For Fedora, for Ubuntu
P.S: Check this tool, very convenient even trial
There are two ways to display tabs at the bottom of a tab activity.
Please check the link for more details.
UPDATE mytbl
SET a = ABS(a)
where a < 0
Yes we have done this.
In your Index.cshtml you'll have something like..
<div id='gameModal' class='modal hide fade in' data-url='@Url.Action("GetGameListing")'>
<div id='gameContainer'>
</div>
</div>
<button id='showGame'>Show Game Listing</button>
Then in JS for the same page (inlined or in a separate file you'll have something like this..
$(document).ready(function() {
$('#showGame').click(function() {
var url = $('#gameModal').data('url');
$.get(url, function(data) {
$('#gameContainer').html(data);
$('#gameModal').modal('show');
});
});
});
With a method on your controller that looks like this..
[HttpGet]
public ActionResult GetGameListing()
{
var model = // do whatever you need to get your model
return PartialView(model);
}
You will of course need a view called GetGameListing.cshtml inside of your Views folder..
It would be extremely difficult to guess the problem since it is due to a an error in the WSDL and without examining the WSDL, I cannot comment much more. So if you can share your WSDL, please do so.
All I can say is that there seems to be a missing schema in the WSDL (with the target namespace 'http://service.ebms.edi.cecid.hku.hk/'). I know about issues and different handling of the schema when include instructions are ignored.
Generally I have found Microsoft's implementation of web services pretty good so I think the web service is sending back dodgy WSDL.
Iterator version
>>> import re
>>> string1 = "498results should get"
>>> [int(x.group()) for x in re.finditer(r'\d+', string1)]
[498]
I have solved my php7 issues on centos 7 by updating /etc/php.ini
with these settings:
post_max_size = 500M
upload_max_filesize = 500M
I was able to solve it by clicking on the "Kernel" drop down menu and choosing "Interrupt."
This is how I solved the issue on my computer:
Actually, it looks like you may be able to download language packs directly through Windows Update. Open the old Control Panel by pressing WinKey+X and clicking Control Panel. Then go to Clock, Language, and Region > Add a language. Add the desired language. Then under the language it should say "Windows display language: Available". Click "Options" and then "Download and install language pack."
I'm not sure why this functionality appears to be less accessible than it was in Windows 8.
You can use Url Parameters from the official documentation.
Example: this.httpClient.get(this.API, { params: new HttpParams().set('noCover', noCover) })
This is what finally worked for me.
brew reinstall postgres
After running the above command you might need to run
brew postgresql-upgrade-database
to access your previous data.
There is a couple scripts out there on the internet to create an MD5 Hash.
The one from webtoolkit is good, http://www.webtoolkit.info/javascript-md5.html
Although, I don't believe it will have access to the local filesystem as that access is limited.
To complement @gertvdijk's answer - I'm adding few screenshots in case it helps someone quick.
On my git bash shell
git branch
command without any parameters shows all my local branches. The current branch which is currently checked out is shown in different color (green) along with an asterisk (*) prefix which is really intuitive.
When you try to see all branches including the remote branches using
git branch -a
command then remote branches which aren't checked out yet are shown in red color:
DECLARE @FirstDate DATE = '2018-01-01'
DECLARE @LastDate Date = '2018-12-31'
DECLARE @tbl TABLE(ID INT IDENTITY(1,1) PRIMARY KEY,CurrDate date)
INSERT @tbl VALUES( @FirstDate)
WHILE @FirstDate < @LastDate
BEGIN
SET @FirstDate = DATEADD( day,1, @FirstDate)
INSERT @tbl VALUES( @FirstDate)
END
INSERT @tbl VALUES( @LastDate)
SELECT * FROM @tbl
Greedy means it will consume your pattern until there are none of them left and it can look no further.
Lazy will stop as soon as it will encounter the first pattern you requested.
One common example that I often encounter is \s*-\s*?
of a regex ([0-9]{2}\s*-\s*?[0-9]{7})
The first \s*
is classified as greedy because of *
and will look as many white spaces as possible after the digits are encountered and then look for a dash character "-". Where as the second \s*?
is lazy because of the present of *?
which means that it will look the first white space character and stop right there.
For iPhone Devices : Now we need only one size iPhone 6 Plus (5.5 Inch) • 1242 x 2208 Then we have check box there, in all other sizes to : Use 5.5-Inch Display
Does an implicit conversion occur between Task<> and int?
Nope. This is just part of how async
/await
works.
Any method declared as async
has to have a return type of:
void
(avoid if possible)Task
(no result beyond notification of completion/failure)Task<T>
(for a logical result of type T
in an async manner)The compiler does all the appropriate wrapping. The point is that you're asynchronously returning urlContents.Length
- you can't make the method just return int
, as the actual method will return when it hits the first await
expression which hasn't already completed. So instead, it returns a Task<int>
which will complete when the async method itself completes.
Note that await
does the opposite - it unwraps a Task<T>
to a T
value, which is how this line works:
string urlContents = await getStringTask;
... but of course it unwraps it asynchronously, whereas just using Result
would block until the task had completed. (await
can unwrap other types which implement the awaitable pattern, but Task<T>
is the one you're likely to use most often.)
This dual wrapping/unwrapping is what allows async to be so composable. For example, I could write another async method which calls yours and doubles the result:
public async Task<int> AccessTheWebAndDoubleAsync()
{
var task = AccessTheWebAsync();
int result = await task;
return result * 2;
}
(Or simply return await AccessTheWebAsync() * 2;
of course.)
Use:
$("#selectbox option:first").val()
Please find the working simple in this JSFiddle.
If you are on Azure you need you can now, you need to have Manag. Studio 2014 and update hotfix: http://blogs.msdn.com/b/sqlreleaseservices/archive/2014/12/18/sql-server-2014-management-studio-updated-support-for-the-latest-azure-sql-database-update-v12-preview.aspx
All inputs should be replaced with custom directive that reads a single global variable to toggle readonly status.
// template
<your-input [readonly]="!childmessage"></your-input>
// component value
childmessage = false;
This message means that there are certain possible method calls which may fail at run-time. Suppose you have
class A { public function foo($a = 1) {;}}
class B extends A { public function foo($a) {;}}
function bar(A $a) {$a->foo();}
The compiler only checks the call $a->foo() against the requirements of A::foo() which requires no parameters. $a may however be an object of class B which requires a parameter and so the call would fail at runtime.
This however can never fail and does not trigger the error
class A { public function foo($a) {;}}
class B extends A { public function foo($a = 1) {;}}
function bar(A $a) {$a->foo();}
So no method may have more required parameters than its parent method.
The same message is also generated when type hints do not match, but in this case PHP is even more restrictive. This gives an error:
class A { public function foo(StdClass $a) {;}}
class B extends A { public function foo($a) {;}}
as does this:
class A { public function foo($a) {;}}
class B extends A { public function foo(StdClass $a) {;}}
That seems more restrictive than it needs to be and I assume is due to internals.
Visibility differences cause a different error, but for the same basic reason. No method can be less visible than its parent method.
Exponential (You have an exponential function if MINIMAL ONE EXPONENT is dependent on a parameter):
Polynomial (You have a polynomial function if NO EXPONENT is dependent on some function parameters):
In Spring 5, or maybe in earlier versions, there is MediaType
class. It has already correct line, if you want to follow DRY:
public static final String APPLICATION_JSON_UTF8_VALUE = "application/json;charset=UTF-8";
So I use this set of controller-related annotations:
@RestController
@RequestMapping(value = "my/api/url", produces = APPLICATION_JSON_UTF8_VALUE)
public class MyController {
// ... Methods here
}
It is marked deprecated in the docs, but I've run into this issue and it is better than copy-pastying the aforementioned line on every method/controller throughout your application, I think.
Check dos and unix file format. This problem is seen on linux platforms if dos file format is used. Use doc2unix command like below and then retry it should work dos2unix *.php
This solution for below problem
Wed Nov 12 07:50:19 2014] [error] [client IP1] PHP Warning: Unknown: failed to
open stream: Permission denied in Unknown on line 0
[Wed Nov 12 07:50:19 2014] [error] [client IP1] PHP Fatal error: Unknown: Failed
opening required '/var/www/html/index.php' (include_path='.:/usr/share/pear:
/usr/share/php') in Unknown on line 0
Command-Option-Shift-K should do it. Alternatively, go to product menu, press the option key, now the option "Clean" will change to "Clean Build Folder ..." select that option.
Ok I have found a solution. The problem is that the site uses SSLv3. And I know that there are some problems in the openssl module. Some time ago I had the same problem with the SSL versions.
<?php
function getSSLPage($url) {
$ch = curl_init();
curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_SSLVERSION,3);
$result = curl_exec($ch);
curl_close($ch);
return $result;
}
var_dump(getSSLPage("https://eresearch.fidelity.com/eresearch/evaluate/analystsOpinionsReport.jhtml?symbols=api"));
?>
When you set the SSL Version with curl to v3 then it works.
Edit:
Another problem under Windows is that you don't have access to the certificates. So put the root certificates directly to curl.
http://curl.haxx.se/docs/caextract.html
here you can download the root certificates.
curl_setopt($ch, CURLOPT_CAINFO, __DIR__ . "/certs/cacert.pem");
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, true);
Then you can use the CURLOPT_SSL_VERIFYPEER
option with true
otherwise you get an error.
just install python-lib. (python27-lib). It will install libpython2.7.so1.0. We don't require to manually set anything.
You want the :checkbox:checked
selector and map
to create an array of the values:
var checkedValues = $('input:checkbox:checked').map(function() {
return this.value;
}).get();
If your checkboxes have a shared class it would be faster to use that instead, eg. $('.mycheckboxes:checked')
, or for a common name $('input[name="Foo"]:checked')
- Update -
If you don't need IE support then you can now make the map()
call more succinct by using an arrow function:
var checkedValues = $('input:checkbox:checked').map((i, el) => el.value).get();
You can increase that in php.ini
; Maximum allowed size for uploaded files.
upload_max_filesize = 2M
0 will get printed.
As in C++ true refers to 1 and false refers to 0.
In case, you want to print false instead of 0,then you have to sets the boolalpha format flag for the str stream.
When the boolalpha format flag is set, bool values are inserted/extracted by their textual representation: either true or false, instead of integral values.
#include <iostream>
int main()
{
std::cout << std::boolalpha << false << std::endl;
}
output:
false
public static void main(String arg[])
{
HashMap<String, ArrayList<String>> hashmap =
new HashMap<String, ArrayList<String>>();
ArrayList<String> arraylist = new ArrayList<String>();
arraylist.add("Hello");
arraylist.add("World.");
hashmap.put("my key", arraylist);
arraylist = hashmap.get("not inserted");
System.out.println(arraylist);
arraylist = hashmap.get("my key");
System.out.println(arraylist);
}
null
[Hello, World.]
Works fine... maybe you find your mistake in my code.
A simple JSF Url Prettyfier filter based in the steps of BalusC's answer. The filter forwards all the requests starting with the /ui path (supposing you've got all your xhtml files stored there) to the same path, but adding the xhtml suffix.
public class UrlPrettyfierFilter implements Filter {
private static final String JSF_VIEW_ROOT_PATH = "/ui";
private static final String JSF_VIEW_SUFFIX = ".xhtml";
@Override
public void destroy() {
}
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
throws IOException, ServletException {
HttpServletRequest httpServletRequest = ((HttpServletRequest) request);
String requestURI = httpServletRequest.getRequestURI();
//Only process the paths starting with /ui, so as other requests get unprocessed.
//You can register the filter itself for /ui/* only, too
if (requestURI.startsWith(JSF_VIEW_ROOT_PATH)
&& !requestURI.contains(JSF_VIEW_SUFFIX)) {
request.getRequestDispatcher(requestURI.concat(JSF_VIEW_SUFFIX))
.forward(request,response);
} else {
chain.doFilter(httpServletRequest, response);
}
}
@Override
public void init(FilterConfig arg0) throws ServletException {
}
}
You have to create a variable of the type of the class, and set it equal to a new instance of the object first.
GradeBook myGradeBook = new GradeBook();
Then call the method on the obect you just created.
myGradeBook.[method you want called]
The main thread here seems to be a corrupted user account profile for the account that is used to start the DB engine. This is the account that was specified for the "SQL Server Database" engine during installation. In the setup event log, it's also indicated by the following entry:
SQLSVCACCOUNT: NT AUTHORITY\SYSTEM
According to the link provided by @royki:
The root cause of this issue, in most cases, is that the profile of the user being used for the service account (in my case it was local system) is corrupted.
This would explain why other respondents had success after changing to different accounts:
To fix the user profile that's causing the error, follow the steps listed KB947215.
The main steps from KB947215 are summarized as follows:-
regedit
HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\ProfileList
Navigate to the SID for the corrupted profile
To find the SID, click on each SID GUID, review the value for the ProfileImagePath
value, and see if it's the correct account. For system accounts, there's a different way to know the SID for the account that failed:
The main system account SIDs of interest are:
SID Name Also Known As
S-1-5-18 Local System NT AUTHORITY\SYSTEM
S-1-5-19 LocalService NT AUTHORITY\LOCAL SERVICE
S-1-5-20 NetworkService NT AUTHORITY\NETWORK SERVICE
For information on additional SIDs, see Well-known security identifiers in Windows operating systems.
RefCount
and State
to be 0
.os.path.dirname
is what you are looking for -
os.path.dirname(r"C:\folder1\folder2\filename.xml")
Make sure you prepend r
to the string so that its considered as a raw string.
Demo -
In [46]: os.path.dirname(r"C:\folder1\folder2\filename.xml")
Out[46]: 'C:\\folder1\\folder2'
If you just want folder2
, you can use os.path.basename
with the above, Example -
os.path.basename(os.path.dirname(r"C:\folder1\folder2\filename.xml"))
Demo -
In [48]: os.path.basename(os.path.dirname(r"C:\folder1\folder2\filename.xml"))
Out[48]: 'folder2'
Combining two of the previous results, we have:
int(round(some_float))
This converts a float to an integer fairly dependably.
function dropdownlist(listindex)
{
document.getElementById("ddlCity").options.length = 0;
switch (listindex)
{
case "Karnataka":
document.getElementById("ddlCity").options[0] = new Option("--select--", "");
document.getElementById("ddlCity").options[1] = new Option("Dharawad", "Dharawad");
document.getElementById("ddlCity").options[2] = new Option("Haveri", "Haveri");
document.getElementById("ddlCity").options[3] = new Option("Belgum", "Belgum");
document.getElementById("ddlCity").options[4] = new Option("Bijapur", "Bijapur");
break;
case "Tamilnadu":
document.getElementById("ddlCity").options[0] = new Option("--select--", "");
document.getElementById("ddlCity").options[1] = new Option("dgdf", "dgdf");
document.getElementById("ddlCity").options[2] = new Option("gffd", "gffd");
break;
}
}
* State: --Select-- Karnataka Tamilnadu Andra pradesh Telngana
<div>
<p>
<label id="lblCt">
<span class="red">*</span>
City:</label>
<select id="ddlCity">
<!-- <option>--Select--</option>
<option value="1">Dharawad</option>
<option value="2">Belgum</option>
<option value="3">Bagalkot</option>
<option value="4">Haveri</option>
<option>Hydrabadh</option>
<option>Vijat vada</option>-->
</select>
<label id="lblCity"></label>
</p>
</div>
Try the line below to convert editText to integer.
int intVal = Integer.parseInt(mEtValue.getText().toString());
If you have another instance of Android Studio running, then kindly close it and then build the app. This worked in my case
There is a jquery plugin available on github that probably just do what you want. It is called jquery-quickfit. It uses Jquery to provide a quick and dirty approach to fitting text into its surrounding container.
HTML:
<div id="quickfit">Text to fit*</div>
Javascript:
<script src=".../jquery.min.js" type="text/javascript" />
<script src="../script/jquery.quickfit.js" type="text/javascript" />
<script type="text/javascript">
$(function() {
$('#quickfit').quickfit();
});
</script>
More information: https://github.com/chunksnbits/jquery-quickfit
You can also define these chars as list of string. Then you can check if the characters is valid for accepted characters with list.Contains(x) method.
As of Android Studio 1.1, we've got official (experimental) support for writing Unit Tests (Roboelectric works as well).
Source: https://sites.google.com/a/android.com/tools/tech-docs/unit-testing-support
I'd use absolute positioning:
#play_button {
position:absolute;
transition: .5s ease;
left: 202px;
top: 198px;
}
Haven't tried this yet, and it is uses a lot of information based on some of the other answers. The complexity here is to avoid a server side data store call per request for user information. Most of the other solutions require a db lookup per request to a user session store. That is fine in certain scenarios but this was created in an attempt to avoid such calls and make whatever required server side state to be very small. You will end up recreating a server side session, however small to provide all the force invalidation features. But if you want to do it here is the gist:
Goals:
The Solution:
This requires you to maintain a blacklist(state) on the server, assuming the user table contains banned user information. The invalid sessions blacklist - is a list of user ids. This blacklist is only checked during a refresh token request. Entries are required to live on it as long as the refresh token TTL. Once the refresh token expires the user would be required to log back in.
Cons:
Pros:
With this solution an in memory data store like reddis isn't needed, at least not for user information as you are as the server is only making a db call every 15 or so minutes. If using reddis, storing a valid/invalid session list in there would be a very fast and simpler solution. No need for a refresh token. Each auth token would have a session id and device id, they could be stored in a reddis table on creation and invalidated when appropriate. Then they would be checked on every request and rejected when invalid.
Add LinearLayout
before EditText
in your XML.
<LinearLayout
android:focusable="true"
android:focusableInTouchMode="true"
android:clickable="true"
android:layout_width="0px"
android:layout_height="0px" />
Or you can do this same thing by adding these lines to view before your 'EditText'.
<Button
android:id="@+id/btnSearch"
android:layout_width="50dp"
android:layout_height="50dp"
android:focusable="true"
android:focusableInTouchMode="true"
android:gravity="center"
android:text="Quick Search"
android:textColor="#fff"
android:textSize="13sp"
android:textStyle="bold" />
<EditText
android:id="@+id/edtSearch"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_centerVertical="true"
android:layout_marginRight="5dp"
android:gravity="left"
android:hint="Name"
android:maxLines="1"
android:singleLine="true"
android:textColorHint="@color/blue"
android:textSize="13sp"
android:textStyle="bold" />
I'll sometimes do this:
def draw_menu(options, selected_index):
for i in range(len(options)):
if i == selected_index:
print " [*] %s" % options[i]
else:
print " [ ] %s" % options[i]
Though I tend to avoid this if it means I'll be saying options[i]
more than a couple of times.
First you should find where Cuda installed.
If it's a default installation like here the location should be:
for ubuntu:
/usr/local/cuda
in this folder you should have a file
version.txt
open this file with any text editor or run:
cat version.txt
from the folder
OR
cat /usr/local/cuda/version.txt
Variables names are only locally meaningful.
Once you hit
return s1,s2,s3,s4
at the end of the method, Python constructs a tuple with the values of s1, s2, s3 and s4 as its four members at index 0, 1, 2 and 3 - NOT a dictionary of variable names to values, NOT an object with variable names and their values, etc.
If you want the variable names to be meaningful after you hit return
in the method, you must create an object or dictionary.
Another possible scenario I've seen - the exact same request is being sent again just after few milliseconds (most likely due to a bug in the client side).
In that case you'll also see that the status of the first request is "canceled" and that the latency is only several milliseconds.
I had simillar issue with maven tests on x86 linux which i was using in terminal. I was logging in to linux by ssh. I started my java selenium tests by
mvn -DargLine="-Dbaseurl=http://http://127.0.0.1:8080/web/" install
Excepting my app, after running these tests I received error in logs:
unknown error: Chrome failed to start: exited abnormally
I was running these tests as root user. Before this error i received that ChromeDriver is nor present. I moved forward with this by installing ChromeDriver binary and adding it to PATH. But then i had to install google-chrome browser - ChromeDriver alone isn't enough to run tests. So the mistake is problem maybe with screen buffer in terminal window, but You can install Xvfb which is virtual screen buffer. What is important, that you should run your tests not as root, because you may receive another Chrome Browser error. So no as root i run:
export DISPLAY=:99
Xvfb :99 -ac -screen 0 1280x1024x24 &
What is important here, that in my case the number related to DISPLAY ought to be same as Xvfb :NN parameter. 99 in that case. I had another problem because i ran Xvfb with another DISPLAY value and I wanted it to stop. In order to restart Xvfb:
ps -aux | grep Xvfb
kill -9 PID
sudo rm /tmp/.X11-unix/X99
So find a process PID with grep. Kill Xvfb process. And then there is lock in /tmp/.X11-unix/XNN , so delete this lock and you can start server again. If You run not as root, set simillar displays, install google-chrome then with maven you can start selenium tests. My tests went fine with these rules and operations.
Best way to locate anchor elements is to use link=Re-Call
:
selenium.click("link=Re-Call");
It will work..
A[A==NDV]=numpy.nan
A==NDV will produce a boolean array that can be used as an index for A
In addition to the other answers, a struct can (but usually doesn't) have virtual functions, in which case the size of the struct will also include the space for the vtbl.
As of Chrome 46, a simple onclick=window.close()
does the trick. This only closes the tab, and not the entire browser, if multiple tabs are opened.
In PHP, Encryption and Decryption of a string is possible using one of the Cryptography Extensions called OpenSSL function for encrypt and decrypt.
openssl_encrypt() Function: The openssl_encrypt() function is used to encrypt the data.
Syntax is as follows :
string openssl_encrypt( string $data, string $method, string $key, $options = 0, string $iv, string $tag= NULL, string $aad, int $tag_length = 16 )
Parameters are as follows :
$data: It holds the string or data which need to be encrypted.
$method: The cipher method is adopted using openssl_get_cipher_methods() function.
$key: It holds the encryption key.
$options: It holds the bitwise disjunction of the flags OPENSSL_RAW_DATA and OPENSSL_ZERO_PADDING.
$iv: It holds the initialization vector which is not NULL.
$tag: It holds the authentication tag which is passed by reference when using AEAD cipher mode (GCM or CCM).
$aad: It holds the additional authentication data.
$tag_length: It holds the length of the authentication tag. The length of authentication tag lies between 4 to 16 for GCM mode.
Return Value: It returns the encrypted string on success or FALSE on failure.
openssl_decrypt() Function The openssl_decrypt() function is used to decrypt the data.
Syntax is as follows :
string openssl_decrypt( string $data, string $method, string $key, int $options = 0, string $iv, string $tag, string $aad)
Parameters are as follows :
$data: It holds the string or data which need to be encrypted.
$method: The cipher method is adopted using openssl_get_cipher_methods() function.
$key: It holds the encryption key.
$options: It holds the bitwise disjunction of the flags OPENSSL_RAW_DATA and OPENSSL_ZERO_PADDING.
$iv: It holds the initialization vector which is not NULL.
$tag: It holds the authentication tag using AEAD cipher mode (GCM or CCM). When authentication fails openssl_decrypt() returns FALSE.
$aad: It holds the additional authentication data.
Return Value: It returns the decrypted string on success or FALSE on failure.
Approach: First declare a string and store it into variable and use openssl_encrypt() function to encrypt the given string and use openssl_decrypt() function to descrypt the given string.
You can find the examples at : https://www.geeksforgeeks.org/how-to-encrypt-and-decrypt-a-php-string/
Add a WHERE
clause
UPDATE dbo.TestStudents
SET LASTNAME = CASE
WHEN LASTNAME = 'AAA' THEN 'BBB'
WHEN LASTNAME = 'CCC' THEN 'DDD'
WHEN LASTNAME = 'EEE' THEN 'FFF'
ELSE LASTNAME
END
WHERE LASTNAME IN ('AAA', 'CCC', 'EEE')
If all you're trying to do is to get attribute1 in your global namespace, version 3 seems just fine. Why is it overkill prefix ?
In version 2, instead of
from module import attribute1
you can do
attribute1 = module.attribute1
No. That will always be a syntax error in Python 3. Consider using 2to3
to translate your code to Python 3
It appears that SQL Server 2008 R2 can be downloaded with or without the management tools. I honestly have NO IDEA why someone would not want the management tools. But either way, the options are here:
http://www.microsoft.com/sqlserver/en/us/editions/express.aspx
and the one for 64 bit WITH the management tools (management studio) is here:
http://www.microsoft.com/sqlserver/en/us/editions/express.aspx
From the first link I presented, the 3rd and 4th include the management studio for 32 and 64 bit respectively.
I have created a module for anuglar2 autocomplete In this module you can use array, or url npm link : ang2-autocomplete
For mysql 8.0.7, Go to your mysql directory, and then use:
sudo bin/mysql_secure_installation
to configure the password option.
wait()
is a method of Object
class.
sleep()
is a method of Thread
class.
sleep()
allows the thread to go to sleep
state for x milliseconds.
When a thread goes into sleep state it doesn’t release the lock
.
wait()
allows thread to release the lock and goes to suspended state
.
This thread will be active when a notify()
or notifAll()
method is
called for the same object.
As this question is been 7 years before, in the latest version which I am using is numpy version 1.13, and python3, I am doing the same thing with adding a row to a matrix, remember to put a double bracket to the second argument, otherwise, it will raise dimension error.
In here I am adding on matrix A
1 2 3
4 5 6
with a row
7 8 9
same usage in np.r_
A= [[1, 2, 3], [4, 5, 6]]
np.append(A, [[7, 8, 9]], axis=0)
>> array([[1, 2, 3],
[4, 5, 6],
[7, 8, 9]])
#or
np.r_[A,[[7,8,9]]]
Just to someone's intersted, if you would like to add a column,
array = np.c_[A,np.zeros(#A's row size)]
following what we did before on matrix A, adding a column to it
np.c_[A, [2,8]]
>> array([[1, 2, 3, 2],
[4, 5, 6, 8]])
I recently wrote a post about how I've been doing it at Udacity for the last couple years. This method has meant we've been able to update Bootstrap whenever we wanted to without having merge conflicts, thrown out work, etc. etc.
The post goes more in depth with examples, but the basic idea is:
This does mean using LESS, and compiling it down to CSS before shipping it to the client (client-side LESS if finicky, and I generally avoid it) but it is EXTREMELY good for maintainability/upgradability, and getting LESS compilation is really really easy. The linked github code has an example using grunt, but there are many ways to achieve this -- even GUIs if that's your thing.
Using this solution, your example problem would look like:
When it comes time to upgrade your bootstrap, you just swap out the pristine bootstrap copy and everything will still work (if bootstrap makes breaking changes, you'll need to update your overrides, but you'd have to do that anyway)
Blog post with walk-through is here.
Code example on github is here.
Animuson gives a decent way to do it, but no help on understanding it. I kept looking and came across a forum thread with this commands:
Echo Off
IF Not EXIST n:\dbfs\doekasp.txt GOTO DoNothing
copy n:\dbfs\doekasp.txt n:\history\doekasp.txt
Rem rename command is done twice (2) to allow for 1 or 2 digit hour,
Rem If before 10am (1digit) hour Rename starting at location (0) for (2) chars,
Rem will error out, as location (0) will have a space
Rem and space is invalid character for file name,
Rem so second remame will be used.
Rem
Rem if equal 10am or later (2 digit hour) then first remame will work and second will not
Rem as doekasp.txt will not be found (remamed)
ren n:\history\doekasp.txt doekasp-%date:~4,2%-%date:~7,2%-%date:~10,4%_@_%time:~0,2%h%time:~3,2%m%time:~6,2%s%.txt
ren n:\history\doekasp.txt doekasp-%date:~4,2%-%date:~7,2%-%date:~10,4%_@_%time:~1,1%h%time:~3,2%m%time:~6,2%s%.txt
I always name year first YYYYMMDD, but wanted to add time. Here you will see that he has given a reason why 0,2 will not work and 1,1 will, because (space) is an invalid character. This opened my eyes to the issue. Also, by default you're in 24hr mode.
I ended up with:
ren Logs.txt Logs-%date:~10,4%%date:~7,2%%date:~4,2%_%time:~0,2%%time:~3,2%.txt
ren Logs.txt Logs-%date:~10,4%%date:~7,2%%date:~4,2%_%time:~1,1%%time:~3,2%.txt
Output:
Logs-20121707_1019
As this is only tagged sql
(which does not indicate any specific DBMS), here is a solution for Postgres:
select d::date
from generate_series(date '1990-01-01', date '1990-01-01' + interval '100' year, interval '1' day) as t(d);
If you need that a lot, it's more efficient to store that in an table (which can e.g. be indexed):
create table calendar
as
select d::date as the_date
from generate_series(date '1990-01-01', date '1990-01-01' + interval '100' year, interval '1' day) as t(d);
This is a bit late for those coming in, but check your proguard rules! I wasted a lot of time on this. Your proguard rules could be changing the names to important firebase files. This really only proves a problem in production and instant run :)
proguard-rules.pro
-keep class com.google.firebase.** { *; }
-keep class com.firebase.** { *; }
-keep class org.apache.** { *; }
-keepnames class com.fasterxml.jackson.** { *; }
-keepnames class javax.servlet.** { *; }
-keepnames class org.ietf.jgss.** { *; }
-dontwarn org.apache.**
-dontwarn org.w3c.dom.**
ShortcutBadger is a library that adds an abstraction layer over the device brand and current launcher and offers a great result. Works with LG, Sony, Samsung, HTC and other custom Launchers.
It even has a way to display Badge Count in Pure Android devices desktop.
Updating the Badge Count in the application icon is as easy as calling:
int badgeCount = 1;
ShortcutBadger.applyCount(context, badgeCount);
It includes a demo application that allows you to test its behavior.
Quick alternative
import timeit
start = timeit.default_timer()
#Your statements here
stop = timeit.default_timer()
print('Time: ', stop - start)
String file = "";
try {
InputStream is = new FileInputStream(filename);
String UTF8 = "utf8";
int BUFFER_SIZE = 8192;
BufferedReader br = new BufferedReader(new InputStreamReader(is,
UTF8), BUFFER_SIZE);
String str;
while ((str = br.readLine()) != null) {
file += str;
}
} catch (Exception e) {
}
Try this,.. :-)
I also use Cygwin on Windows, but with gVim (as opposed to the terminal-based Vim).
To make this work, I have done the following:
git_editor.bat
) which contains the following:
"C:/Program Files/Vim/vim72/gvim.exe" --nofork "%*"
git_editor.bat
on in my PATH
.GIT_EDITOR=git_editor.bat
With this done, git commit
, etc. will correctly invoke the gVim executable.
NOTE 1: The --nofork
option to gVim ensures that it blocks until the commit message has been written.
NOTE 2: The quotes around the path to gVim is required if you have spaces in the path.
NOTE 3: The quotes around "%*" are needed just in case Git passes a file path with spaces.
webm format is the best solution for Chrome > 29, but it is not supported in Firefox IE and Safari, the best solution is using Flash (wmode="transparent"). but you have to forget "ios".
There's a similar post here: http://techpad.co.uk/content.php?sid=137 which explains how to do it.
function file_get_contents_proxy($url,$proxy){
// Create context stream
$context_array = array('http'=>array('proxy'=>$proxy,'request_fulluri'=>true));
$context = stream_context_create($context_array);
// Use context stream with file_get_contents
$data = file_get_contents($url,false,$context);
// Return data via proxy
return $data;
}
$output = preg_replace('/\s+/', ' ',$input);
\s is shorthand for [ \t\n\r]
. Multiple spaces will be replaced with single space.
I just found some issues on FAB and I want to enhance another answer.
So, the issue will come once you set the ripple color (FAB color on pressed) programmatically through setRippleColor
. But, we still have an alternative way to set it, i.e. by calling:
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
ColorStateList rippleColor = ContextCompat.getColorStateList(context, R.color.fab_ripple_color);
fab.setBackgroundTintList(rippleColor);
Your project need to has this structure:
/res/color/fab_ripple_color.xml
And the code from fab_ripple_color.xml
is:
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_pressed="true" android:color="@color/fab_color_pressed" />
<item android:state_focused="true" android:color="@color/fab_color_pressed" />
<item android:color="@color/fab_color_normal"/>
</selector>
Finally, alter your FAB slightly:
<android.support.design.widget.FloatingActionButton
android:id="@+id/fab"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/ic_action_add"
android:layout_alignParentBottom="true"
android:layout_alignParentRight="true"
app:fabSize="normal"
app:borderWidth="0dp"
app:elevation="6dp"
app:pressedTranslationZ="12dp"
app:rippleColor="@android:color/transparent"/> <!-- set to transparent color -->
For API level 21 and higher, set margin right and bottom to 24dp:
...
android:layout_marginRight="24dp"
android:layout_marginBottom="24dp" />
As you can see on my FAB xml code above, I set:
...
android:layout_alignParentBottom="true"
android:layout_alignParentRight="true"
app:elevation="6dp"
app:pressedTranslationZ="12dp"
...
By setting these attributes, you don't need to set layout_marginTop
and layout_marginRight
again (only on pre-Lollipop). Android will place it automatically on the right corned side of the screen, which the same as normal FAB in Android Lollipop.
android:layout_alignParentBottom="true"
android:layout_alignParentRight="true"
Or, you can use this in CoordinatorLayout
:
android:layout_gravity="end|bottom"
elevation
and 12dp pressedTranslationZ
, according to this guide from Google.if discount.nil? || discount == 0
[do something]
end
Inside of your <head></head>
tags add...
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script>
$(document).ready(function(){
$('input[type=radio]').change(function() {
$('input[type=radio]').each(function(index) {
$(this).closest('tr').removeClass('selected');
});
$(this).closest('tr').addClass('selected');
});
});
</script>
EDIT: The placement inside of <head></head>
is not the only option...this could just as easily be placed RIGHT before the closing </body>
tag. I generally try and place my JavaScript inside of head
for placement reasons, but it can in some cases slow down page rendering so some will recommend the latter approach (before closing body
).
This is what I did:
EF:
using (var context = new SomeDBContext())
{
foreach (var item in model.ShopItems) // ShopItems is a posted list with values
{
var feature = context.Shop
.Where(h => h.ShopID == 123 && h.Type == item.Type).ToList();
feature.ForEach(a => a.SortOrder = item.SortOrder);
}
context.SaveChanges();
}
Hope helps someone.
The CBO builds a decision tree, estimating the costs of each possible execution path available per query. The costs are set by the CPU_cost or I/O_cost parameter set on the instance. And the CBO estimates the costs, as best it can with the existing statistics of the tables and indexes that the query will use. You should not tune your query based on cost alone. Cost allows you to understand WHY the optimizer is doing what it does. Without cost you could figure out why the optimizer chose the plan it did. Lower cost does not mean a faster query. There are cases where this is true and there will be cases where this is wrong. Cost is based on your table stats and if they are wrong the cost is going to be wrong.
When tuning your query, you should take a look at the cardinality and the number of rows of each step. Do they make sense? Is the cardinality the optimizer is assuming correct? Is the rows being return reasonable. If the information present is wrong then its very likely the optimizer doesn't have the proper information it needs to make the right decision. This could be due to stale or missing statistics on the table and index as well as cpu-stats. Its best to have stats updated when tuning a query to get the most out of the optimizer. Knowing your schema is also of great help when tuning. Knowing when the optimizer chose a really bad decision and pointing it in the correct path with a small hint can save a load of time.
Find the file called: php.ini
on your server and follow below steps
With apache2 and php5 installed you need to make three changes in the php.ini file. First open the file for editing, e.g.:
sudo gedit /etc/php5/apache2/php.ini
OR
sudo gedit /etc/php/7.0/apache2/php.ini
Next, search for the post_max_size
entry, and enter a larger number than the size of your database (15M in this case), for example:
post_max_size = 25M
Next edit the entry for memory_limit
and give it a larger value than the one given to post_max_size
.
Then ensure the value of upload_max_filesize
is smaller than post_max_size
.
The order from biggest to smallest should be:
memory_limit
post_max_size
upload_max_filesize
After saving the file, restart apache (e.g. sudo /etc/init.d/apache2 restart
) and you are set.
Don't forget to Restart Apache Services
for changes to be applied.
For further details, click here.
You can bind function as follows, instead of init on load
$("div").css("height", $(window).height());
$(?window?).bind("resize",function() {
$("div").css("height", $(window).height());
});????
I am not going to use this pattern in my own code since I'm not a big fan of using global variables. However, in a pinch it will work.
User is a promisified Mongoose model.
var globalVar = '';
User.findAsync({}).then(function(users){
globalVar = users;
}).then(function(){
console.log(globalVar);
});
#include <opencv2/imgproc/imgproc.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <iostream>
#include <iomanip>
using namespace cv;
using namespace std;
int main(int argc, char** argv)
{
double data[4] = {-0.0000000077898273846583732, -0.03749374753019832, -0.0374787251930463, -0.000000000077893623846343843};
Mat src = Mat(1, 4, CV_64F, &data);
for(int i=0; i<4; i++)
cout << setprecision(3) << src.at<double>(0,i) << endl;
return 0;
}
request.getRequestDispatcher(“url”) means the dispatch is relative to the current HTTP request.Means this is for chaining two servlets with in the same web application Example
RequestDispatcher reqDispObj = request.getRequestDispatcher("/home.jsp");
getServletContext().getRequestDispatcher(“url”) means the dispatch is relative to the root of the ServletContext.Means this is for chaining two web applications with in the same server/two different servers
Example
RequestDispatcher reqDispObj = getServletContext().getRequestDispatcher("/ContextRoot/home.jsp");
SQL stands for Structured Query Language, and it is a programming language designed for querying data from a database. MySQL is a relational database management system, which is a completely different thing.
MySQL is an open-source platform that uses SQL, just like MSSQL, which is Microsoft's product (not open-source) that uses SQL for database management.
So the question is how can I check if my array already has a "horse" included so that I don't fill it with the same horse?
While the answers are concerned with looking through the array to see if a particular string or object exists, that's really going about it wrong, because, as the array gets larger, the search will take longer.
Instead, use either a Hash, or a Set. Both only allow a single instance of a particular element. Set will behave closer to an Array but only allows a single instance. This is a more preemptive approach which avoids duplication because of the nature of the container.
hash = {}
hash['a'] = nil
hash['b'] = nil
hash # => {"a"=>nil, "b"=>nil}
hash['a'] = nil
hash # => {"a"=>nil, "b"=>nil}
require 'set'
ary = [].to_set
ary << 'a'
ary << 'b'
ary # => #<Set: {"a", "b"}>
ary << 'a'
ary # => #<Set: {"a", "b"}>
Hash uses name/value pairs, which means the values won't be of any real use, but there seems to be a little bit of extra speed using a Hash, based on some tests.
require 'benchmark'
require 'set'
ALPHABET = ('a' .. 'z').to_a
N = 100_000
Benchmark.bm(5) do |x|
x.report('Hash') {
N.times {
h = {}
ALPHABET.each { |i|
h[i] = nil
}
}
}
x.report('Array') {
N.times {
a = Set.new
ALPHABET.each { |i|
a << i
}
}
}
end
Which outputs:
user system total real
Hash 8.140000 0.130000 8.270000 ( 8.279462)
Array 10.680000 0.120000 10.800000 ( 10.813385)
Setting the slice to nil
is the best way to clear a slice. nil
slices in go are perfectly well behaved and setting the slice to nil
will release the underlying memory to the garbage collector.
package main
import (
"fmt"
)
func dump(letters []string) {
fmt.Println("letters = ", letters)
fmt.Println(cap(letters))
fmt.Println(len(letters))
for i := range letters {
fmt.Println(i, letters[i])
}
}
func main() {
letters := []string{"a", "b", "c", "d"}
dump(letters)
// clear the slice
letters = nil
dump(letters)
// add stuff back to it
letters = append(letters, "e")
dump(letters)
}
Prints
letters = [a b c d]
4
4
0 a
1 b
2 c
3 d
letters = []
0
0
letters = [e]
1
1
0 e
Note that slices can easily be aliased so that two slices point to the same underlying memory. The setting to nil
will remove that aliasing.
This method changes the capacity to zero though.
Precision 4, scale 2: 99.99
Precision 10, scale 0: 9999999999
Precision 8, scale 3: 99999.999
Precision 5, scale -3: 99999000
finally I got the solution:
Only put this line
@RequestMapping(value = "/YOUR_URL_Name",method = RequestMethod.POST,produces = "application/json; charset=utf-8")
this will definitely help.
The user-agent
should be specified as a field in the header.
Here is a list of HTTP header fields, and you'd probably be interested in request-specific fields, which includes User-Agent
.
The simplest way to do what you want is to create a dictionary and specify your headers directly, like so:
import requests
url = 'SOME URL'
headers = {
'User-Agent': 'My User Agent 1.0',
'From': '[email protected]' # This is another valid field
}
response = requests.get(url, headers=headers)
Older versions of requests
clobbered default headers, so you'd want to do the following to preserve default headers and then add your own to them.
import requests
url = 'SOME URL'
# Get a copy of the default headers that requests would use
headers = requests.utils.default_headers()
# Update the headers with your custom ones
# You don't have to worry about case-sensitivity with
# the dictionary keys, because default_headers uses a custom
# CaseInsensitiveDict implementation within requests' source code.
headers.update(
{
'User-Agent': 'My User Agent 1.0',
}
)
response = requests.get(url, headers=headers)
$url="http://www.google.co.in/intl/en_com/images/srpr/logo1w.png";
$contents=file_get_contents($url);
$save_path="/path/to/the/dir/and/image.jpg";
file_put_contents($save_path,$contents);
you must have allow_url_fopen
set to on
This can be done by enabling short_open_tag in php.ini:
short_open_tag = on
If you don't have access to the php.ini you can try to enable them trough the .htaccess file but it's possible the hosting company disabled this if you are on shared hosting:
php_value short_open_tag 1
For the people thinking that short_open_tags are bad practice as of php 5.4 the <?= ... ?>
shorttag will supported everywhere, regardless of the settings so there is no reason not to use them if you can control the settings on the server. Also said in this link: short_open_tag
Another simple example:
Search: style="(.+?)"
Replace: css={css`$1`}
Useful for converting HTML to JSX with emotion/css!
Since this question draws so many votes and kind of becomes an FAQ, I guess it would be better to write a separate answer to mention one significant difference between C++03 and C++11 regarding the impact of std::vector
's insertion operation on the validity of iterators and references with respect to reserve()
and capacity()
, which the most upvoted answer failed to notice.
C++ 03:
Reallocation invalidates all the references, pointers, and iterators referring to the elements in the sequence. It is guaranteed that no reallocation takes place during insertions that happen after a call to reserve() until the time when an insertion would make the size of the vector greater than the size specified in the most recent call to reserve().
C++11:
Reallocation invalidates all the references, pointers, and iterators referring to the elements in the sequence. It is guaranteed that no reallocation takes place during insertions that happen after a call to reserve() until the time when an insertion would make the size of the vector greater than the value of capacity().
So in C++03, it is not "unless the new container size is greater than the previous capacity (in which case all iterators and references are invalidated)
" as mentioned in the other answer, instead, it should be "greater than the size specified in the most recent call to reserve()
". This is one thing that C++03 differs from C++11. In C++03, once an insert()
causes the size of the vector to reach the value specified in the previous reserve()
call (which could well be smaller than the current capacity()
since a reserve()
could result a bigger capacity()
than asked for), any subsequent insert()
could cause reallocation and invalidate all the iterators and references. In C++11, this won't happen and you can always trust capacity()
to know with certainty that the next reallocation won't take place before the size overpasses capacity()
.
In conclusion, if you are working with a C++03 vector and you want to make sure a reallocation won't happen when you perform insertion, it's the value of the argument you previously passed to reserve()
that you should check the size against, not the return value of a call to capacity()
, otherwise you may get yourself surprised at a "premature" reallocation.
As others already noted, in one case you are attempting to return cString
(which is a char *
value in this context - a pointer) from a function that is declared to return a char
(which is an integer). In another case you do the reverse: you are assigning a char
return value to a char *
pointer. This is what triggers the warnings. You certainly need to declare your return values as char *
, not as char
.
Note BTW that these assignments are in fact constraint violations from the language point of view (i.e. they are "errors"), since it is illegal to mix pointers and integers in C like that (aside from integral constant zero). Your compiler is simply too forgiving in this regard and reports these violations as mere "warnings".
What I also wanted to note is that in several answers you might notice the relatively strange suggestion to return void
from your functions, since you are modifying the string in-place. While it will certainly work (since you indeed are modifying the string in-place), there's nothing really wrong with returning the same value from the function. In fact, it is a rather standard practice in C language where applicable (take a look at the standard functions like strcpy
and others), since it enables "chaining" of function calls if you choose to use it, and costs virtually nothing if you don't use "chaining".
That said, the assignments in your implementation of compareString
look complete superfluous to me (even though they won't break anything). I'd either get rid of them
int compareString(char cString1[], char cString2[]) {
// To lowercase
strToLower(cString1);
strToLower(cString2);
// Do regular strcmp
return strcmp(cString1, cString2);
}
or use "chaining" and do
int compareString(char cString1[], char cString2[]) {
return strcmp(strToLower(cString1), strToLower(cString2));
}
(this is when your char *
return would come handy). Just keep in mind that such "chained" function calls are sometimes difficult to debug with a step-by-step debugger.
As an additional, unrealted note, I'd say that implementing a string comparison function in such a destructive fashion (it modifies the input strings) might not be the best idea. A non-destructive function would be of a much greater value in my opinion. Instead of performing as explicit conversion of the input strings to a lower case, it is usually a better idea to implement a custom char-by-char case-insensitive string comparison function and use it instead of calling the standard strcmp
.
If you have a budget for your IDE, you should give Wingware Professional a try, see wingware.com .
That task should be done by the next layer up in your software stack. SQL is a data repository, not a presentation system
You can do it with
CONVERT(VARCHAR(10), fmdate(), 101)
But you shouldn't
var input = document.getElementById("customx");
if (input && input.value) {
alert(1);
}
else {
alert (0);
}
You will have to change some of your data types but the basics of what you just posted could be converted to something similar to this given the data types I used may not be accurate.
Dim DateToday As String: DateToday = Format(Date, "yyyy/MM/dd")
Dim Computers As New Collection
Dim disabledList As New Collection
Dim compArray(1 To 1) As String
'Assign data to first item in array
compArray(1) = "asdf"
'Format = Item, Key
Computers.Add "ErrorState", "Computer Name"
'Prints "ErrorState"
Debug.Print Computers("Computer Name")
Collections cannot be sorted so if you need to sort data you will probably want to use an array.
Here is a link to the outlook developer reference. http://msdn.microsoft.com/en-us/library/office/ff866465%28v=office.14%29.aspx
Another great site to help you get started is http://www.cpearson.com/Excel/Topic.aspx
Moving everything over to VBA from VB.Net is not going to be simple since not all the data types are the same and you do not have the .Net framework. If you get stuck just post the code you're stuck converting and you will surely get some help!
Edit:
Sub ArrayExample()
Dim subject As String
Dim TestArray() As String
Dim counter As Long
subject = "Example"
counter = Len(subject)
ReDim TestArray(1 To counter) As String
For counter = 1 To Len(subject)
TestArray(counter) = Right(Left(subject, counter), 1)
Next
End Sub
Here's an example program that will send myfile.mp3 by streaming it from disk (that is, it doesn't read the whole file into memory before sending the file). The server listens on port 2000.
[Update] As mentioned by @Aftershock in the comments, util.pump
is gone and was replaced with a method on the Stream prototype called pipe
; the code below reflects this.
var http = require('http'),
fileSystem = require('fs'),
path = require('path');
http.createServer(function(request, response) {
var filePath = path.join(__dirname, 'myfile.mp3');
var stat = fileSystem.statSync(filePath);
response.writeHead(200, {
'Content-Type': 'audio/mpeg',
'Content-Length': stat.size
});
var readStream = fileSystem.createReadStream(filePath);
// We replaced all the event handlers with a simple call to readStream.pipe()
readStream.pipe(response);
})
.listen(2000);
Taken from http://elegantcode.com/2011/04/06/taking-baby-steps-with-node-js-pumping-data-between-streams/
using std::string;
string string_replace( string src, string const& target, string const& repl)
{
// handle error situations/trivial cases
if (target.length() == 0) {
// searching for a match to the empty string will result in
// an infinite loop
// it might make sense to throw an exception for this case
return src;
}
if (src.length() == 0) {
return src; // nothing to match against
}
size_t idx = 0;
for (;;) {
idx = src.find( target, idx);
if (idx == string::npos) break;
src.replace( idx, target.length(), repl);
idx += repl.length();
}
return src;
}
Since it's not a member of the string
class, it doesn't allow quite as nice a syntax as in your example, but the following will do the equivalent:
test = string_replace( string_replace( test, "abc", "hij"), "def", "klm")
For (much) more power and flexibility, use a dedicated spellchecking library like PyEnchant
. There's a tutorial, or you could just dive straight in:
>>> import enchant
>>> d = enchant.Dict("en_US")
>>> d.check("Hello")
True
>>> d.check("Helo")
False
>>> d.suggest("Helo")
['He lo', 'He-lo', 'Hello', 'Helot', 'Help', 'Halo', 'Hell', 'Held', 'Helm', 'Hero', "He'll"]
>>>
PyEnchant
comes with a few dictionaries (en_GB, en_US, de_DE, fr_FR), but can use any of the OpenOffice ones if you want more languages.
There appears to be a pluralisation library called inflect
, but I've no idea whether it's any good.
In my case the problem was due to having our main storyboard set as the Launch Screen, and I'd get a console error (no crash) at app start for every custom view controller referenced in the storyboard.
We'd covered from XIBs and launch images to storyboards and I hadn't yet gotten around to getting the launch screen working again. When I finally got around to creating a bare bones launch storyboard with no custom view controllers (which aren't allowed) these console errors stopped appearing.
Another way would be to use .Net parser for HttpRequest. To do that you need to use a bit of reflection and simple class for WorkerRequest.
First create class that derives from HttpWorkerRequest (for simplicity you can use SimpleWorkerRequest):
public class MyWorkerRequest : SimpleWorkerRequest
{
private readonly string _size;
private readonly Stream _data;
private string _contentType;
public MyWorkerRequest(Stream data, string size, string contentType)
: base("/app", @"c:\", "aa", "", null)
{
_size = size ?? data.Length.ToString(CultureInfo.InvariantCulture);
_data = data;
_contentType = contentType;
}
public override string GetKnownRequestHeader(int index)
{
switch (index)
{
case (int)HttpRequestHeader.ContentLength:
return _size;
case (int)HttpRequestHeader.ContentType:
return _contentType;
}
return base.GetKnownRequestHeader(index);
}
public override int ReadEntityBody(byte[] buffer, int offset, int size)
{
return _data.Read(buffer, offset, size);
}
public override int ReadEntityBody(byte[] buffer, int size)
{
return ReadEntityBody(buffer, 0, size);
}
}
Then wherever you have you message stream create and instance of this class. I'm doing it like that in WCF Service:
[WebInvoke(Method = "POST",
ResponseFormat = WebMessageFormat.Json,
BodyStyle = WebMessageBodyStyle.Bare)]
public string Upload(Stream data)
{
HttpWorkerRequest workerRequest =
new MyWorkerRequest(data,
WebOperationContext.Current.IncomingRequest.ContentLength.
ToString(CultureInfo.InvariantCulture),
WebOperationContext.Current.IncomingRequest.ContentType
);
And then create HttpRequest using activator and non public constructor
var r = (HttpRequest)Activator.CreateInstance(
typeof(HttpRequest),
BindingFlags.Instance | BindingFlags.NonPublic,
null,
new object[]
{
workerRequest,
new HttpContext(workerRequest)
},
null);
var runtimeField = typeof (HttpRuntime).GetField("_theRuntime", BindingFlags.Static | BindingFlags.NonPublic);
if (runtimeField == null)
{
return;
}
var runtime = (HttpRuntime) runtimeField.GetValue(null);
if (runtime == null)
{
return;
}
var codeGenDirField = typeof(HttpRuntime).GetField("_codegenDir", BindingFlags.Instance | BindingFlags.NonPublic);
if (codeGenDirField == null)
{
return;
}
codeGenDirField.SetValue(runtime, @"C:\MultipartTemp");
After that in r.Files
you will have files from your stream.
~(5.5) // => -6
~(-6) // => 5
~~5.5 // => 5 (same as Math.floor(5.5))
~~(-5.5) // => -5 (NOT the same as Math.floor(-5.5), which would give -6 )
For more info, see:
The GetHashCode
function is specifically designed to create a well distributed range of integers with a low probability of collision, so for this use case is likely to be the best you can do.
But, as I'm sure you're aware, hashing 128 bits of information into 32 bits of information throws away a lot of data, so there will almost certainly be collisions if you have a sufficiently large number of GUIDs.
You need this instead:
if(s.contains("+"))
contains()
method of String
class does not take regular expression as a parameter, it takes normal text.
EDIT:
String s = "ddjdjdj+kfkfkf";
if(s.contains("+"))
{
String parts[] = s.split("\\+");
System.out.print(parts[0]);
}
OUTPUT:
ddjdjdj
Thanks to Chris Jester-Young I managed to make it work!
I think the way I managed to do it will work only on really simple projects:
With apktool i got the android manifest and the resources files.
In Eclipse I create a new project with the same settings as the old one (checking all the information in the manifest file)
/!\ be sure you removed the old apk from the device an error will be thrown stating that the apk signature is not the same as the old one!
You can extract the scroll position using jQuery's .scrollTop()
method
$(window).scroll(function (event) {
var scroll = $(window).scrollTop();
// Do something
});
When you want to run an executable file from the Command prompt, (cmd.exe), or a batch file, it will:
%PATH%
environment variable for the executable file.If the file isn't found in either of those options you will need to either:
%PATH%
by apending it, (recommended only with extreme caution).You can see which locations are specified in %PATH%
from the Command prompt, Echo %Path%
.
Because of your reported error we can assume that Mobile.exe
is not in the current directory or in a location specified within the %Path%
variable, so you need to use 1.
, 2.
or 3.
.
Examples for 1.
C:\directory_path_without_spaces\My-App\Mobile.exe
or:
"C:\directory path with spaces\My-App\Mobile.exe"
Alternatively you may try:
Start C:\directory_path_without_spaces\My-App\Mobile.exe
or
Start "" "C:\directory path with spaces\My-App\Mobile.exe"
Where ""
is an empty title, (you can optionally add a string between those doublequotes).
Examples for 2.
CD /D C:\directory_path_without_spaces\My-App
Mobile.exe
or
CD /D "C:\directory path with spaces\My-App"
Mobile.exe
You could also use the /D
option with Start
to change the working directory for the executable to be run by the start command
Start /D C:\directory_path_without_spaces\My-App Mobile.exe
or
Start "" /D "C:\directory path with spaces\My-App" Mobile.exe
Since we are talking about having every element exactly once, a "set" makes more sense to me.
Example with classes and IEqualityComparer implemented:
public class Product
{
public int Id { get; set; }
public string Name { get; set; }
public Product(int x, string y)
{
Id = x;
Name = y;
}
}
public class ProductCompare : IEqualityComparer<Product>
{
public bool Equals(Product x, Product y)
{ //Check whether the compared objects reference the same data.
if (Object.ReferenceEquals(x, y)) return true;
//Check whether any of the compared objects is null.
if (Object.ReferenceEquals(x, null) || Object.ReferenceEquals(y, null))
return false;
//Check whether the products' properties are equal.
return x.Id == y.Id && x.Name == y.Name;
}
public int GetHashCode(Product product)
{
//Check whether the object is null
if (Object.ReferenceEquals(product, null)) return 0;
//Get hash code for the Name field if it is not null.
int hashProductName = product.Name == null ? 0 : product.Name.GetHashCode();
//Get hash code for the Code field.
int hashProductCode = product.Id.GetHashCode();
//Calculate the hash code for the product.
return hashProductName ^ hashProductCode;
}
}
Now
List<Product> originalList = new List<Product> {new Product(1, "ad"), new Product(1, "ad")};
var setList = new HashSet<Product>(originalList, new ProductCompare()).ToList();
setList
will have unique elements
I thought of this while dealing with .Except()
which returns a set-difference
The posts here help me a lot on my way to find a solution for the Uncaught TypeError: Cannot read property 'value' of undefined issue.
There are already here many answers which are correct, but what we don't have here is the combination for 2 answers that i think resolve this issue completely.
function myFunction(field, data){
if (typeof document.getElementsByName("+field+")[0] != 'undefined'){
document.getElementsByName("+field+")[0].value=data;
}
}
The difference is that you make a check(if a property is defined or not) and if the check is true then you can try to assign it a value.
As suggested by Adam Miller in the comments, I'll add another solution.
The MailMessage(String from, String to) constructor accepts a comma separated list of addresses. So if you happen to have already a comma (',') separated list, the usage is as simple as:
MailMessage Msg = new MailMessage(fromMail, addresses);
In this particular case, we can replace the ';' for ',' and still make use of the constructor.
MailMessage Msg = new MailMessage(fromMail, addresses.replace(";", ","));
Whether you prefer this or the accepted answer it's up to you. Arguably the loop makes the intent clearer, but this is shorter and not obscure. But should you already have a comma separated list, I think this is the way to go.
The problem by using stream().forEach(..)
with a call to add
or put
inside the forEach
(so you mutate the external myMap
or myList
instance) is that you can run easily into concurrency issues if someone turns the stream in parallel and the collection you are modifying is not thread safe.
One approach you can take is to first partition the entries in the original map. Once you have that, grab the corresponding list of entries and collect them in the appropriate map and list.
Map<Boolean, List<Map.Entry<K, V>>> partitions =
animalMap.entrySet()
.stream()
.collect(partitioningBy(e -> e.getValue() == null));
Map<K, V> myMap =
partitions.get(false)
.stream()
.collect(toMap(Map.Entry::getKey, Map.Entry::getValue));
List<K> myList =
partitions.get(true)
.stream()
.map(Map.Entry::getKey)
.collect(toList());
... or if you want to do it in one pass, implement a custom collector (assuming a Tuple2<E1, E2>
class exists, you can create your own), e.g:
public static <K,V> Collector<Map.Entry<K, V>, ?, Tuple2<Map<K, V>, List<K>>> customCollector() {
return Collector.of(
() -> new Tuple2<>(new HashMap<>(), new ArrayList<>()),
(pair, entry) -> {
if(entry.getValue() == null) {
pair._2.add(entry.getKey());
} else {
pair._1.put(entry.getKey(), entry.getValue());
}
},
(p1, p2) -> {
p1._1.putAll(p2._1);
p1._2.addAll(p2._2);
return p1;
});
}
with its usage:
Tuple2<Map<K, V>, List<K>> pair =
animalMap.entrySet().parallelStream().collect(customCollector());
You can tune it more if you want, for example by providing a predicate as parameter.
If your use case is that some backend code inserts a record, then the same code wants to retrieve the last insert id, without counting on any underlying data access library preset function to do this, then, as mentioned by others, you should just craft your SQL query using SEQ_MY_NAME.NEXTVAL
for the column you want (usually the primary key), then just run statement SELECT SEQ_MY_NAME.CURRVAL FROM dual
from the backend.
Remember, CURRVAL is only callable if NEXTVAL has been priorly invoked, which is all naturally done in the strategy above...
S.Lott inserted a comment, but it should be an answer: see the same question.
Since it wasn't as obvious as I intended it to be, here follows a verbatim copy of S.Lott's answer in the other question:
I'm a big fan of ARGO UML from Tigris.org. Draws nice pictures using standard UML notation. It does some code generation, but mostly Java classes, which isn't SQL DDL, so that may not be close enough to what you want to do.
You can look at the Data Modelling Tools list and see if anything there is better than Argo UML. Many of the items on this list are free or cheap.
Also, if you're using Eclipse or NetBeans, there are many design plug-ins, some of which may have the features you're looking for.
When a VS2013 C++ project is opened in VS2015, and there are warnings about "The build tools for v120... cannot be found", I simply need to edit the .vcxproj file and change <PlatformToolset>v120</PlatformToolset>
to <PlatformToolset>v140</PlatformToolset>
, and close and re-open the solution.
That's depending if userid is a resource identifier or additional parameter. If it is then it's ok to return 404 if not you might return other code like
400 (bad request) - indicates a bad request
or
412 (Precondition Failed) e.g. conflict by performing conditional update
More info in free InfoQ Explores: REST book.
In the latest version of Pandas there is an easy way to do exactly this. Column names (which are strings) can be sliced in whatever manner you like.
columns = ['b', 'c']
df1 = pd.DataFrame(df, columns=columns)
You can use VBSedit software to convert your VBS code to .exe file. You can download free version from Internet and installtion vbsedit applilcation on your system and convert the files to exe format.
Vbsedit is a good application for VBscripter's
This is extremely easy to do in Sass! Don't delve into JavaScript for this. The & selector in sass does exactly this.
http://thesassway.com/intermediate/referencing-parent-selectors-using-ampersand
Let's start with the need for scaling that is increasing resources so that your system can now handle more requests than it earlier could.
When you realise your system is getting slow and is unable to handle the current number of requests, you need to scale the system.
This provides you with two options. Either you increase the resources in the server which you are using currently, i.e, increase the amount of RAM, CPU, GPU and other resources. This is known as vertical scaling.
Vertical scaling is typically costly. It does not make the system fault tolerant, i.e if you are scaling application running with single server, if that server goes down, your system will go down. Also the amount of threads remains the same in vertical scaling. Vertical scaling may require your system to go down for a moment when process takes place. Increasing resources on a server requires a restart and put your system down.
Another solution to this problem is increasing the amount of servers present in the system. This solution is highly used in the tech industry. This will eventually decrease the request per second rate in each server. If you need to scale the system, just add another server, and you are done. You would not be required to restart the system. Number of threads in each system decreases leading to high throughput. To segregate the requests, equally to each of the application server, you need to add load balancer which would act as reverse proxy to the web servers. This whole system can be called as a single cluster. Your system may contain a large number of requests which would require more amount of clusters like this.
Hope you get the whole concept of introducing scaling to the system.
<select id="cars">
<option value='volvo'>volvo</option>
<option value='bmw'>bmw</option>
<option value='fiat'>fiat</option>
</select>
var make = "fiat";
$("#cars option[value='" + make + "']").attr("selected","selected");
Change your return type to java.lang.Integer . This way you can safely return null
Your MySQL binaries should be somewhere under your XAMPP folder. Look for a /bin folder, and you'll find the mysql.exe client around. Let's assume it is in c:\xampp\mysql\bin, then you should fireup a command prompt in this folder.
That means, fire up "cmd", and type:
cd c:\xampp\mysql\bin
mysql.exe -u root --password
If you want to use mysqldump.exe, you should also find it there.
Log into your mysql server, and start typing your commands.
Hope it helps...
You are getting something wrong... RTSP is a realtime streaming protocol. Meaning, you can stream whatever you want in real time. So you can use it to stream LIVE content (no matter what it is, video, audio, text, presentation...). RTP is a transport protocol which is used to transport media data which is negotiated over RTSP.
You use RTSP to control media transmission over RTP. You use it to setup, play, pause, teardown the stream...
So, if you want your server to just start streaming when the URL is requested, you can implement some sort of RTP-only server. But if you want more control and if you are streaming live video, you must use RTSP, because it transmits SDP and other important decoding data.
Read the documents I linked here, they are a good starting point.
The access type should be set to offline
. state
is a variable you set for your own use, not the API's use.
Make sure you have the latest version of the client library and add:
$client->setAccessType('offline');
See Forming the URL for an explanation of the parameters.
Javascript doesn't handle Strings over multiple lines.
You will need to concatenate those:
var obj = '{'
+'"name" : "Raj",'
+'"age" : 32,'
+'"married" : false'
+'}';
You can also use template literals in ES6 and above: (See here for the documentation)
var obj = `{
"name" : "Raj",
"age" : 32,
"married" : false,
}`;
userType = (user.Type == 0) ? "Admin" : (user.type == 1) ? "User" : "Admin";
should do the trick.
If you use it in a database, this is a good way:
Set the ip field in database to varchar(250), and then use this:
$theip = $_SERVER["REMOTE_ADDR"];
if (!empty($_SERVER["HTTP_X_FORWARDED_FOR"])) {
$theip .= '('.$_SERVER["HTTP_X_FORWARDED_FOR"].')';
}
if (!empty($_SERVER["HTTP_CLIENT_IP"])) {
$theip .= '('.$_SERVER["HTTP_CLIENT_IP"].')';
}
$realip = substr($theip, 0, 250);
Then you just check $realip against the database ip field
You could use the function group.sum
from package Rfast.
Category <- Rfast::as_integer(Category,result.sort=FALSE) # convert character to numeric. R's as.numeric produce NAs.
result <- Rfast::group.sum(Frequency,Category)
names(result) <- Rfast::Sort(unique(Category)
# 30 5 34
Rfast has many group functions and group.sum
is one of them.
You mean you want to add a new row and only put data in a certain column? Try the following:
var row = dataTable.NewRow();
row[myColumn].Value = "my new value";
dataTable.Add(row);
As it is a data table, though, there will always be data of some kind in every column. It just might be DBNull.Value
instead of whatever data type you imagine it would be.
The AJAX request never has the opportunity to NOT follow the redirect (i.e., it must follow the redirect). More information can be found in this answer https://stackoverflow.com/a/2573589/965648
df.groupby('key you want to group by').apply(print)
As mentioned by an other member, this is the easiest and simplest solution to visualize a groupby object.
A RESTful resource controller sets up some default routes for you and even names them.
Route::resource('users', 'UsersController');
Gives you these named routes:
Verb Path Action Route Name
GET /users index users.index
GET /users/create create users.create
POST /users store users.store
GET /users/{user} show users.show
GET /users/{user}/edit edit users.edit
PUT|PATCH /users/{user} update users.update
DELETE /users/{user} destroy users.destroy
And you would set up your controller something like this (actions = methods)
class UsersController extends BaseController {
public function index() {}
public function show($id) {}
public function store() {}
}
You can also choose what actions are included or excluded like this:
Route::resource('users', 'UsersController', [
'only' => ['index', 'show']
]);
Route::resource('monkeys', 'MonkeysController', [
'except' => ['edit', 'create']
]);
Laravel 5.5 added another method for dealing with routes for resource controllers. API Resource Controller acts exactly like shown above, but does not register create
and edit
routes. It is meant to be used for ease of mapping routes used in RESTful APIs - where you typically do not have any kind of data located in create
nor edit
methods.
Route::apiResource('users', 'UsersController');
RESTful Resource Controller documentation
An Implicit controller is more flexible. You get routed to your controller methods based on the HTTP request type and name. However, you don't have route names defined for you and it will catch all subfolders for the same route.
Route::controller('users', 'UserController');
Would lead you to set up the controller with a sort of RESTful naming scheme:
class UserController extends BaseController {
public function getIndex()
{
// GET request to index
}
public function getShow($id)
{
// get request to 'users/show/{id}'
}
public function postStore()
{
// POST request to 'users/store'
}
}
Implicit Controller documentation
It is good practice to use what you need, as per your preference. I personally don't like the Implicit controllers, because they can be messy, don't provide names and can be confusing when using php artisan routes
. I typically use RESTful Resource controllers in combination with explicit routes.
Tokens need to be stored somewhere (local/session storage or cookies)
Tokens can expire like cookies, but you have more control
Local/session storage won't work across domains, use a marker cookie
Preflight requests will be sent on each CORS request
When you need to stream something, use the token to get a signed request
It's easier to deal with XSS than XSRF
The token gets sent on every request, watch out its size
If you store confidential info, encrypt the token
JSON Web Tokens can be used in OAuth
Tokens are not silver bullets, think about your authorization use cases carefully
http://blog.auth0.com/2014/01/27/ten-things-you-should-know-about-tokens-and-cookies/
http://blog.auth0.com/2014/01/07/angularjs-authentication-with-cookies-vs-token/
thisTag = _tags.FirstOrDefault(t => t.Key == tag);
is an inefficient and a little bit strange way to find something by key in a dictionary. Looking things up for a Key is the basic function of a Dictionary.
The basic solution would be:
if (_tags.Containskey(tag)) { string myValue = _tags[tag]; ... }
But that requires 2 lookups.
TryGetValue(key, out value)
is more concise and efficient, it only does 1 lookup. And that answers the last part of your question, the best way to do a lookup is:
string myValue;
if (_tags.TryGetValue(tag, out myValue)) { /* use myValue */ }
VS 2017 update, for C# 7 and beyond we can declare the result variable inline:
if (_tags.TryGetValue(tag, out string myValue))
{
// use myValue;
}
// use myValue, still in scope, null if not found
Edit: the api call has been removed by google. so it is no longer functioning.
Agree with Pareshkumar's answer. Now there is a python wrapper googlefinance for the url call.
Install googlefinance
$pip install googlefinance
It is easy to get current stock price:
>>> from googlefinance import getQuotes
>>> import json
>>> print json.dumps(getQuotes('AAPL'), indent=2)
[
{
"Index": "NASDAQ",
"LastTradeWithCurrency": "129.09",
"LastTradeDateTime": "2015-03-02T16:04:29Z",
"LastTradePrice": "129.09",
"Yield": "1.46",
"LastTradeTime": "4:04PM EST",
"LastTradeDateTimeLong": "Mar 2, 4:04PM EST",
"Dividend": "0.47",
"StockSymbol": "AAPL",
"ID": "22144"
}
]
Google finance is a source that provides real-time stock data. There are also other APIs from yahoo, such as yahoo-finance, but they are delayed by 15min for NYSE and NASDAQ stocks.
I feel the performance characteristics change from one DBMS to another. It's all on how they choose to implement it. Since I have worked extensively on Oracle, I'll tell from that perspective.
COUNT(*)
- Fetches entire row into result set before passing on to the count function, count function will aggregate 1 if the row is not null
COUNT(1)
- Will not fetch any row, instead count is called with a constant value of 1 for each row in the table when the WHERE
matches.
COUNT(PK)
- The PK in Oracle is indexed. This means Oracle has to read only the index. Normally one row in the index B+ tree is many times smaller than the actual row. So considering the disk IOPS rate, Oracle can fetch many times more rows from Index with a single block transfer as compared to entire row. This leads to higher throughput of the query.
From this you can see the first count is the slowest and the last count is the fastest in Oracle.
You can use SQL Compact Query Analyzer
http://sqlcequery.codeplex.com/
SQL Compact Query Analyzer is really snappy. 3 MB download, requires an install but really snappy and works.
label for=
in html formThis could permit to visualy dissociate label(s) and object while keeping them linked.
Sample: there is a checkbox and two labels. You could check/uncheck the box by clicking indifferently on any label or on box, but not on text nor on input content...
<label for="demo1"> There is a label </label>
<br />
Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Duis sem velit, ultrices et, fermentum auctor, rhoncus ut, ligula. Phasellus at purus sed purus cursus iaculis. Suspendisse fermentum. Pellentesque et arcu. Maecenas viverra. In consectetuer, lorem eu lobortis egestas, velit odio imperdiet eros, sit amet sagittis nunc mi ac neque. Sed non ipsum. Nullam venenatis gravida orci.
<br />
<label for="demo1"> There is a 2nd label </label>
<input id="demo1" type="checkbox">Demo 1</input>
_x000D_
By use stylesheet CSS
power, you could do a lot of interresting things...
#demo2:checked ~ .but2:before { content: 'Des'; }
#demo2:checked ~ .box2:before { content: '?'; }
.but2:before { content: 'S'; }
.box2:before { content: '?'; }
#demo1:checked ~ .but1:before { content: 'Des'; }
#demo1:checked ~ .box1:before { content: '?'; }
.but1:before { content: 'S'; }
.box1:before { content: '?'; }
_x000D_
<input id="demo1" type="checkbox">Demo 1</input>
<input id="demo2" type="checkbox">Demo 2</input>
<br />
<label for="demo1" class="but1">elect 2</label> -
<label for="demo2" class="but2">elect 1</label>
<br />
Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Duis sem velit, ultrices et, fermentum auctor, rhoncus ut, ligula. Phasellus at purus sed purus cursus iaculis. Suspendisse fermentum. Pellentesque et arcu. Maecenas viverra. In consectetuer, lorem eu lobortis egestas, velit odio imperdiet eros, sit amet sagittis nunc mi ac neque. Sed non ipsum. Nullam venenatis gravida orci.
<br />
<label for="demo1" class="but1">elect this 2nd label </label> -
<label class="but2" for="demo2">elect this another 2nd label </label>
<br />
<label for="demo1" class="box1"> check 1</label>
<label for="demo2" class="box2"> check 2</label>
_x000D_
Upload Image See Here click This Link
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;
class AppConfig {
private static String BASE_URL = "http://mushtaq.16mb.com/";
static Retrofit getRetrofit() {
return new Retrofit.Builder()
.baseUrl(AppConfig.BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.build();
}
}
========================================================
import okhttp3.MultipartBody;
import okhttp3.RequestBody;
import retrofit2.Call;
import retrofit2.http.Multipart;
import retrofit2.http.POST;
import retrofit2.http.Part;
interface ApiConfig {
@Multipart
@POST("retrofit_example/upload_image.php")
Call<ServerResponse> uploadFile(@Part MultipartBody.Part file,
@Part("file") RequestBody name);
/*@Multipart
@POST("ImageUpload")
Call<ServerResponseKeshav> uploadFile(@Part MultipartBody.Part file,
@Part("file") RequestBody name);*/
@Multipart
@POST("retrofit_example/upload_multiple_files.php")
Call<ServerResponse> uploadMulFile(@Part MultipartBody.Part file1,
@Part MultipartBody.Part file2);
}
//https://drive.google.com/open?id=0BzBKpZ4nzNzUMnJfaklVVTJkWEk
I have found the selected answer to have problems with upscaling, and so I have made (yet) another version (which I have tested):
public static Point scaleFit(Point src, Point bounds) {
int newWidth = src.x;
int newHeight = src.y;
double boundsAspectRatio = bounds.y / (double) bounds.x;
double srcAspectRatio = src.y / (double) src.x;
// first check if we need to scale width
if (boundsAspectRatio < srcAspectRatio) {
// scale width to fit
newWidth = bounds.x;
//scale height to maintain aspect ratio
newHeight = (newWidth * src.y) / src.x;
} else {
//scale height to fit instead
newHeight = bounds.y;
//scale width to maintain aspect ratio
newWidth = (newHeight * src.x) / src.y;
}
return new Point(newWidth, newHeight);
}
Written in Android terminology :-)
as for the tests:
@Test public void scaleFit() throws Exception {
final Point displaySize = new Point(1080, 1920);
assertEquals(displaySize, Util.scaleFit(displaySize, displaySize));
assertEquals(displaySize, Util.scaleFit(new Point(displaySize.x / 2, displaySize.y / 2), displaySize));
assertEquals(displaySize, Util.scaleFit(new Point(displaySize.x * 2, displaySize.y * 2), displaySize));
assertEquals(new Point(displaySize.x, displaySize.y * 2), Util.scaleFit(new Point(displaySize.x / 2, displaySize.y), displaySize));
assertEquals(new Point(displaySize.x * 2, displaySize.y), Util.scaleFit(new Point(displaySize.x, displaySize.y / 2), displaySize));
assertEquals(new Point(displaySize.x, displaySize.y * 3 / 2), Util.scaleFit(new Point(displaySize.x / 3, displaySize.y / 2), displaySize));
}
list1 = ["name1", "info1", 10]
list2 = ["name2", "info2", 30]
list3 = ["name3", "info3", 50]
def printer(*lists):
for _list in lists:
for ele in _list:
print(ele, end = ", ")
print()
printer(list1, list2, list3)
Use substr with parameter -1:
"linto.yahoo.com.".substr(-1);
equals "."
Note:
To extract characters from the end of the string, use a negative start number (This does not work in IE 8 and earlier).
In my case problem went away simply by using HttpContext.Current.Session
instead of Session
Gradle can work with the 18.0.+ notation, it however now depends on the new support repository which is now bundled with the SDK.
Open the SDK manager and immediately under Extras the first option is "Android Support Repository" and install it
I make Miquels Version Injectable as service:
import { Injectable } from '@angular/core';
@Injectable()
export class CookiesService {
isConsented = false;
constructor() {}
/**
* delete cookie
* @param name
*/
public deleteCookie(name) {
this.setCookie(name, '', -1);
}
/**
* get cookie
* @param {string} name
* @returns {string}
*/
public getCookie(name: string) {
const ca: Array<string> = decodeURIComponent(document.cookie).split(';');
const caLen: number = ca.length;
const cookieName = `${name}=`;
let c: string;
for (let i = 0; i < caLen; i += 1) {
c = ca[i].replace(/^\s+/g, '');
if (c.indexOf(cookieName) === 0) {
return c.substring(cookieName.length, c.length);
}
}
return '';
}
/**
* set cookie
* @param {string} name
* @param {string} value
* @param {number} expireDays
* @param {string} path
*/
public setCookie(name: string, value: string, expireDays: number, path: string = '') {
const d: Date = new Date();
d.setTime(d.getTime() + expireDays * 24 * 60 * 60 * 1000);
const expires = `expires=${d.toUTCString()}`;
const cpath = path ? `; path=${path}` : '';
document.cookie = `${name}=${value}; ${expires}${cpath}; SameSite=Lax`;
}
/**
* consent
* @param {boolean} isConsent
* @param e
* @param {string} COOKIE
* @param {string} EXPIRE_DAYS
* @returns {boolean}
*/
public consent(isConsent: boolean, e: any, COOKIE: string, EXPIRE_DAYS: number) {
if (!isConsent) {
return this.isConsented;
} else if (isConsent) {
this.setCookie(COOKIE, '1', EXPIRE_DAYS);
this.isConsented = true;
e.preventDefault();
}
}
}
My issue was that I had a setInterval
running, which had an if/else
block, where the clearInterval
method was inside the else
:
const dataExistsInterval = setInterval(async () => {
const dataExists = Object.keys(req.body).length !== 0;
if (dataExists) {
if (!req.files.length) {
return res.json({ msg: false });
} else {
clearInterval(dataExistsInterval);
try {
. . .
Putting the clearInterval
before the if/else
did the trick.
add JAVA_HOME to the file:
/etc/environment
for it to be available to the entire system (you would need to restart Ubuntu though)
Well Facebook has undergone MANY many changes and it wasn't originally designed to be efficient. It was designed to do it's job. I have absolutely no idea what the code looks like and you probably won't find much info about it (for obvious security and copyright reasons), but just take a look at the API. Look at how often it changes and how much of it doesn't work properly, anymore, or at all.
I think the biggest ace up their sleeve is the Hiphop. http://developers.facebook.com/blog/post/358 You can use HipHop yourself: https://github.com/facebook/hiphop-php/wiki
But if you ask me it's a very ambitious and probably time wasting task. Hiphop only supports so much, it can't simply convert everything to C++. So what does this tell us? Well, it tells us that Facebook is NOT fully taking advantage of the PHP language. It's not using the latest 5.3 and I'm willing to bet there's still a lot that is PHP 4 compatible. Otherwise, they couldn't use HipHop. HipHop IS A GOOD IDEA and needs to grow and expand, but in it's current state it's not really useful for that many people who are building NEW PHP apps.
There's also PHP to JAVA via things like Resin/Quercus. Again, it doesn't support everything...
Another thing to note is that if you use any non-standard PHP module, you aren't going to be able to convert that code to C++ or Java either. However...Let's take a look at PHP modules. They are ARE compiled in C++. So if you can build PHP modules that do things (like parse XML, etc.) then you are basically (minus some interaction) working at the same speed. Of course you can't just make a PHP module for every possible need and your entire app because you would have to recompile and it would be much more difficult to code, etc.
However...There are some handy PHP modules that can help with speed concerns. Though at the end of the day, we have this awesome thing known as "the cloud" and with it, we can scale our applications (PHP included) so it doesn't matter as much anymore. Hardware is becoming cheaper and cheaper. Amazon just lowered it's prices (again) speaking of.
So as long as you code your PHP app around the idea that it will need to one day scale...Then I think you're fine and I'm not really sure I'd even look at Facebook and what they did because when they did it, it was a completely different world and now trying to hold up that infrastructure and maintain it...Well, you get things like HipHop.
Now how is HipHop going to help you? It won't. It can't. You're starting fresh, you can use PHP 5.3. I'd highly recommend looking into PHP 5.3 frameworks and all the new benefits that PHP 5.3 brings to the table along with the SPL libraries and also think about your database too. You're most likely serving up content from a database, so check out MongoDB and other types of databases that are schema-less and document-oriented. They are much much faster and better for the most "common" type of web site/app.
Look at NEW companies like Foursquare and Smugmug and some other companies that are utilizing NEW technology and HOW they are using it. For as successful as Facebook is, I honestly would not look at them for "how" to build an efficient web site/app. I'm not saying they don't have very (very) talented people that work there that are solving (their) problems creatively...I'm also not saying that Facebook isn't a great idea in general and that it's not successful and that you shouldn't get ideas from it....I'm just saying that if you could view their entire source code, you probably wouldn't benefit from it.
You can use this function if you want to add the data into database, with a button. I hope it will help.
// dgvBill is name of DataGridView
string StrQuery;
try
{
using (SqlConnection conn = new SqlConnection(ConnectingString))
{
using (SqlCommand comm = new SqlCommand())
{
comm.Connection = conn;
conn.Open();
for (int i = 0; i < dgvBill.Rows.Count; i++)
{
StrQuery = @"INSERT INTO tblBillDetails (IdBill, productID, quantity, price, total) VALUES ('" + IdBillVar+ "','" + dgvBill.Rows[i].Cells[0].Value + "', '" + dgvBill.Rows[i].Cells[4].Value + "', '" + dgvBill.Rows[i].Cells[3].Value + "', '" + dgvBill.Rows[i].Cells[2].Value + "');";
comm.CommandText = StrQuery;
comm.ExecuteNonQuery();
}
}
}
}
catch (Exception err)
{
MessageBox.Show(err.Message , "Error !");
}
In your pom.xml file inside that <java.version> write "8" instead write "11" ,and RECOMPILE your pom.xml file And tadaaaaaa it works !
If you want to always display some value after decimal for example "12.00" or "12.23" Then use just like below , it worked for me
FormatNumber("145.231000",2)
Which will display 145.23
FormatNumber("145",2)
Which will display 145.00
1 - Go to window . 2 - Go to Perspective and click . 3 - Go to Reset Perspective. 4 - Then you will find Eclipse all reset option.
this worked fine for me:
<div class="card card-body " style="height:80% !important">
forcing our CSS over the bootstraps general CSS.
Lodash has a _.pickBy
function which does exactly what you're looking for.
var thing = {_x000D_
"a": 123,_x000D_
"b": 456,_x000D_
"abc": 6789_x000D_
};_x000D_
_x000D_
var result = _.pickBy(thing, function(value, key) {_x000D_
return _.startsWith(key, "a");_x000D_
});_x000D_
_x000D_
console.log(result.abc) // 6789_x000D_
console.log(result.b) // undefined
_x000D_
<script src="https://cdn.jsdelivr.net/lodash/4.16.4/lodash.min.js"></script>
_x000D_
May be You are not registering the Controllers. Try below code:
Step 1. Write your own controller factory class ControllerFactory :DefaultControllerFactory by implementing defaultcontrollerfactory in models folder
public class ControllerFactory :DefaultControllerFactory
{
protected override IController GetControllerInstance(RequestContext requestContext, Type controllerType)
{
try
{
if (controllerType == null)
throw new ArgumentNullException("controllerType");
if (!typeof(IController).IsAssignableFrom(controllerType))
throw new ArgumentException(string.Format(
"Type requested is not a controller: {0}",
controllerType.Name),
"controllerType");
return MvcUnityContainer.Container.Resolve(controllerType) as IController;
}
catch
{
return null;
}
}
public static class MvcUnityContainer
{
public static UnityContainer Container { get; set; }
}
}
Step 2:Regigster it in BootStrap: inBuildUnityContainer method
private static IUnityContainer BuildUnityContainer()
{
var container = new UnityContainer();
// register all your components with the container here
// it is NOT necessary to register your controllers
// e.g. container.RegisterType<ITestService, TestService>();
//RegisterTypes(container);
container = new UnityContainer();
container.RegisterType<IProductRepository, ProductRepository>();
MvcUnityContainer.Container = container;
return container;
}
Step 3: In Global Asax.
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
WebApiConfig.Register(GlobalConfiguration.Configuration);
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles);
AuthConfig.RegisterAuth();
Bootstrapper.Initialise();
ControllerBuilder.Current.SetControllerFactory(typeof(ControllerFactory));
}
And you are done
Did you write return true
somewhere? You should have written it, otherwise function returns nothing and program may think that it's false, too.
function isValid(str) {
var iChars = "~`!#$%^&*+=-[]\\\';,/{}|\":<>?";
for (var i = 0; i < str.length; i++) {
if (iChars.indexOf(str.charAt(i)) != -1) {
alert ("File name has special characters ~`!#$%^&*+=-[]\\\';,/{}|\":<>? \nThese are not allowed\n");
return false;
}
}
return true;
}
I tried this in my chrome console and it worked well.
I recently (today) needed to figure out a quick way to do this and of course I was going to use the exception approach for ease when the monkey on the shoulder (conscience) woke up so it took me down this old familiar rabbit hole; no exceptions are not that much more expensive in fact sometimes exceptions are faster (old AIX multiprocessor systems) but regardless it’s to elegant so I did something that the younger me never did and to my amazement nobody here did either (apologize if someone did and I missed it I honestly did not find) : so what did I think we all missed; taking a look at how the JRE implemented it, yes they threw an exception but we can always skip that part.
The younger me from 10 years ago would have felt this to be beneath him, but then again he is a loud mouthed show off with a poor temperament and a god complex so there is that.
I am putting this here for the benefit of anyone coming here in the future. Here is what I found:
public static int parseInt(String s, int radix) throws NumberFormatException
{
/*
* WARNING: This method may be invoked early during VM initialization
* before IntegerCache is initialized. Care must be taken to not use
* the valueOf method.
*/
if (s == null) {
throw new NumberFormatException("null");
}
if (radix < Character.MIN_RADIX) {
throw new NumberFormatException("radix " + radix +
" less than Character.MIN_RADIX");
}
if (radix > Character.MAX_RADIX) {
throw new NumberFormatException("radix " + radix +
" greater than Character.MAX_RADIX");
}
int result = 0;
boolean negative = false;
int i = 0, len = s.length();
int limit = -Integer.MAX_VALUE;
int multmin;
int digit;
if (len > 0) {
char firstChar = s.charAt(0);
if (firstChar < '0') { // Possible leading "+" or "-"
if (firstChar == '-') {
negative = true;
limit = Integer.MIN_VALUE;
} else if (firstChar != '+')
throw NumberFormatException.forInputString(s);
if (len == 1) // Cannot have lone "+" or "-"
throw NumberFormatException.forInputString(s);
i++;
}
multmin = limit / radix;
while (i < len) {
// Accumulating negatively avoids surprises near MAX_VALUE
digit = Character.digit(s.charAt(i++),radix);
if (digit < 0) {
throw NumberFormatException.forInputString(s);
}
if (result < multmin) {
throw NumberFormatException.forInputString(s);
}
result *= radix;
if (result < limit + digit) {
throw NumberFormatException.forInputString(s);
}
result -= digit;
}
} else {
throw NumberFormatException.forInputString(s);
}
return negative ? result : -result;
}
Lapack is a Linear Algebra package which is used by R (actually it's used everywhere) underneath solve()
, dgesv spits this kind of error when the matrix you passed as a parameter is singular.
As an addendum: dgesv performs LU decomposition, which, when using your matrix, forces a division by 0, since this is ill-defined, it throws this error. This only happens when matrix is singular or when it's singular on your machine (due to approximation you can have a really small number be considered 0)
I'd suggest you check its determinant if the matrix you're using contains mostly integers and is not big. If it's big, then take a look at this link.
Adding to @Kirill Fuchs excellent solution and answering @StackUser's doubt - while starting the http-server, set the path till the app folder only, NOT till the html page!
http-server C:\location\to\app
and access index.html
under app
folder
NSDictionary from NSData
http://www.cocoanetics.com/2009/09/nsdictionary-from-nsdata/
NSDictionary to NSData
You can use NSPropertyListSerialization class for that. Have a look at its method:
+ (NSData *)dataFromPropertyList:(id)plist format:(NSPropertyListFormat)format
errorDescription:(NSString **)errorString
Returns an NSData object containing a given property list in a specified format.
If you only want to read the first 999,999 (non-header) rows:
read_csv(..., nrows=999999)
If you only want to read rows 1,000,000 ... 1,999,999
read_csv(..., skiprows=1000000, nrows=999999)
nrows : int, default None Number of rows of file to read. Useful for reading pieces of large files*
skiprows : list-like or integer Row numbers to skip (0-indexed) or number of rows to skip (int) at the start of the file
and for large files, you'll probably also want to use chunksize:
chunksize : int, default None Return TextFileReader object for iteration