The different between getTextBounds
and measureText
is described with the image below.
In short,
getTextBounds
is to get the RECT of the exact text. The measureText
is the length of the text, including the extra gap on the left and right.
If there are spaces between the text, it is measured in measureText
but not including in the length of the TextBounds, although the coordinate get shifted.
The text could be tilted (Skew) left. In this case, the bounding box left side would exceed outside the measurement of the measureText, and the overall length of the text bound would be bigger than measureText
The text could be tilted (Skew) right. In this case, the bounding box right side would exceed outside the measurement of the measureText, and the overall length of the text bound would be bigger than measureText
I am summarizing the steps that helped me in resolving this issue:
During installation, IIS Express uses Http.sys to reserve ports 44300 through 44399 for SSL use. This enables standard users (without elevated privileges) of IISExpress to configure and use SSL. For more details on this refer here
netsh http show sslcert > sslcert.txt
IP:port : 0.0.0.0:44300
Certificate Hash : eb380ba6bd10fb4f597cXXXXXXXXXX
Application ID : {214124cd-d05b-4309-XXX-XXXXXXX}
(Click on the ServerRoot -> under section IIS () -> Open the Server Certificates)
netsh http delete sslcert ipport=0.0.0.0:44300
netsh http add sslcert ipport=0.0.0.0:44300 certhash=New_Certificate_Hash_without_space appid={214124cd-d05b-4309-XXX-XXXXXXX}
The New_Certificate_Hash will be your default certificate tied-up with your localhost (That we found in step 4) or the one which you want to add as a new certificate.
P.S. Thank you for your answer uos?? (which helped me in resolving this issue)
You may also use the handy replace_na function: https://tidyr.tidyverse.org/reference/replace_na.html
Followed Mark's advise and did this to set the default number formatting to text in the whole workbook:
$objPHPExcel = new PHPExcel();
$objPHPExcel->getDefaultStyle()
->getNumberFormat()
->setFormatCode(
PHPExcel_Style_NumberFormat::FORMAT_TEXT
);
And it works flawlessly. Thank you, Mark Baker.
The solution of using a list of axes by abevieiramota works very well until you use only one row of images, as pointed out in the comments. Using a reasonable aspect ratio for figsize
helps, but is still far from perfect. For example:
import numpy as np
import matplotlib.pyplot as plt
fig, axes = plt.subplots(nrows=1, ncols=3, figsize=(9.75, 3))
for ax in axes.flat:
im = ax.imshow(np.random.random((10,10)), vmin=0, vmax=1)
fig.colorbar(im, ax=axes.ravel().tolist())
plt.show()
The colorbar function provides the shrink
parameter which is a scaling factor for the size of the colorbar axes. It does require some manual trial and error. For example:
fig.colorbar(im, ax=axes.ravel().tolist(), shrink=0.75)
Decode the string to Unicode. Assuming it's UTF-8-encoded:
str.decode("utf-8")
Call the replace
method and be sure to pass it a Unicode string as its first argument:
str.decode("utf-8").replace(u"\u2022", "*")
Encode back to UTF-8, if needed:
str.decode("utf-8").replace(u"\u2022", "*").encode("utf-8")
(Fortunately, Python 3 puts a stop to this mess. Step 3 should really only be performed just prior to I/O. Also, mind you that calling a string str
shadows the built-in type str
.)
As of today Nov 4, 2018 all the following methods works, install the zsh with:
sh -c "$(curl -fsSL https://raw.githubusercontent.com/robbyrussell/oh-my-zsh/master/tools/install.sh)"
Not recommending brew installation for zsh:
brew install zsh zsh-completions
P.S: Tried with with brew and brew install under the root and is not an wise idea to do so due the security and all time anything related will need to be started under sudo so better is to stick with curl or wget.
to make work conda in OS X with oh-my-zsh installed is to add path as following and will work.
Find the python paths so can see if you installed Anaconda2 or Anaconda3:
where python
orwhich python
will result in similar output:
/usr/bin/python
/Users/"username"/anaconda3/bin/python
/usr/bin/python
Finding your Anaconda Python interpreter path
vi ~/.zshrc or gedit ~/.zshrc
For Anaconda: at field
# User configuration
add:
PATH="$HOME/anaconda/bin:$PATH"
For Anaconda2 at field
# User configuration
add:
PATH="$HOME/anaconda/bin:$PATH"
For Anaconda3 at field
# User configuration
add:
PATH="$HOME/anaconda3/bin:$PATH"
or replace "username" with your username:
PATH="/Users/"username"/anaconda3/bin:$PATH
According to documentation Installing on macOS we add add in
~/.zshrc
instead of.bashrc or .bash_profile
Add export
PATH="/<path to anaconda>/bin:$PATH"
in ~/.zshrcOr set the PATH variable:
export PATH="/<path to anaconda>/bin:$PATH"
Replace
“<path to anaconda>”
with the actual path to your Anaconda installation.This methods are working on ubuntu/Centos7/MacOS as well (just close/reset the terminal once you are completing the changes) than just type conda to test.
Per @truongnm comment just source after adding the path: "I pasted the path from my bash_profile, and don't forget to
source ~/.zshrc
"
foreach (DataRow row in myDataTable.Rows)
{
Console.WriteLine(row["ImagePath"]);
}
I am writing this from memory.
Hope this gives you enough hint to understand the object model.
DataTable
-> DataRowCollection
-> DataRow
(which one can use & look for column contents for that row, either using columnName or ordinal).
-> = contains.
For loading weights, you need to have a model first. It must be:
existingModel.save_weights('weightsfile.h5')
existingModel.load_weights('weightsfile.h5')
If you want to save and load the entire model (this includes the model's configuration, it's weights and the optimizer states for further training):
model.save_model('filename')
model = load_model('filename')
Also, using the awesome font, you can use the following tag. Simple and beautiful
With the possibility of changing the size and color and other features in CSS
See result here
I am using this a status update to show a "+" character every 1000 iterations, and it seems to be working good.
if ($ucounter % 1000 == 0) { echo '+'; }
You could in theory piggyback addEventListener and removeEventListener to add remove a flag to the 'this' object. Ugly and I haven't tested ...
Change column position:
ALTER TABLE Employees
CHANGE empName empName VARCHAR(50) NOT NULL AFTER department;
If you need to move it to the first position you have to use term FIRST at the end of ALTER TABLE CHANGE [COLUMN] query:
ALTER TABLE UserOrder
CHANGE order_id order_id INT(11) NOT NULL FIRST;
You should try this for the putting 2 array in singlr foreach loop Suppose i have 2 Array 1.$item_nm 2.$item_qty
`<?php $i=1; ?>
<table><tr><td>Sr.No</td> <td>item_nm</td> <td>item_qty</td> </tr>
@foreach (array_combine($item_nm, $item_qty) as $item_nm => $item_qty)
<tr>
<td> $i++ </td>
<td> $item_nm </td>
<td> $item_qty </td>
</tr></table>
@endforeach `
You can simply wrap your list as a data.frame (data.frame is in fact a special kind of list). Here is an example:
mylist = list()
mylist[["a"]] = 1:10
mylist[["b"]] = letters[1:10]
write.table(as.data.frame(mylist),file="mylist.csv", quote=F,sep=",",row.names=F)
or alternatively you can use write.csv (a wrapper around write.table). For the conversion of the list , you can use both as.data.frame(mylist)
and data.frame(mylist)
.
To help in making a reproducible example, you can use functions like dput
on your data.
Problem here is you are trying to open a mongo shell without starting a mongo db which is listening to port 127.0.0.1:27017(deafault for mongo db) thats what the error is all about:
Error: couldn't connect to server 127.0.0.1:27017 at src/mongo/shell/mongo.js:145 exception: connect failed
The easiest solution is to open the terminal and type
$ mongod --dbpath ~/data/db
Note: dbpath here is "Users/user" where data/db directories are created
i.e., you need to create directory data and sub directory db in your user folder. For e.g say `
/Users/johnny/data
After mongo db is up. Open another terminal in new window and type
$ mongo
it will open mongo shell with your mongo db connection opened in another terminal.
Maybe in your data source add a column which does a sumif over all rows.
Not sure what your data looks like but something like =(sumif([column holding pivot row heads),[current row head value in row], probability column)>.2).
This will give you a True when the pivot table will show >20%.
Then add a filter on your pivot table on this column for TRUE values
The Official Documentation is clear about Path
.
Linux Syntax: /home/joe/foo
Windows Syntax: C:\home\joe\foo
Note: joe
is your username for these examples.
Check it Out-->
For getting text
$("#selme").change(function(){
$(this[this.selectedIndex]).text();
});
For getting value
$("#selme").change(function(){
$(this[this.selectedIndex]).val();
});
just and another class to jumbotron
bg-transparent
It will work perfectly
bootstrap color documentation: https://getbootstrap.com/docs/4.3/utilities/colors/
how's this one?
def global_index(lst, test):
return ( pair[0] for pair in zip(range(len(lst)), lst) if test(pair[1]) )
Usage:
>>> global_index([1, 2, 3, 4, 5, 6], lambda x: x>3)
<generator object <genexpr> at ...>
>>> list(_)
[3, 4, 5]
NP-complete problems are those problems that are both NP-Hard and in the complexity class NP. Therefore, to show that any given problem is NP-complete, you need to show that the problem is both in NP and that it is NP-hard.
Problems that are in the NP complexity class can be solved non-deterministically in polynomial time and a possible solution (i.e., a certificate) for a problem in NP can be verified for correctness in polynomial time.
An example of a non-deterministic solution to the k-clique problem would be something like:
1) randomly select k nodes from a graph
2) verify that these k nodes form a clique.
The above strategy is polynomial in the size of the input graph and therefore the k-clique problem is in NP.
Note that all problems deterministically solvable in polynomial time are also in NP.
Showing that a problem is NP-hard typically involves a reduction from some other NP-hard problem to your problem using a polynomial time mapping: http://en.wikipedia.org/wiki/Reduction_(complexity)
First of all you missed ScriptService attribute to add in webservice.
[ScriptService]
After then try following method to call webservice via JSON.
var webAddr = "http://Domain/VBRService.asmx/callJson"; var httpWebRequest = (HttpWebRequest)WebRequest.Create(webAddr); httpWebRequest.ContentType = "application/json; charset=utf-8"; httpWebRequest.Method = "POST"; using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream())) { string json = "{\"x\":\"true\"}"; streamWriter.Write(json); streamWriter.Flush(); } var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse(); using (var streamReader = new StreamReader(httpResponse.GetResponseStream())) { var result = streamReader.ReadToEnd(); return result; }
Use Location Listener Method
@Override
public void onLocationChanged(Location loc) {
Double lat = loc.getLatitude();
Double lng = loc.getLongitude();
}
std::list<Object> l;
std::list<Object>::iterator ptr;
int i;
for( i = 0 , ptr = l.begin() ; i < N && ptr != l.end() ; i++ , ptr++ );
if( ptr == l.end() ) {
// list too short
} else {
// 'ptr' points to N-th element of list
}
buf.delete(0, buf.length());
Below are two functions: dbo.HexToInt and dbo.IntToHex, I use them for such conversion:
if OBJECT_ID('dbo.HexToInt') is not null
drop function dbo.HexToInt
GO
create function dbo.HexToInt (@chars varchar(max))
returns int
begin
declare @char varchar(1), @len int, @i int, @r int, @tmp int, @pow int
set @chars = RTRIM(LTRIM(@chars))
set @len = LEN(@chars)
set @i = 1
set @r = 0
while @i <= @len
begin
set @pow = @len - @i
set @char = SUBSTRING(@chars, @i, 1)
if @char = '0'
set @tmp = 0
else if @char = '1'
set @tmp = 1
else if @char = '2'
set @tmp = 2
else if @char = '3'
set @tmp = 3
else if @char = '4'
set @tmp = 4
else if @char = '5'
set @tmp = 5
else if @char = '6'
set @tmp = 6
else if @char = '7'
set @tmp = 7
else if @char = '8'
set @tmp = 8
else if @char = '9'
set @tmp = 9
else if @char = 'A'
set @tmp = 10
else if @char = 'B'
set @tmp = 11
else if @char = 'C'
set @tmp = 12
else if @char = 'D'
set @tmp = 13
else if @char = 'E'
set @tmp = 14
else if @char = 'F'
set @tmp = 15
set @r = @r + @tmp * POWER(16,@pow)
set @i = @i + 1
end
return @r
end
And the second one:
if OBJECT_ID('dbo.IntToHex') is not null
drop function dbo.IntToHex
GO
create function dbo.IntToHex (@val int)
returns varchar(max)
begin
declare @r varchar(max), @tmp int, @v1 int, @v2 int, @char varchar(1)
set @tmp = @val
set @r = ''
while 1=1
begin
set @v1 = @tmp / 16
set @v2 = @tmp % 16
if @v2 = 0
set @char = '0'
else if @v2 = 1
set @char = '1'
else if @v2 = 2
set @char = '2'
else if @v2 = 3
set @char = '3'
else if @v2 = 4
set @char = '4'
else if @v2 = 5
set @char = '5'
else if @v2 = 6
set @char = '6'
else if @v2 = 7
set @char = '7'
else if @v2 = 8
set @char = '8'
else if @v2 = 9
set @char = '9'
else if @v2 = 10
set @char = 'A'
else if @v2 = 11
set @char = 'B'
else if @v2 = 12
set @char = 'C'
else if @v2 = 13
set @char = 'D'
else if @v2 = 14
set @char = 'E'
else if @v2 = 15
set @char = 'F'
set @tmp = @v1
set @r = @char + @r
if @tmp = 0
break
end
return @r
end
Why to annoy the user with three different Dialog Boxes to enter things, why not do all this in one go in a single Dialog and save time, instead of testing the patience of the USER ?
You can add everything in a single Dialog, by putting all the fields on your JPanel
and then adding this JPanel
to your JOptionPane
. Below code can clarify a bit more :
import java.awt.*;
import java.util.*;
import javax.swing.*;
public class AverageExample
{
private double[] marks;
private JTextField[] marksField;
private JLabel resultLabel;
public AverageExample()
{
marks = new double[3];
marksField = new JTextField[3];
marksField[0] = new JTextField(10);
marksField[1] = new JTextField(10);
marksField[2] = new JTextField(10);
}
private void displayGUI()
{
int selection = JOptionPane.showConfirmDialog(
null, getPanel(), "Input Form : "
, JOptionPane.OK_CANCEL_OPTION
, JOptionPane.PLAIN_MESSAGE);
if (selection == JOptionPane.OK_OPTION)
{
for ( int i = 0; i < 3; i++)
{
marks[i] = Double.valueOf(marksField[i].getText());
}
Arrays.sort(marks);
double average = (marks[1] + marks[2]) / 2.0;
JOptionPane.showMessageDialog(null
, "Average is : " + Double.toString(average)
, "Average : "
, JOptionPane.PLAIN_MESSAGE);
}
else if (selection == JOptionPane.CANCEL_OPTION)
{
// Do something here.
}
}
private JPanel getPanel()
{
JPanel basePanel = new JPanel();
//basePanel.setLayout(new BorderLayout(5, 5));
basePanel.setOpaque(true);
basePanel.setBackground(Color.BLUE.darker());
JPanel centerPanel = new JPanel();
centerPanel.setLayout(new GridLayout(3, 2, 5, 5));
centerPanel.setBorder(
BorderFactory.createEmptyBorder(5, 5, 5, 5));
centerPanel.setOpaque(true);
centerPanel.setBackground(Color.WHITE);
JLabel mLabel1 = new JLabel("Enter Marks 1 : ");
JLabel mLabel2 = new JLabel("Enter Marks 2 : ");
JLabel mLabel3 = new JLabel("Enter Marks 3 : ");
centerPanel.add(mLabel1);
centerPanel.add(marksField[0]);
centerPanel.add(mLabel2);
centerPanel.add(marksField[1]);
centerPanel.add(mLabel3);
centerPanel.add(marksField[2]);
basePanel.add(centerPanel);
return basePanel;
}
public static void main(String... args)
{
SwingUtilities.invokeLater(new Runnable()
{
@Override
public void run()
{
new AverageExample().displayGUI();
}
});
}
}
In the HTML which you have provided:
<div>My Button</div>
The text My Button
is the innerHTML
and have no whitespaces around it so you can easily use text()
as follows:
my_element = driver.find_element_by_xpath("//div[text()='My Button']")
Note:
text()
selects all text node children of the context node
In case the relevant text containing whitespaces either in the beginning:
<div> My Button</div>
or at the end:
<div>My Button </div>
or at both the ends:
<div> My Button </div>
In these cases you have two options:
You can use contains()
function which determines whether the first argument string contains the second argument string and returns boolean true or false as follows:
my_element = driver.find_element_by_xpath("//div[contains(., 'My Button')]")
You can use normalize-space()
function which strips leading and trailing white-space from a string, replaces sequences of whitespace characters by a single space, and returns the resulting string as follows:
driver.find_element_by_xpath("//div[normalize-space()='My Button']]")
In case the text is a variable, you can use:
foo= "foo_bar"
my_element = driver.find_element_by_xpath("//div[.='" + foo + "']")
While this is not yet valid for Java 7 and below, I believe that we should look to the future and at least recognize the changes to come in new versions such as Java 8.
Namely, this new version brings lambdas and method references to Java (along with new APIs, which are another valid solution to this problem. While they still require an interface no new objects are created, and extra classfiles need not pollute output directories due to different handling by the JVM.
Both flavors(lambda and method reference) require an interface available with a single method whose signature is used:
public interface NewVersionTest{
String returnAString(Object oIn, String str);
}
Names of methods will not matter from here on. Where a lambda is accepted, a method reference is as well. For example, to use our signature here:
public static void printOutput(NewVersionTest t, Object o, String s){
System.out.println(t.returnAString(o, s));
}
This is just a simple interface invocation, up until the lambda1 gets passed:
public static void main(String[] args){
printOutput( (Object oIn, String sIn) -> {
System.out.println("Lambda reached!");
return "lambda return";
}
);
}
This will output:
Lambda reached!
lambda return
Method references are similar. Given:
public class HelperClass{
public static String testOtherSig(Object o, String s){
return "real static method";
}
}
and main:
public static void main(String[] args){
printOutput(HelperClass::testOtherSig);
}
the output would be real static method
. Method references can be static, instance, non-static with arbitrary instances, and even constructors. For the constructor something akin to ClassName::new
would be used.
1 This is not considered a lambda by some, as it has side effects. It does illustrate, however, the use of one in a more straightforward-to-visualize fashion.
Try this query:
SELECT *
FROM table
WHERE MONTH(FROM_UNIXTIME(columnName))= MONTH(CURDATE())
Create a bash file say move.sh
which has the following code
C:\cygwin64\bin\run.exe -p /bin bash runFile.sh
This starts the Cygwin and executes the runFile.sh
present in the bin directory of Cygwin
Suppose you want to navigate to a specific directory say E:\code
then runFile.sh has the following code cd E:
cd code
I assume you're talking about the Apache server that Oracle installs. Look for the file httpd.conf.
Open this file in a text editor and look for the line
Listen 8080
or
Listen {ip address}:8080
Change the port number and either restart the web server or just reboot the machine.
Lots of these answers no longer apply, so here's mine:
Use the Share Dialog described at the Facebook Dev Page.
Example:
https://www.facebook.com/dialog/share?
app_id=<your_app_id>
&display=popup
&href=https%3A%2F%2Fdevelopers.facebook.com%2Fdocs%2F
&redirect_uri=https%3A%2F%2Fdevelopers.facebook.com%2Ftools%2Fexplorer
But you have to put in your registered app_id, the href, and a redirect uri.
It'll have the same behavior as the underlying recv libc call see the man page for an official description of behavior (or read a more general description of the sockets api).
When the directory is deleted, the inode for that directory (and the inodes for its contents) are recycled. The pointer your shell has to that directory's inode (and its contents's inodes) are now no longer valid. When the directory is restored from backup, the old inodes are not (necessarily) reused; the directory and its contents are stored on random inodes. The only thing that stays the same is that the parent directory reuses the same name for the restored directory (because you told it to).
Now if you attempt to access the contents of the directory that your original shell is still pointing to, it communicates that request to the file system as a request for the original inode, which has since been recycled (and may even be in use for something entirely different now). So you get a stale file handle
message because you asked for some nonexistent data.
When you perform a cd
operation, the shell reevaluates the inode location of whatever destination you give it. Now that your shell knows the new inode for the directory (and the new inodes for its contents), future requests for its contents will be valid.
I had same Issue and i solve it following way:
The xml file which is using for create a Row inside createViewholder, just add below line:
android:clickable="true"
android:focusableInTouchMode="true"
android:background="?attr/selectableItemBackgroundBorderless"
OR If you using frameLayout as a parent of row item then:
android:clickable="true"
android:focusableInTouchMode="true"
android:foreground="?attr/selectableItemBackgroundBorderless"
In java code inside view holder where you added on click listener:
@Override
public void onClick(View v) {
//ur other code here
v.setPressed(true);
}
I honestly thought that the casting method would work fine. Since it doesn't you can try stringstream. An example is below:
#include <sstream>
#include <string>
std::stringstream ss;
std::string target;
char mychar = 'a';
ss << mychar;
ss >> target;
One caveat! If you want to compose this via OR or AND you cannot use it in this form:
-myfield:*
but you must use
(*:* NOT myfield:*)
This form is perfectly composable. Apparently SOLR will expand the first form to the second, but only when it is a top node. Hope this saves you some time!
To compare entire revisions, it's simply:
svn diff -r 8979:11390
If you want to compare the last committed state against your currently saved working files, you can use convenience keywords:
svn diff -r PREV:HEAD
(Note, without anything specified afterwards, all files in the specified revisions are compared.)
You can compare a specific file if you add the file path afterwards:
svn diff -r 8979:HEAD /path/to/my/file.php
Make sure your Java version matches the project's Java version requirement. This could be an another cause for such kinds of issues.
For imported maven project and JDK 1.7 do the following:
Modify your pom.xml file, add following properties (make sure following settings are not overridden by explicit maven-compiler-plugin definition in your POM)
<properties>
<maven.compiler.source>1.7</maven.compiler.source>
<maven.compiler.target>1.7</maven.compiler.target>
</properties>
Import updated project into Eclipse.
endstring = ''
for s in list:
endstring += s
if using avast go for virus chest,will find adb,restore it by clicking right button..thats all,perfectly works
The other answers might not be easy to understand for one who is not much familiar with the subject of architectural patterns. Someone who is new to app architecture might want to know how its choice can affect her app in practice and what all the fuss is about in communities.
Trying to shed some light on the above, I made up this screenplay involving MVVM, MVP and MVC. The story begins by a user clicking on the ‘FIND’ button in a movie search app… :
User: Click …
View: Who’s that? [MVVM|MVP|MVC]
User: I just clicked on the search button …
View: Ok, hold on a sec … . [MVVM|MVP|MVC]
( View calling the ViewModel|Presenter|Controller … ) [MVVM|MVP|MVC]
View: Hey ViewModel|Presenter|Controller, a User has just clicked on the search button, what shall I do? [MVVM|MVP|MVC]
ViewModel|Presenter|Controller: Hey View, is there any search term on that page? [MVVM|MVP|MVC]
View: Yes,… here it is … “piano” [MVVM|MVP|MVC]
—— This is the most important difference between MVVM AND MVP|MVC ———
Presenter: Thanks View,… meanwhile I’m looking up the search term on the Model, please show him/her a progress bar [MVP|MVC]
( Presenter|Controller is calling the Model … ) [MVP|MVC]
ViewController: Thanks, I’ll be looking up the search term on the Model but will not update you directly. Instead, I will trigger events to searchResultsListObservable if there is any result. So you had better observe on that. [MVVM]
(While observing on any trigger in searchResultsListObservable, the View thinks it should show some progress bar to the user, since ViewModel would not talk to it on that)
——————————————————————————————
ViewModel|Presenter|Controller: Hey Model, Do you have any match for this search term?: “piano” [MVVM|MVP|MVC]
Model: Hey ViewModel|Presenter|Controller, let me check … [MVVM|MVP|MVC]
( Model is making a query to the movie database … ) [MVVM|MVP|MVC]
( After a while … )
———— This is the diverging point between MVVM, MVP and MVC ————–
Model: I found a list for you, ViewModel|Presenter, here it is in JSON “[{“name”:”Piano Teacher”,”year”:2001},{“name”:”Piano”,”year”:1993}]” [MVVM|MVP]
Model: There is some result available, Controller. I have created a field variable in my instance and filled it with the result. It’s name is “searchResultsList” [MVC]
(Presenter|Controller thanks Model and gets back to the View) [MVP|MVC]
Presenter: Thanks for waiting View, I found a list of matching results for you and arranged them in a presentable format: [“Piano Teacher 2001",”Piano 1993”]. Also please hide the progress bar now [MVP]
Controller: Thanks for waiting View, I have asked Model about your search query. It says it has found a list of matching results and stored them in a variable named “searchResultsList” inside its instance. You can get it from there. Also please hide the progress bar now [MVC]
ViewModel: Any observer on searchResultsListObservable be notified that there is this new list in presentable format: [“Piano Teacher 2001",”Piano 1993”].[MVVM]
View: Thank you very much Presenter [MVP]
View: Thank you “Controller” [MVC] (Now the View is questioning itself: How should I present the results I get from the Model to the user? Should the production year of the movie come first or last…?)
View: Oh, there is a new trigger in searchResultsListObservable … , good, there is a presentable list, now I only have to show it in a list. I should also hide the progress bar now that I have the result. [MVVM]
In case you are interested, I have written a series of articles here, comparing MVVM, MVP and MVC by implementing a movie search android app.
Install the latest version of TDM-GCC here is the link-http://wiki.codeblocks.org/index.php/MinGW_installation
ViewData
: It requires type casting for complex data types and checks for null values to avoid errors.
ViewBag
: It doesn’t require type casting for complex data types.
Consider the following example:
public class HomeController : Controller
{
public ActionResult Index()
{
var emp = new Employee
{
EmpID=101,
Name = "Deepak",
Salary = 35000,
Address = "Delhi"
};
ViewData["emp"] = emp;
ViewBag.Employee = emp;
return View();
}
}
And the code for View
is as follows:
@model MyProject.Models.EmpModel;
@{
Layout = "~/Views/Shared/_Layout.cshtml";
ViewBag.Title = "Welcome to Home Page";
var viewDataEmployee = ViewData["emp"] as Employee; //need type casting
}
<h2>Welcome to Home Page</h2>
This Year Best Employee is!
<h4>@ViewBag.Employee.Name</h4>
<h3>@viewDataEmployee.Name</h3>
Bootstrap is an open-source CSS, JavaScript framework that was originally developed for twitter application by twitter's team of designers and developers. Then they released it for open-source. Being a longtime user of twitter bootstrap I find that its one of the best for designing mobile ready responsive websites. Many CSS and Javascript plugins are available for designing your website in no time. It's kind of rapid template design framework. Some people complain that the bootstrap CSS files are heavy and take time to load but these claims are made by lazy people. You don't have to keep the complete bootstrap.css in your website. You always have the option to remove the styles for components that you do not need for your website. For example, if you are only using basic components like forms and buttons then you can remove other components like accordions etc from the main CSS file. To start dabbling in bootstrap you can download the basic templates and components from getbootstrap site and let the magic happen.
For me, I found the suggestion in the following thread helped:
It suggested running the following command in the Terminal application:
sudo /usr/sbin/DevToolsSecurity --enable
//Time compare.
private int CompareTime(string t1, string t2)
{
TimeSpan s1 = TimeSpan.Parse(t1);
TimeSpan s2 = TimeSpan.Parse(t2);
return s2.CompareTo(s1);
}
There is a way to catch the error directly in the except clause with ConnectionResetError, better to isolate the right error. This example also catches the timeout.
from urllib.request import urlopen
from socket import timeout
url = "http://......"
try:
string = urlopen(url, timeout=5).read()
except ConnectionResetError:
print("==> ConnectionResetError")
pass
except timeout:
print("==> Timeout")
pass
This will let you choose from email, whatsapp or whatever.
try {
Intent shareIntent = new Intent(Intent.ACTION_SEND);
shareIntent.setType("text/plain");
shareIntent.putExtra(Intent.EXTRA_SUBJECT, "My application name");
String shareMessage= "\nLet me recommend you this application\n\n";
shareMessage = shareMessage + "https://play.google.com/store/apps/details?id=" + BuildConfig.APPLICATION_ID +"\n\n";
shareIntent.putExtra(Intent.EXTRA_TEXT, shareMessage);
startActivity(Intent.createChooser(shareIntent, "choose one"));
} catch(Exception e) {
//e.toString();
}
<table id="table1"></table>
<table id="table2"></table>
or
<table class="table1"></table>
<table class="table2"></table>
I'm not sure what you mean by having tried it onblur, but to get the length of any string, use its .length property, so in the case of a textbox or textarea:
document.getElementById("textarea").value.length
Changing that ID, of course, to whatever the actual ID is.
The count
method of NSArray
returns an NSUInteger
, and on the 64-bit OS X platform
NSUInteger
is defined as unsigned long
, andunsigned long
is a 64-bit unsigned integer.int
is a 32-bit integer.So int
is a "smaller" datatype than NSUInteger
, therefore the compiler warning.
See also NSUInteger in the "Foundation Data Types Reference":
When building 32-bit applications, NSUInteger is a 32-bit unsigned integer. A 64-bit application treats NSUInteger as a 64-bit unsigned integer.
To fix that compiler warning, you can either declare the local count
variable as
NSUInteger count;
or (if you are sure that your array will never contain more than 2^31-1
elements!),
add an explicit cast:
int count = (int)[myColors count];
For this span
<span id="name">sdfsdf</span>
You can go like this :-
$("name").firstChild.nodeValue = "Hello" + "World";
A performance-driven approach - calling environ
is expensive, so it's better to call it once and save it to a dictionary. Full example:
from os import environ
# Slower
print(environ["USER"], environ["NAME"])
# Faster
env_dict = dict(environ)
print(env_dict["USER"], env_dict["NAME"])
P.S- if you worry about exposing private environment variables, then sanitize env_dict
after the assignment.
Just wanted to complete the thread. To be very clear this does not works in IE9, however we can do it by little css trick.
<div class="customselect">
<select>
<option>2000</option>
<option>2001</option>
<option>2002</option>
</select>
</div>
.customselect {
width: 80px;
overflow: hidden;
border:1px solid;
}
.customselect select {
width: 100px;
border:none;
-moz-appearance: none;
-webkit-appearance: none;
appearance: none;
}
As @Brian Riley already said you should either remove 1 column in your select
select countrylanguage.language ,sum(country.population*countrylanguage.percentage/100)
from countrylanguage
join country on countrylanguage.countrycode = country.code
group by countrylanguage.language
order by sum(country.population*countrylanguage.percentage) desc ;
or add it to your grouping
select countrylanguage.language, country.code, sum(country.population*countrylanguage.percentage/100)
from countrylanguage
join country on countrylanguage.countrycode = country.code
group by countrylanguage.language, country.code
order by sum(country.population*countrylanguage.percentage) desc ;
To be able to build with C# 6 syntax use this in path:
C:\Program Files (x86)\MSBuild\14.0\Bin
Note: The answer below is written from the perspective of Windows PowerShell.
However, it applies to the cross-platform PowerShell Core edition (v6+) as well, except that the latter - commendably - consistently defaults to BOM-less UTF-8 character encoding, which is the most widely compatible one across platforms and cultures..
To complement bigtv's helpful answer helpful answer with a more concise alternative and background information:
# > $file is effectively the same as | Out-File $file
# Objects are written the same way they display in the console.
# Default character encoding is UTF-16LE (mostly 2 bytes per char.), with BOM.
# Use Out-File -Encoding <name> to change the encoding.
$env:computername > $file
# Set-Content calls .ToString() on each object to output.
# Default character encoding is "ANSI" (culture-specific, single-byte).
# Use Set-Content -Encoding <name> to change the encoding.
# Use Set-Content rather than Add-Content; the latter is for *appending* to a file.
$env:computername | Set-Content $file
When outputting to a text file, you have 2 fundamental choices that use different object representations and, in Windows PowerShell (as opposed to PowerShell Core), also employ different default character encodings:
Out-File
(or >
) / Out-File -Append
(or >>
):
Suitable for output objects of any type, because PowerShell's default output formatting is applied to the output objects.
The default encoding, which can be changed with the -Encoding
parameter, is Unicode
, which is UTF-16LE in which most characters are encoded as 2 bytes. The advantage of a Unicode encoding such as UTF-16LE is that it is a global alphabet, capable of encoding all characters from all human languages.
>
and >>
, via the $PSDefaultParameterValues
preference variable, taking advantage of the fact that >
and >>
are now effectively aliases of Out-File
and Out-File -Append
. To change to UTF-8, for instance, use:$PSDefaultParameterValues['Out-File:Encoding']='UTF8'
For writing strings and instances of types known to have meaningful string representations, such as the .NET primitive data types (Booleans, integers, ...).
.psobject.ToString()
method is called on each output object, which results in meaningless representations for types that don't explicitly implement a meaningful representation; [hashtable]
instances are an example:@{ one = 1 } | Set-Content t.txt
writes literal System.Collections.Hashtable
to t.txt
, which is the result of @{ one = 1 }.ToString()
.The default encoding, which can be changed with the -Encoding
parameter, is Default
, which is the system's "ANSI" code page, a the single-byte culture-specific legacy encoding for non-Unicode applications, most commonly Windows-1252.
Note that the documentation currently incorrectly claims that ASCII is the default encoding.
Note that Add-Content
's purpose is to append content to an existing file, and it is only equivalent to Set-Content
if the target file doesn't exist yet.
Furthermore, the default or specified encoding is blindly applied, irrespective of the file's existing contents' encoding.
Out-File
/ >
/ Set-Content
/ Add-Content
all act culture-sensitively, i.e., they produce representations suitable for the current culture (locale), if available (though custom formatting data is free to define its own, culture-invariant representation - see Get-Help about_format.ps1xml
).
This contrasts with PowerShell's string expansion (string interpolation in double-quoted strings), which is culture-invariant - see this answer of mine.
As for performance: Since Set-Content
doesn't have to apply default formatting to its input, it performs better.
As for the OP's symptom with Add-Content
:
Since $env:COMPUTERNAME
cannot contain non-ASCII characters, Add-Content
's output, using "ANSI" encoding, should not result in ?
characters in the output, and the likeliest explanation is that the ?
were part of the preexisting content in output file $file
, which Add-Content
appended to.
Try doing this:
py -m pip install pipwin
py -m pipwin install PyAudio
Start the second activity with startActivityForResult and in the second activity return a value, that once in the onActivityResult method of the first activity closes the main application. I think this is the correct way Android does it.
If zero doesn't work as the proper default value, you can use the component model to define a workaround for the enum:
[DefaultValue(None)]
public enum Orientation
{
None = -1,
North = 0,
East = 1,
South = 2,
West = 3
}
public static class Utilities
{
public static TEnum GetDefaultValue<TEnum>() where TEnum : struct
{
Type t = typeof(TEnum);
DefaultValueAttribute[] attributes = (DefaultValueAttribute[])t.GetCustomAttributes(typeof(DefaultValueAttribute), false);
if (attributes != null &&
attributes.Length > 0)
{
return (TEnum)attributes[0].Value;
}
else
{
return default(TEnum);
}
}
}
and then you can call:
Orientation o = Utilities.GetDefaultValue<Orientation>();
System.Diagnostics.Debug.Print(o.ToString());
Note: you will need to include the following line at the top of the file:
using System.ComponentModel;
This does not change the actual C# language default value of the enum, but gives a way to indicate (and get) the desired default value.
Sometimes you don't have the option of editing the php file to set $_GET to the parameters passed in, and sometimes you can't or don't want to install php-cgi.
I found this to be the best solution for that case:
php -r '$_GET["key"]="value"; require_once("script.php");'
This avoids altering your php file and lets you use the plain php command. If you have php-cgi installed, by all means use that, but this is the next best thing. Thought this options was worthy of mention
the -r means run the php code in the string following. you set the $_GET value manually there, and then reference the file you want to run.
Its worth noting you should run this in the right folder, often but not always the folder the php file is in. Requires statements will use the location of your command to resolve relative urls, NOT the location of the file
Try this:
apt-get install lib32stdc++6
It is done to maintain the arrangement of bytes which is sent in the network(Endianness). Depending upon architecture of your device,data can be arranged in the memory either in the big endian format or little endian format. In networking, we call the representation of byte order as network byte order and in our host, it is called host byte order. All network byte order is in big endian format.If your host's memory computer architecture is in little endian format,htons() function become necessity but in case of big endian format memory architecture,it is not necessary.You can find endianness of your computer programmatically too in the following way:->
int x = 1;
if (*(char *)&x){
cout<<"Little Endian"<<endl;
}else{
cout<<"Big Endian"<<endl;
}
and then decide whether to use htons() or not.But in order to avoid the above line,we always write htons() although it does no changes for Big Endian based memory architecture.
In addition to @Marc Claesen's answer, I think that an instructive classic example of cache-unfriendly code is code that scans a C bidimensional array (e.g. a bitmap image) column-wise instead of row-wise.
Elements that are adjacent in a row are also adjacent in memory, thus accessing them in sequence means accessing them in ascending memory order; this is cache-friendly, since the cache tends to prefetch contiguous blocks of memory.
Instead, accessing such elements column-wise is cache-unfriendly, since elements on the same column are distant in memory from each other (in particular, their distance is equal to the size of the row), so when you use this access pattern you are jumping around in memory, potentially wasting the effort of the cache of retrieving the elements nearby in memory.
And all that it takes to ruin the performance is to go from
// Cache-friendly version - processes pixels which are adjacent in memory
for(unsigned int y=0; y<height; ++y)
{
for(unsigned int x=0; x<width; ++x)
{
... image[y][x] ...
}
}
to
// Cache-unfriendly version - jumps around in memory for no good reason
for(unsigned int x=0; x<width; ++x)
{
for(unsigned int y=0; y<height; ++y)
{
... image[y][x] ...
}
}
This effect can be quite dramatic (several order of magnitudes in speed) in systems with small caches and/or working with big arrays (e.g. 10+ megapixels 24 bpp images on current machines); for this reason, if you have to do many vertical scans, often it's better to rotate the image of 90 degrees first and perform the various analysis later, limiting the cache-unfriendly code just to the rotation.
1) Create a key to sign your application, and remember the alias.
2) Install OpenSSL.
3) Put the bin folder of OpenSSL in your path.
4) Follow the steps mentioned under "Setup Single Sign-On" on the FB-Android-SDK page, and generate your Hash Key. Make sure you put the correct alias and keystore file name.
5) Create an application on Facebok, and under Mobile Devices tab, enter this Hash Key.
You can do
orig.update(extra)
or, if you don't want orig
to be modified, make a copy first:
dest = dict(orig) # or orig.copy()
dest.update(extra)
Note that if extra and orig have overlapping keys, the final value will be taken from extra. For example,
>>> d1 = {1: 1, 2: 2}
>>> d2 = {2: 'ha!', 3: 3}
>>> d1.update(d2)
>>> d1
{1: 1, 2: 'ha!', 3: 3}
var statuses = new[] { "A", "B", "C" };
var filteredOrders = from order in orders.Order
where statuses.Contains(order.StatusCode)
select order;
I had the same problem on my Eclipse Juno. These steps solved the problem :
Project -> Properties -> C/C++ General -> Path and Symbols -> Tab [Symbols]
. NOPASS
in the configuration on your target machine is the solution. Continue reading at http://maestric.com/doc/unix/ubuntu_sudo_without_password
string[] TobeDistinct = {"Name","City","State"};
DataTable dtDistinct = GetDistinctRecords(DTwithDuplicate, TobeDistinct);
//Following function will return Distinct records for Name, City and State column.
public static DataTable GetDistinctRecords(DataTable dt, string[] Columns)
{
DataTable dtUniqRecords = new DataTable();
dtUniqRecords = dt.DefaultView.ToTable(true, Columns);
return dtUniqRecords;
}
Create a new migration by executing this command : make:migration
Example :
php artisan make:migration add_store_id_to_users_table --table=users
In database/migrations folder you have new migration file, something like :
2018_08_08_093431_add_store_id_to_users_table.php (see the comments)
<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class AddStoreIdToUsersTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::table('users', function (Blueprint $table) {
// 1. Create new column
// You probably want to make the new column nullable
$table->integer('store_id')->unsigned()->nullable()->after('password');
// 2. Create foreign key constraints
$table->foreign('store_id')->references('id')->on('stores')->onDelete('SET NULL');
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::table('users', function (Blueprint $table) {
// 1. Drop foreign key constraints
$table->dropForeign(['store_id']);
// 2. Drop the column
$table->dropColumn('store_id');
});
}
}
After that run the command :
php artisan migrate
In case you want to undo the last migration for any reason, run this command :
php artisan migrate:rollback
You can find more information about migrations in the docs
You may need admin access to do it on your system.
C:\Program Files (x86)\Notepad++
themes
folder.
change the opacity of the parent element with the border and this will re organize the stacked elements. This worked miraculously for me after hours of research and failed attempts. It was as simple as adding an opacity of 0.99 to re organize this paint process of browsers. Check out http://philipwalton.com/articles/what-no-one-told-you-about-z-index/
Dependencies can be updated by using "Maven --> Update Project.." in Eclipse using m2e plugin, after pom.xml file modification.
Select "File" -> "Project Structure".
Under "Project Settings" select "Project"
From there you can select the "Project SDK".
Why not just make the server return the names?
["Woodland Hills", "none", "Los Angeles", "Laguna Hills"]
Then create the <option>
elements using JavaScript.
$.ajax({
url:'suggest.html',
type:'POST',
data: 'q=' + str,
dataType: 'json',
success: function( json ) {
$.each(json, function(i, value) {
$('#myselect').append($('<option>').text(value).attr('value', value));
});
}
});
I was having trouble with mobile touchscreen button styling. This will fix your hover-stick / active button problems.
body, html {
width: 600px;
}
p {
font-size: 20px;
}
button {
border: none;
width: 200px;
height: 60px;
border-radius: 30px;
background: #00aeff;
font-size: 20px;
}
button:active {
background: black;
color: white;
}
.delayed {
transition: all 0.2s;
transition-delay: 300ms;
}
.delayed:active {
transition: none;
}
_x000D_
<h1>Sticky styles for better touch screen buttons!</h1>
<button>Normal button</button>
<button class="delayed"><a href="https://www.google.com"/>Delayed style</a></button>
<p>The CSS :active psuedo style is displayed between the time when a user touches down (when finger contacts screen) on a element to the time when the touch up (when finger leaves the screen) occures. With a typical touch-screen tap interaction, the time of which the :active psuedo style is displayed can be very small resulting in the :active state not showing or being missed by the user entirely. This can cause issues with users not undertanding if their button presses have actually reigstered or not.</p>
<p>Having the the :active styling stick around for a few hundred more milliseconds after touch up would would improve user understanding when they have interacted with a button.</p>
_x000D_
Just wondering why you are using 2 directives?
It seems like, in this case it would be more straightforward to have a controller as the parent - handle adding the data from your service to its $scope, and pass the model you need from there into your warrantyDirective.
Or for that matter, you could use 0 directives to achieve the same result. (ie. move all functionality out of the separate directives and into a single controller).
It doesn't look like you're doing any explicit DOM transformation here, so in this case, perhaps using 2 directives is overcomplicating things.
Alternatively, have a look at the Angular documentation for directives: http://docs.angularjs.org/guide/directive The very last example at the bottom of the page explains how to wire up dependent directives.
I pasted your code into test project, added about 20 items and I get usable scroll bars, no problem, and they work as expected. When I only add a couple items (such that scrolling is unnecessary) I get no usable scrollbar. Could this be the case? that you are not adding enough items?
If you remove the ScrollViewer.VerticalScrollBarVisibility="Visible"
then the scroll bars only appear when you have need of them.
Yes, in C# 6.0 -- https://msdn.microsoft.com/en-us/magazine/dn802602.aspx.
object?.SomeMethod()
you can write to a unit, but you can also write to a string
program foo
character(len=1024) :: filename
write (filename, "(A5,I2)") "hello", 10
print *, trim(filename)
end program
Please note (this is the second trick I was talking about) that you can also build a format string programmatically.
program foo
character(len=1024) :: filename
character(len=1024) :: format_string
integer :: i
do i=1, 10
if (i < 10) then
format_string = "(A5,I1)"
else
format_string = "(A5,I2)"
endif
write (filename,format_string) "hello", i
print *, trim(filename)
enddo
end program
the join()
function must work for you:
$array = array('apple','banana','ananas');
$string = join(',', $array);
echo $string;
Output :
apple,banana,ananas
Sometime in the future Comment out the following code in web.config
<!--<system.codedom>
<compilers>
<compiler language="c#;cs;csharp" extension=".cs" type="Microsoft.CodeDom.Providers.DotNetCompilerPlatform.CSharpCodeProvider, Microsoft.CodeDom.Providers.DotNetCompilerPlatform, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" warningLevel="4" compilerOptions="/langversion:6 /nowarn:1659;1699;1701" />
<compiler language="vb;vbs;visualbasic;vbscript" extension=".vb" type="Microsoft.CodeDom.Providers.DotNetCompilerPlatform.VBCodeProvider, Microsoft.CodeDom.Providers.DotNetCompilerPlatform, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" warningLevel="4" compilerOptions="/langversion:14 /nowarn:41008 /define:_MYTYPE=\"Web\" /optionInfer+" />
</compilers>
</system.codedom>-->
update the to the following code.
<system.web>
<authentication mode="None" />
<compilation debug="true" targetFramework="4.6.1" />
<httpRuntime targetFramework="4.6.1" />
<customErrors mode="Off"/>
<trust level="Full"/>
</system.web>
Try this :
odd :
select * from(
SELECT col1, col2, ROW_NUMBER() OVER(ORDER BY col1 DESC) AS 'RowNumber',
FROM table1
) d where (RowNumber % 2) = 1
even :
select * from(
SELECT col1, col2, ROW_NUMBER() OVER(ORDER BY col1 DESC) AS 'RowNumber',
FROM table1
) d where (RowNumber % 2) = 0
Scott Guthrie has made a post on how to change Visual Studio's default browser:
1) Right click on a .aspx page in your solution explorer
2) Select the "browse with" context menu option
3) In the dialog you can select or add a browser. If you want Firefox in the list, click "add" and point to the firefox.exe filename
4) Click the "Set as Default" button to make this the default browser when you run any page on the site.
I however dislike the fact that this isn't as straightforward as it should be.
Or you could use the Probe application and just look at its System Info page. Much easier than writing code, and once you start using it you'll never go back to Tomcat Manager.
Just because @MartinCapodici 's comment is awesome I write here as an answer to give visibility.
All clockwise:
There is a massive difference in the example you have posted, the first version:
var urls = await context.Urls.ToListAsync();
This is bad, it basically does select * from table
, returns all results into memory and then applies the where
against that in memory collection rather than doing select * from table where...
against the database.
The second method will not actually hit the database until a query is applied to the IQueryable
(probably via a linq .Where().Select()
style operation which will only return the db values which match the query.
If your examples were comparable, the async
version will usually be slightly slower per request as there is more overhead in the state machine which the compiler generates to allow the async
functionality.
However the major difference (and benefit) is that the async
version allows more concurrent requests as it doesn't block the processing thread whilst it is waiting for IO to complete (db query, file access, web request etc).
this is pretty old, but if you are using Python 3.4 or above use PathLib.
# using OS
import os
path=os.path.dirname("C:/folder1/folder2/filename.xml")
print(path)
print(os.path.basename(path))
# using pathlib
import pathlib
path = pathlib.PurePath("C:/folder1/folder2/filename.xml")
print(path.parent)
print(path.parent.name)
If you are working with Android's MediaStore database, here is how to store an image and then display it after it is saved.
on button click write this
Intent in = new Intent(Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
in.putExtra("crop", "true");
in.putExtra("outputX", 100);
in.putExtra("outputY", 100);
in.putExtra("scale", true);
in.putExtra("return-data", true);
startActivityForResult(in, 1);
then do this in your activity
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// TODO Auto-generated method stub
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 1 && resultCode == RESULT_OK && data != null) {
Bitmap bmp = (Bitmap) data.getExtras().get("data");
img.setImageBitmap(bmp);
btnadd.requestFocus();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bmp.compress(Bitmap.CompressFormat.JPEG, 100, baos);
byte[] b = baos.toByteArray();
String encodedImageString = Base64.encodeToString(b, Base64.DEFAULT);
byte[] bytarray = Base64.decode(encodedImageString, Base64.DEFAULT);
Bitmap bmimage = BitmapFactory.decodeByteArray(bytarray, 0,
bytarray.length);
}
}
To remove the last character, just use a slice: my_file_path[:-1]
. If you only want to remove a specific set of characters, use my_file_path.rstrip('/')
. If you see the string as a file path, the operation is os.path.dirname. If the path is in fact a filename, I rather wonder where the extra slash came from in the first place.
In the new rspec
expect
syntax this would be:
expect(subject).to receive(:bar).with("an argument I want")
For UTC:
string unixTimestamp = Convert.ToString((int)DateTime.UtcNow.Subtract(new DateTime(1970, 1, 1)).TotalSeconds);
For local system:
string unixTimestamp = Convert.ToString((int)DateTime.Now.Subtract(new DateTime(1970, 1, 1)).TotalSeconds);
The default value for bool is false
. See this table for a great reference on default values. The only reason it would not be false when you check it is if you initialize/set it to true.
In your php.ini
configuration file simply uncomment the extension:
;extension=pdo_mysql
(You can find your php.ini file in the php folder where your server is installed.)
make this to
extension=pdo_mysql
now you need to configure your .env file in find DB_DATABASE=
write in that database name which you used than migrate like if i used my database and database name is "abc" than i need to write there DB_DATABASE=abc
and save that .env file and run command again
php artisan migrate
so after run than you got some msg like as:
php artisan migrate
Migration table created successfully.
This is the best place for Eclipse color themes:
To first force HTTPS, you must check the correct environment variable %{HTTPS} off
, but your rule above then prepends the www.
Since you have a second rule to enforce www.
, don't use it in the first rule.
RewriteEngine On
RewriteCond %{HTTPS} off
# First rewrite to HTTPS:
# Don't put www. here. If it is already there it will be included, if not
# the subsequent rule will catch it.
RewriteRule .* https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
# Now, rewrite any request to the wrong domain to use www.
# [NC] is a case-insensitive match
RewriteCond %{HTTP_HOST} !^www\. [NC]
RewriteRule .* https://www.%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
When behind some forms of proxying, whereby the client is connecting via HTTPS to a proxy, load balancer, Passenger application, etc., the %{HTTPS}
variable may never be on
and cause a rewrite loop. This is because your application is actually receiving plain HTTP traffic even though the client and the proxy/load balancer are using HTTPS. In these cases, check the X-Forwarded-Proto
header instead of the %{HTTPS}
variable. This answer shows the appropriate process
Javadoc for String has all the details. Removes white space (space, tabs, etc ) from both end and returns a new string.
This works for me:
git grep '<<<<<<< HEAD'
or
git grep '<<<<<<< HEAD' | less -N
What git-revert does is create a commit which undoes changes made in a given commit, creating a commit which is reverse (well, reciprocal) of a given commit. Therefore
git revert <SHA-1>
should and does work.
If you want to rewind back to a specified commit, and you can do this because this part of history was not yet published, you need to use git-reset, not git-revert:
git reset --hard <SHA-1>
(Note that --hard
would make you lose any non-committed changes in the working directory).
By the way, perhaps it is not obvious, but everywhere where documentation says <commit>
or <commit-ish>
(or <object>
), you can put an SHA-1 identifier (full or shortened) of commit.
The seek
function expect's an offset in bytes.
So if you have a text file with the following content:
simple.txt
abc
You can jump 1 byte to skip over the first character as following:
fp = open('simple.txt', 'r')
fp.seek(1)
print fp.readline()
>>> bc
fp = open('afile.png', 'rb')
fp.seek(16)
print 'width: {0}'.format(struct.unpack('>i', fp.read(4))[0])
print 'height: ', struct.unpack('>i', fp.read(4))[0]
Note: Once you call
read
you are changing the position of the read-head, which act's likeseek
.
Just to addon if someone is dealing with
, this would work if dealing with
.
Replace it with str_replace()
first and check it with empty()
empty(str_replace(" " ,"" , $YOUR_DATA)) ? $YOUR_DATA = '--' : $YOUR_DATA;
To quote the Python 2.x documentation:
A prefix of 'b' or 'B' is ignored in Python 2; it indicates that the literal should become a bytes literal in Python 3 (e.g. when code is automatically converted with 2to3). A 'u' or 'b' prefix may be followed by an 'r' prefix.
The Python 3 documentation states:
Bytes literals are always prefixed with 'b' or 'B'; they produce an instance of the bytes type instead of the str type. They may only contain ASCII characters; bytes with a numeric value of 128 or greater must be expressed with escapes.
CSS:
tr {
width: 100%;
display: inline-table;
height:60px; // <-- the rows height
}
table{
height:300px; // <-- Select the height of the table
display: -moz-groupbox; // For firefox bad effect
}
tbody{
overflow-y: scroll;
height: 200px; // <-- Select the height of the body
width: 100%;
position: absolute;
}
Bootply : http://www.bootply.com/AgI8LpDugl
For Font Awesome 5(webfont with css) and Laravel mixin add package for font awesome 5
npm i --save @fortawesome/fontawesome-free
And import font awesome scss in app.scss or your custom scss file
@import '~@fortawesome/fontawesome-free/scss/brands';
@import '~@fortawesome/fontawesome-free/scss/regular';
@import '~@fortawesome/fontawesome-free/scss/solid';
@import '~@fortawesome/fontawesome-free/scss/fontawesome';
compile your assets npm run dev
or npm run production
and include your compiled css into layout
Surely it's a little extreme to say
...never use a for in loop to enumerate over an array. Never. Use good old for(var i = 0; i<arr.length; i++)
?
It is worth highlighting the section in the Douglas Crockford extract
...The second form should be used with objects...
If you require an associative array ( aka hashtable / dictionary ) where keys are named instead of numerically indexed, you will have to implement this as an object, e.g. var myAssocArray = {key1: "value1", key2: "value2"...};
.
In this case myAssocArray.length
will come up null (because this object doesn't have a 'length' property), and your i < myAssocArray.length
won't get you very far. In addition to providing greater convenience, I would expect associative arrays to offer performance advantages in many situations, as the array keys can be useful properties (i.e. an array member's ID property or name), meaning you don't have to iterate through a lengthy array repeatedly evaluating if statements to find the array entry you're after.
Anyway, thanks also for the explanation of the JSLint error messages, I will use the 'isOwnProperty' check now when interating through my myriad associative arrays!
I used the above examples to craft my own function. But the missing piece for me was automatically escaping magic characters.
Here is my contribution:
function split(text, delim)
-- returns an array of fields based on text and delimiter (one character only)
local result = {}
local magic = "().%+-*?[]^$"
if delim == nil then
delim = "%s"
elseif string.find(delim, magic, 1, true) then
-- escape magic
delim = "%"..delim
end
local pattern = "[^"..delim.."]+"
for w in string.gmatch(text, pattern) do
table.insert(result, w)
end
return result
end
The accepted answer (DROP SERIES) will work for many cases, but will not work if the records you need to delete are distributed among many time ranges and tag sets.
A more general purpose approach (albeit a slower one) is to issue the delete queries one-by-one, with the use of another programming language.
For each of the records you want to delete:
Format this into a query, e.g.
DELETE FROM "things" WHERE time=123123123 AND tag1='val' AND tag2='val'
Send each of the queries one at a time
Weird, your code seems to work for me:
import java.util.Arrays;
public class Test
{
public static void main(String[] args)
{
// args is the list of guests
Arrays.sort(args);
for(int i = 0; i < args.length; i++)
System.out.println(args[i]);
}
}
I ran that code using "java Test Bobby Joe Angel" and here is the output:
$ java Test Bobby Joe Angel
Angel
Bobby
Joe
Of course: simply use os.chdir(..)
.
For separation of concern, I would suggest you use action filter for model validation, so you don't need to care much how to do validation in your api controller:
using System.Net;
using System.Net.Http;
using System.Web.Http.Controllers;
using System.Web.Http.Filters;
namespace System.Web.Http.Filters
{
public class ValidationActionFilter : ActionFilterAttribute
{
public override void OnActionExecuting(HttpActionContext actionContext)
{
var modelState = actionContext.ModelState;
if (!modelState.IsValid)
actionContext.Response = actionContext.Request
.CreateErrorResponse(HttpStatusCode.BadRequest, modelState);
}
}
}
You can always abuse type juggling:
function zpad(int $value, int $pad): string {
return substr(1, $value + 10 ** $pad);
}
This wont work as expected if either 10 ** pad > INT_MAX
or value >= 10 * pad
.
You can use the CSS3 Linear Gradient property along with your background-image like this:
#landing-wrapper {
display:table;
width:100%;
background: linear-gradient( rgba(0, 0, 0, 0.5), rgba(0, 0, 0, 0.5) ), url('landingpagepic.jpg');
background-position:center top;
height:350px;
}
Here's a demo:
#landing-wrapper {_x000D_
display: table;_x000D_
width: 100%;_x000D_
background: linear-gradient(rgba(0, 0, 0, 0.5), rgba(0, 0, 0, 0.5)), url('http://placehold.it/350x150');_x000D_
background-position: center top;_x000D_
height: 350px;_x000D_
color: white;_x000D_
}
_x000D_
<div id="landing-wrapper">Lorem ipsum dolor ismet.</div>
_x000D_
USE Database_Name
select name,recovery_model_desc from sys.databases
ALTER DATABASE Database_Name SET RECOVERY simple
DBCC SHRINKFILE (Database_Name_log , 1)
There's a simple way to get rid of this restriction by using the datePicker component provided by jQuery.
Include jQuery and jQuery UI libraries (I'm still using an old one)
Use the following snip
$(function() {
$( "#id_of_the_component" ).datepicker({ dateFormat: 'yy-mm-dd'});
});
See jQuery UI DatePicker - Change Date Format if needed.
I'm embarrassed to admit this, but the problem for me was that a template had been specified as ….hml
instead of ….html
. Watch out!
I just wanted to post a demo using calc() for setting rows/height, since no one did.
body {_x000D_
/* page default */_x000D_
font-size: 15px;_x000D_
line-height: 1.5;_x000D_
}_x000D_
_x000D_
textarea {_x000D_
/* demo related */_x000D_
width: 300px;_x000D_
margin-bottom: 1em;_x000D_
display: block;_x000D_
_x000D_
/* rows related */_x000D_
font-size: inherit;_x000D_
line-height: inherit;_x000D_
padding: 3px;_x000D_
}_x000D_
_x000D_
textarea.border-box {_x000D_
box-sizing: border-box;_x000D_
}_x000D_
_x000D_
textarea.rows-5 {_x000D_
/* height: calc(font-size * line-height * rows); */_x000D_
height: calc(1em * 1.5 * 5);_x000D_
}_x000D_
_x000D_
textarea.border-box.rows-5 {_x000D_
/* height: calc(font-size * line-height * rows + padding-top + padding-bottom + border-top-width + border-bottom-width); */_x000D_
height: calc(1em * 1.5 * 5 + 3px + 3px + 1px + 1px);_x000D_
}
_x000D_
<p>height is 2 rows by default</p>_x000D_
_x000D_
<textarea>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</textarea>_x000D_
_x000D_
<p>height is 5 now</p>_x000D_
_x000D_
<textarea class="rows-5">Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</textarea>_x000D_
_x000D_
<p>border-box height is 5 now</p>_x000D_
_x000D_
<textarea class="border-box rows-5">Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</textarea>
_x000D_
If you use large values for the paddings (e.g. greater than 0.5em), you'll start to see the text that overflows the content(-box) area, and that might lead you to think that the height is not exactly x rows (that you set), but it is. To understand what's going on, you might want to check out The box model and box-sizing pages.
It depends on what you want.
console.log("story "+name+" story")
will concatenate the strings together and print that. For me, I use this because it is easier to see what is going on.
Using console.log("story",name,"story")
is similar to concatenation however, it seems to run something like this:
var text = ["story", name, "story"];
console.log(text.join(" "));
This is pushing all of the items in the array together, separated by a space: .join(" ")
@CMS's answer is just fine, but I want to note that you can use this package: https://github.com/sindresorhus/slugify, which does it for you and covers many edge cases (i.e., German umlauts, Vietnamese, Arabic, Russian, Romanian, Turkish, etc.).
I'm not familiar with resolve, but I've used the others:
Recursive is the default for non-fast-forward merges. We're all familiar with that one.
I've used octopus when I've had several trees that needed to be merged. You see this in larger projects where many branches have had independent development and it's all ready to come together into a single head.
An octopus branch merges multiple heads in one commit as long as it can do it cleanly.
For illustration, imagine you have a project that has a master, and then three branches to merge in (call them a, b, and c).
A series of recursive merges would look like this (note that the first merge was a fast-forward, as I didn't force recursion):
However, a single octopus merge would look like this:
commit ae632e99ba0ccd0e9e06d09e8647659220d043b9
Merge: f51262e... c9ce629... aa0f25d...
Ours == I want to pull in another head, but throw away all of the changes that head introduces.
This keeps the history of a branch without any of the effects of the branch.
(Read: It is not even looked at the changes between those branches. The branches are just merged and nothing is done to the files. If you want to merge in the other branch and every time there is the question "our file version or their version" you can use git merge -X ours
)
Subtree is useful when you want to merge in another project into a subdirectory of your current project. Useful when you have a library you don't want to include as a submodule.
This is cleaner way I am doing and it just works great
if (floor(NSFoundationVersionNumber) < NSFoundationVersionNumber_iOS_8_0)
[[UIApplication sharedApplication] registerForRemoteNotificationTypes:UIRemoteNotificationTypeBadge|
UIRemoteNotificationTypeAlert| UIRemoteNotificationTypeSound];
else {
[application registerUserNotificationSettings:[UIUserNotificationSettings settingsForTypes:(UIUserNotificationTypeSound | UIUserNotificationTypeAlert | UIUserNotificationTypeBadge) categories:nil]];
[application registerForRemoteNotifications];
}
Kindly check Column ApplicationId datatype in Table aspnet_Users , ApplicationId column datatype should be uniqueidentifier .
*Your parameter order is passed wrongly , Parameter @id should be passed as first argument, but in your script it is placed in second argument..*
So error is raised..
Please refere sample script:
DECLARE @id uniqueidentifier
SET @id = NEWID()
Create Table #temp1(AppId uniqueidentifier)
insert into #temp1 values(@id)
Select * from #temp1
Drop Table #temp1
Change the <a>
tag like this:
<a href="newsletter_01.pdf" target="_blank">
You can find more about the target
attribute here.
I had a similar situation, and the following process worked for me:
In the terminal, type
vi ~/.profile
Then add this line in the file, and save
export JAVA_HOME=/Library/Java/JavaVirtualMachines/jdk<version>.jdk/Contents/Home
where version is the one on your computer, such as 1.7.0_25
Exit the editor, then type the following command make it become effective
source ~/.profile
Then type java -version to check the result
java -version
What is .profile? From:http://computers.tutsplus.com/tutorials/speed-up-your-terminal-workflow-with-command-aliases-and-profile--mac-30515
.profile file is a hidden file. It is an optional file which tells the system which commands to run when the user whose profile file it is logs in. For example, if my username is bruno and there is a .profile file in /Users/bruno/, all of its contents will be executed during the log-in procedure.
The answers mentioning canvas.width
return the internal dimensions of the canvas, i.e. those specified when creating the element:
<canvas width="500" height="200">
If you size the canvas with CSS, its DOM dimensions are accessible via .scrollWidth
and .scrollHeight
:
var canvasElem = document.querySelector('canvas');_x000D_
document.querySelector('#dom-dims').innerHTML = 'Canvas DOM element width x height: ' +_x000D_
canvasElem.scrollWidth +_x000D_
' x ' +_x000D_
canvasElem.scrollHeight_x000D_
_x000D_
var canvasContext = canvasElem.getContext('2d');_x000D_
document.querySelector('#internal-dims').innerHTML = 'Canvas internal width x height: ' +_x000D_
canvasContext.canvas.width +_x000D_
' x ' +_x000D_
canvasContext.canvas.height;_x000D_
_x000D_
canvasContext.fillStyle = "#00A";_x000D_
canvasContext.fillText("Distorted", 0, 10);
_x000D_
<p id="dom-dims"></p>_x000D_
<p id="internal-dims"></p>_x000D_
<canvas style="width: 100%; height: 123px; border: 1px dashed black">
_x000D_
You can give a function expression a name that is actually private and is only visible from inside of the function ifself:
var factorial = function myself (n) {
if (n <= 1) {
return 1;
}
return n * myself(n-1);
}
typeof myself === 'undefined'
Here myself
is visible only inside of the function itself.
You can use this private name to call the function recursively.
See 13. Function Definition
of the ECMAScript 5 spec:
The Identifier in a FunctionExpression can be referenced from inside the FunctionExpression's FunctionBody to allow the function to call itself recursively. However, unlike in a FunctionDeclaration, the Identifier in a FunctionExpression cannot be referenced from and does not affect the scope enclosing the FunctionExpression.
Please note that Internet Explorer up to version 8 doesn't behave correctly as the name is actually visible in the enclosing variable environment, and it references a duplicate of the actual function (see patrick dw's comment below).
Alternatively you could use arguments.callee
to refer to the current function:
var factorial = function (n) {
if (n <= 1) {
return 1;
}
return n * arguments.callee(n-1);
}
The 5th edition of ECMAScript forbids use of arguments.callee() in strict mode, however:
(From MDN): In normal code arguments.callee refers to the enclosing function. This use case is weak: simply name the enclosing function! Moreover, arguments.callee substantially hinders optimizations like inlining functions, because it must be made possible to provide a reference to the un-inlined function if arguments.callee is accessed. arguments.callee for strict mode functions is a non-deletable property which throws when set or retrieved.
Yes, presumably it wants the path to the javadoc
command line tool that comes with the JDK (in the bin directory, same as java
and javac
).
Eclipse should be able to find it automatically; are you perhaps running it on a JRE? That would explain the request.
You can do it via FileInfo or DirectoryInfo:
DirectoryInfo di = new DirectoryInfo("TempDir");
di.Delete(true);
And then recreate the directory
You should use Terms Query
{
"query" : {
"terms" : {
"tags" : ["c", "d"]
}
}
}
String Objects
can be checked using JSON.stringify()
trick.
var me = new String("me");
var you = new String("me");
var isEquel = JSON.stringify(me) === JSON.stringify(you);
console.log(isEquel);
_x000D_
if not exist "%USERPROFILE%\.qgis-custom\" (
mkdir "%USERPROFILE%\.qgis-custom" 2>nul
if not errorlevel 1 (
xcopy "%OSGEO4W_ROOT%\qgisconfig" "%USERPROFILE%\.qgis-custom" /s /v /e
)
)
You have it almost done. The logic is correct, just some little changes.
This code checks for the existence of the folder (see the ending backslash, just to differentiate a folder from a file with the same name).
If it does not exist then it is created and creation status is checked. If a file with the same name exists or you have no rights to create the folder, it will fail.
If everyting is ok, files are copied.
All paths are quoted to avoid problems with spaces.
It can be simplified (just less code, it does not mean it is better). Another option is to always try to create the folder. If there are no errors, then copy the files
mkdir "%USERPROFILE%\.qgis-custom" 2>nul
if not errorlevel 1 (
xcopy "%OSGEO4W_ROOT%\qgisconfig" "%USERPROFILE%\.qgis-custom" /s /v /e
)
In both code samples, files are not copied if the folder is not being created during the script execution.
EDITED - As dbenham comments, the same code can be written as a single line
md "%USERPROFILE%\.qgis-custom" 2>nul && xcopy "%OSGEO4W_ROOT%\qgisconfig" "%USERPROFILE%\.qgis-custom" /s /v /e
The code after the &&
will only be executed if the previous command does not set errorlevel. If mkdir
fails, xcopy
is not executed.
If you're getting a "Codec is experimental but experimental codecs are not enabled" error use this :
ffmpeg -i inputFile -vf "transpose=1" -c:a copy outputFile
Happened with me for some .mov file with aac audio.
More one example:
Follow:
qryAux = (from q in qryAux where
q.OrdSeq == (from pp in Sessao.Query<NameTable>() where pp.FieldPk
== q.FieldPk select pp.OrdSeq).Max() select q);
Equals:
select t.* from nametable t where t.OrdSeq =
(select max(t2.OrdSeq) from nametable t2 where t2.FieldPk= t.FieldPk)
Its a new operator for combined comparison. Similar to strcmp()
or version_compare() in behavior, but it can be used on all generic PHP values with the same semantics as <
, <=
, ==
, >=
, >
. It returns 0
if both operands are equal, 1
if the left is greater, and -1
if the right is greater. It uses exactly the same comparison rules as used by our existing comparison operators: <
, <=
, ==
, >=
and >
.
It removes whatever already-compiled files are in your project so that you can do a complete fresh rebuild.
Git can search diffs with the -S option (it's called pickaxe in the docs)
git log -S password
This will find any commit that added or removed the string password
. Here a few options:
-p
: will show the diffs. If you provide a file (-p file
), it will generate a patch for you.-G
: looks for differences whose added or removed line matches the given regexp, as opposed to -S
, which "looks for differences that introduce or remove an instance of string".--all
: searches over all branches and tags; alternatively, use --branches[=<pattern>]
or --tags[=<pattern>]
You could set both left
and right
property to 0
. This will make the div stretch to the document width, but requires that no parent element is positioned (which is not the case, seeing as #header
is position: relative;
)
#site_nav_global_primary {
position: absolute;
top: 0;
left: 0;
right: 0;
}
Demo at: http://jsfiddle.net/xWnq2/, where I removed position:relative;
from #header
I recommend using the ValueProvider property of the controller, much in the way that UpdateModel/TryUpdateModel do to extract the route, query, and form parameters required. This will keep your method signatures from potentially growing very large and being subject to frequent change. It also makes it a little easier to test since you can supply a ValueProvider to the controller during unit tests.
I had a similar issue. I needed to keep the legacy encrypted passwords (Base64/SHA-1/Random salt Encoded) as users will not want to change their passwords or re-register. However I wanted to use the BCrypt encoder moving forward too.
My solution was to write a bespoke decoder that checks to see which encryption method was used first before matching (BCrypted ones start with $
).
To get around the salt issue, I pass into the decoder a concatenated String of salt + encrypted password via my modified user object.
Decoder
@Component
public class LegacyEncoder implements PasswordEncoder {
private static final String BCRYP_TYPE = "$";
private static final PasswordEncoder BCRYPT = new BCryptPasswordEncoder();
@Override
public String encode(CharSequence rawPassword) {
return BCRYPT.encode(rawPassword);
}
@Override
public boolean matches(CharSequence rawPassword, String encodedPassword) {
if (encodedPassword.startsWith(BCRYP_TYPE)) {
return BCRYPT.matches(rawPassword, encodedPassword);
}
return sha1SaltMatch(rawPassword, encodedPassword);
}
@SneakyThrows
private boolean sha1SaltMatch(CharSequence rawPassword, String encodedPassword) {
String[] saltHash = encodedPassword.split(User.SPLIT_CHAR);
// Legacy code from old system
byte[] b64salt = Base64.getDecoder().decode(saltHash[0].getBytes());
byte[] validHash = Base64.getDecoder().decode(saltHash[1]);
byte[] checkHash = Utility.getHash(5, rawPassword.toString(), b64salt);
return Arrays.equals(checkHash, validHash);
}
}
User Object
public class User implements UserDetails {
public static final String SPLIT_CHAR = ":";
@Id
@Column(name = "user_id", nullable = false)
private Integer userId;
@Column(nullable = false, length = 60)
private String password;
@Column(nullable = true, length = 32)
private String salt;
.
.
@PostLoad
private void init() {
username = emailAddress; //To comply with UserDetails
password = salt == null ? password : salt + SPLIT_CHAR + password;
}
You can also add a hook to re-encode the password in the new BCrypt format and replace it. Thus phasing out the old method.
Conditional imports could also be achieved with a ternary and require()
s:
const logger = DEBUG ? require('dev-logger') : require('logger');
This example was taken from the ES Lint global-require docs: https://eslint.org/docs/rules/global-require
Also, a good reason to use a controller vs. link function (since they both have access to the scope, element, and attrs) is because you can pass in any available service or dependency into a controller (and in any order), whereas you cannot do that with the link function. Notice the different signatures:
controller: function($scope, $exceptionHandler, $attr, $element, $parse, $myOtherService, someCrazyDependency) {...
vs.
link: function(scope, element, attrs) {... //no services allowed
Or you can simply use PRINT
command instead of SELECT
command. Try this,
PRINT dbo.fn_HomePageSlider(9, 3025)
Use: nm --demangle <libname>.so
private static DataTable ReadFTP_CSV()
{
String ftpserver = "ftp://servername/ImportData/xxxx.csv";
FtpWebRequest reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(ftpserver));
reqFTP.Credentials = new NetworkCredential(ftpUserID, ftpPassword);
FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse();
Stream responseStream = response.GetResponseStream();
// use the stream to read file from FTP
StreamReader sr = new StreamReader(responseStream);
DataTable dt_csvFile = new DataTable();
#region Code
//Add Code Here To Loop txt or CSV file
#endregion
return dt_csvFile;
}
I hope it can help you.
I think your issue may be in the url pattern. Changing
<servlet-mapping>
<servlet-name>Register</servlet-name>
<url-pattern>/Register</url-pattern>
</servlet-mapping>
and
<form action="/Register" method="post">
may fix your problem
If Japanese people come here, please add the following lines to your ~/.vimrc
set encoding=utf-8
set fileencodings=iso-2022-jp,euc-jp,sjis,utf-8
set fileformats=unix,dos,mac
Following is an example. You can see the details http://jkssweetlife.com/configure-slf4j-working-various-logging-frameworks/ and download the full codes here.
Add following dependency to your pom if you are using maven, otherwise, just download the jar files and put on your classpath
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>1.7.7</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<version>1.7.7</version>
</dependency>
Configure log4j.properties
log4j.rootLogger=TRACE, stdout
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.Target=System.out
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d{yyyy-MM-dd'T'HH:mm:ss.SSS} %-5p [%c] - %m%n
Java example
public class Slf4jExample {
public static void main(String[] args) {
Logger logger = LoggerFactory.getLogger(Slf4jExample.class);
final String message = "Hello logging!";
logger.trace(message);
logger.debug(message);
logger.info(message);
logger.warn(message);
logger.error(message);
}
}
Chances are that you've not included the header file that declares system()
.
In order to be able to compile C++ code that uses functions which you don't (manually) declare yourself, you have to pull in the declarations. These declarations are normally stored in so-called header files that you pull into the current translation unit using the #include
preprocessor directive. As the code does not #include
the header file in which system()
is declared, the compilation fails.
To fix this issue, find out which header file provides you with the declaration of system()
and include that. As mentioned in several other answers, you most likely want to add #include <cstdlib>
Your project unable to resolve EntityFramework classes until you not added it in your project. For adding EntityFramework support you have to follow this steps: Tools->Nuget Package Manager ->Manage Nuget package for solution browse EntityFramework It shows latest stable EntityFramework version. currently 6.1.3 is latest version Install it for the selected project.
I tried the win32com way and xlwings way but I didn't get any luck. I use PyCharm and didn't see the .WorkBook option in the autocompletion for win32com. I got the -2147352567 error when I tried to pass a workbook as variable.
Then, I found a work around using vba shell to run my Python script. Write something on the XLS file you are working with when everything is done. So that Excel knows that it's time to run the VBA macro.
But the vba Application.wait function will take up 100% cpu which is wierd. Some people said that using the windows Sleep function would fix it.
Import xlsxwriter
Shell "C:\xxxxx\python.exe
C:/Users/xxxxx/pythonscript.py"
exitLoop = 0
wait for Python to finish its work.
Do
waitTime = TimeSerial(Hour(Now), Minute(Now), Second(Now) + 30)
Application.Wait waitTime
Set wb2 = Workbooks.Open("D:\xxxxx.xlsx", ReadOnly:=True)
exitLoop = wb2.Worksheets("blablabla").Cells(50, 1)
wb2.Close exitLoop
Loop While exitLoop <> 1
Call VbaScript
If you are getting that List
from a method call that you implement, then don't return null
, return an empty List
.
If you can't change the implementation then you are stuck with the null
check. If it should't be null
, then throw an exception.
I would not go for the helper method that returns an empty list because it may be useful some times but then you would get used to call it in every loop you make possibly hiding some bugs.
as explained here
With help from numpy one can calculate for example a linear fitting.
# plot the data itself
pylab.plot(x,y,'o')
# calc the trendline
z = numpy.polyfit(x, y, 1)
p = numpy.poly1d(z)
pylab.plot(x,p(x),"r--")
# the line equation:
print "y=%.6fx+(%.6f)"%(z[0],z[1])
If you have no concrete implementations of the class and the methods aren't static
whats the point of testing them? If you have a concrete class then you'll be testing those methods as part of the concrete class's public API.
I know what you are thinking "I don't want to test these methods over and over thats the reason I created the abstract class", but my counter argument to that is that the point of unit tests is to allow developers to make changes, run the tests, and analyze the results. Part of those changes could include overriding your abstract class's methods, both protected
and public
, which could result in fundamental behavioral changes. Depending on the nature of those changes it could affect how your application runs in unexpected, possibly negative ways. If you have a good unit testing suite problems arising from these types changes should be apparent at development time.
Python x.x
res = True
while res:
res = input("Please confirm with y/yes...").lower(); res = res not in {'y','yes','Y','YES',''}
"Segmentation fault (core dumped)"
is the string that Linux prints when a program exits with a SIGSEGV
signal and you have core creation enabled. This means some program has crashed.
If you're actually getting this error from running Python, this means the Python interpreter has crashed. There are only a few reasons this can happen:
You're using a third-party extension module written in C, and that extension module has crashed.
You're (directly or indirectly) using the built-in module ctypes
, and calling external code that crashes.
There's something wrong with your Python installation.
You've discovered a bug in Python that you should report.
The first is by far the most common. If your q
is an instance of some object from some third-party extension module, you may want to look at the documentation.
Often, when C modules crash, it's because you're doing something which is invalid, or at least uncommon and untested. But whether it's your "fault" in that sense or not - that doesn't matter. The module should raise a Python exception that you can debug, instead of crashing. So, you should probably report a bug to whoever wrote the extension. But meanwhile, rather than waiting 6 months for the bug to be fixed and a new version to come out, you need to figure out what you did that triggered the crash, and whether there's some different way to do what you want. Or switch to a different library.
On the other hand, since you're reading and printing out data from somewhere else, it's possible that your Python interpreter just read the line "Segmentation fault (core dumped)"
and faithfully printed what it read. In that case, some other program upstream presumably crashed. (It's even possible that nobody crashed—if you fetched this page from the web and printed it out, you'd get that same line, right?) In your case, based on your comment, it's probably the Java program that crashed.
If you're not sure which case it is (and don't want to learn how to do process management, core-file inspection, or C-level debugging today), there's an easy way to test: After print line
add a line saying print "And I'm OK"
. If you see that after the Segmentation fault
line, then Python didn't crash, someone else did. If you don't see it, then it's probably Python that's crashed.
This should work.
<!DOCTYPE html>
<html>
<head>
<title>Hello World</title>
<style>
html, body {
width: 100%;
height: 100%;
margin: 0;
padding: 0;
background-color: green;
}
#container {
width: inherit;
height: inherit;
margin: 0;
padding: 0;
background-color: pink;
}
h1 {
margin: 0;
padding: 0;
}
</style>
</head>
<body>
<div id="container">
<h1>Hello World</h1>
</div>
</body>
</html>
The background colors are there so you can see how this works. Copy this code to a file and open it in your browser. Try playing around with the CSS a bit and see what happens.
The width: inherit; height: inherit;
pulls the width and height from the parent element. This should be the default and is not truly necessary.
Try removing the h1 { ... }
CSS block and see what happens. You might notice the layout reacts in an odd way. This is because the h1
element is influencing the layout of its container. You could prevent this by declaring overflow: hidden;
on the container or the body.
I'd also suggest you do some reading on the CSS Box Model.
One-liner using the new method in .NET. Will always return x86 Program Files folder.
Environment.Is64BitOperatingSystem ? Environment.GetEnvironmentVariable("ProgramFiles(x86)") : Environment.GetEnvironmentVariable("ProgramFiles"))
In my case was by uploading an APK, that although it was signed with production certificate and was a release variant, was generated by the run play button from Android studio. Problem solved after generating APK from Gradle or from Build APK menu option.
Plese try this:
var sizeInKB = input.files[0].size/1024; //Normally files are in bytes but for KB divide by 1024 and so on
var sizeLimit= 30;
if (sizeInKB >= sizeLimit) {
alert("Max file size 30KB");
return false;
}
Onfous And onblur Text box with javascript
<input type="text" value="A new value" onfocus="if(this.value=='A new value') this.value='';" onblur="if(this.value=='') this.value='A new value';"/>
this really worked form for I am making a table using thymeleaf and inside the table there is two buttons in one form...thanks man even this thread is old it still helps me alot!
<th:block th:each="infos : ${infos}">_x000D_
<tr>_x000D_
<form method="POST">_x000D_
<td><input class="admin" type="text" name="firstName" id="firstName" th:value="${infos.firstName}"/></td>_x000D_
<td><input class="admin" type="text" name="lastName" id="lastName" th:value="${infos.lastName}"/></td>_x000D_
<td><input class="admin" type="email" name="email" id="email" th:value="${infos.email}"/></td>_x000D_
<td><input class="admin" type="text" name="passWord" id="passWord" th:value="${infos.passWord}"/></td>_x000D_
<td><input class="admin" type="date" name="birthDate" id="birthDate" th:value="${infos.birthDate}"/></td>_x000D_
<td>_x000D_
<select class="admin" name="gender" id="gender">_x000D_
<option><label th:text="${infos.gender}"></label></option>_x000D_
<option value="Male">Male</option>_x000D_
<option value="Female">Female</option>_x000D_
</select>_x000D_
</td>_x000D_
<td><select class="admin" name="status" id="status">_x000D_
<option><label th:text="${infos.status}"></label></option>_x000D_
<option value="Yes">Yes</option>_x000D_
<option value="No">No</option>_x000D_
</select>_x000D_
</td>_x000D_
<td><select class="admin" name="ustatus" id="ustatus">_x000D_
<option><label th:text="${infos.ustatus}"></label></option>_x000D_
<option value="Yes">Yes</option>_x000D_
<option value="No">No</option>_x000D_
</select>_x000D_
</td>_x000D_
<td><select class="admin" name="type" id="type">_x000D_
<option><label th:text="${infos.type}"></label></option>_x000D_
<option value="Yes">Yes</option>_x000D_
<option value="No">No</option>_x000D_
</select></td>_x000D_
<td><input class="register" id="mobileNumber" type="text" th:value="${infos.mobileNumber}" name="mobileNumber" onkeypress="return isNumberKey(event)" maxlength="11"/></td>_x000D_
<td><input class="table" type="submit" id="submit" name="submit" value="Upd" Style="color: white; background-color:navy; border-color: black;" th:formaction="@{/updates}"/></td>_x000D_
<td><input class="table" type="submit" id="submit" name="submit" value="Del" Style="color: white; background-color:navy; border-color: black;" th:formaction="@{/delete}"/></td>_x000D_
</form>_x000D_
</tr>_x000D_
</th:block>
_x000D_
import java.io.*;
import java.util.Scanner;
class ar1 {
public static void main(String[] args) {
//Scanner sc=new Scanner(System.in);
int[] a={10,20,30,40,12,32};
int bi=0,sm=0;
//bi=sc.nextInt();
//sm=sc.nextInt();
for(int i=0;i<=a.length-1;i++) {
if(a[i]>a[i+1])
bi=a[i];
if(a[i]<a[i+1])
sm=a[i];
}
System.out.println("big"+bi+"small"+sm);
}
}
There is always a reason to have a public folder in the Laravel setup, all public related stuffs should be present inside the public folder,
Don't Point your ip address/domain to the Laravel's root folder but point it to the public folder. It is unsafe pointing the server Ip to the root folder., because unless you write restrictions in
.htaccess
, one can easily access the other files.,
Just write rewrite condition in the .htaccess
file and install rewrite module and enable the rewrite module, the problem which adds public in the route will get solved.
Here's a really quick implementation of "git status":
import os
import string
from subprocess import *
repoDir = '/Users/foo/project'
def command(x):
return str(Popen(x.split(' '), stdout=PIPE).communicate()[0])
def rm_empty(L): return [l for l in L if (l and l!="")]
def getUntracked():
os.chdir(repoDir)
status = command("git status")
if "# Untracked files:" in status:
untf = status.split("# Untracked files:")[1][1:].split("\n")
return rm_empty([x[2:] for x in untf if string.strip(x) != "#" and x.startswith("#\t")])
else:
return []
def getNew():
os.chdir(repoDir)
status = command("git status").split("\n")
return [x[14:] for x in status if x.startswith("#\tnew file: ")]
def getModified():
os.chdir(repoDir)
status = command("git status").split("\n")
return [x[14:] for x in status if x.startswith("#\tmodified: ")]
print("Untracked:")
print( getUntracked() )
print("New:")
print( getNew() )
print("Modified:")
print( getModified() )
Here's the most concise way I've found (using capybara 3.3.0 and chromium driver):
all('#id-of-select option')[1].select_option
will select the 2nd option. Increment the index as needed.
With transforms being more ubiquitously supported these days, you can do this without knowing the width/height of the popup
.popup {
position: fixed;
top: 50%;
left: 50%;
-webkit-transform: translate(-50%, -50%);
transform: translate(-50%, -50%);
}
Easy! JSFiddle here: http://jsfiddle.net/LgSZV/
Update: Check out https://css-tricks.com/centering-css-complete-guide/ for a fairly exhaustive guide on CSS centering. Adding it to this answer as it seems to get a lot of eyeballs.
I just realized that Web API Client has a ParseQueryString
extension method that works on a Uri
and returns a HttpValueCollection
:
var parameters = uri.ParseQueryString();
string foo = parameters["foo"];
sql_mode
MySQL 5.7.9 or later
To add or remove a mode from sql_mode
, you can use list_add
and list_drop
functions.
To remove a mode from the current SESSION.sql_mode
, you can use one of the following:
SET SESSION sql_mode = sys.list_drop(@@SESSION.sql_mode, 'ONLY_FULL_GROUP_BY');
SET sql_mode = sys.list_drop(@@sql_mode, 'ONLY_FULL_GROUP_BY');
SET @@sql_mode = sys.list_drop(@@sql_mode, 'ONLY_FULL_GROUP_BY');
To remove a mode from the GLOBAL.sql_mode
that persists for the current runtime operation, until the service is restarted.
SET GLOBAL sql_mode = sys.list_drop(@@GLOBAL.sql_mode, 'ONLY_FULL_GROUP_BY');
MySQL 5.7.8 or prior
Since the sql_mode
value is a CSV string of modes, you would need to ensure that the string does not contain residual commas, which can be accomplished by using TRIM(BOTH ',' FROM ...)
.
To remove a mode from the sql_mode
variable, you would want to use REPLACE()
along with TRIM()
to ensure any residual commas are removed.
SET SESSION sql_mode = TRIM(BOTH ',' FROM REPLACE(@@SESSION.sql_mode, 'ONLY_FULL_GROUP_BY', ''));
SET GLOBAL sql_mode = TRIM(BOTH ',' FROM REPLACE(@@GLOBAL.sql_mode, 'ONLY_FULL_GROUP_BY', ''));
To add a mode to the sql_mode
variable, you would want to use CONCAT_WS(',', ...)
, to ensure a comma is appended with the current modes and TRIM()
to ensure any residual commas are removed.
SET SESSION sql_mode = TRIM(BOTH ',' FROM CONCAT_WS(',', 'ONLY_FULL_GROUP_BY', @@SESSION.sql_mode));
SET GLOBAL sql_mode = TRIM(BOTH ',' FROM CONCAT_WS(',', 'ONLY_FULL_GROUP_BY', @@GLOBAL.sql_mode));
NOTE: Changing the
GLOBAL
variable does not propagate to theSESSION
variable, until a new connection is established.The
GLOBAL
variable will persist until the running service is restarted.The
SESSION
variable will persist for the current connection, until the connection is closed and a new connection is established.
GLOBAL.sql_mode
Since SET sql_mode = 'ONLY_FULL_GROUP_BY';
was executed without the GLOBAL
modifier, the change only affected the current SESSION
state value, which also pertains to @@sql_mode
. To remove it and revert to the global default on server restart value, you would want to use the value from @@GLOBAL.sql_mode
. [sic]
The current
SESSION
value is only valid for the current connection. Reconnecting to the server will revert the value back to theGLOBAL
value.
To revert the current session state value to the current global value, you can use one of the following:
SET SESSION sql_mode = @@GLOBAL.sql_mode;
SET @@sql_mode = @@GLOBAL.sql_mode;
SET sql_mode = @@GLOBAL.sql_mode;
Change SESSION.sql_mode
value to ONLY_FULL_GROUP_BY
SET sql_mode = 'ONLY_FULL_GROUP_BY';
SELECT @@sql_mode, @@GLOBAL.sql_mode;
+--------------------+----------------------------------------------+
| @@sql_mode | @@GLOBAL.sql_mode |
+--------------------+----------------------------------------------+
| ONLY_FULL_GROUP_BY | NO_AUTO_VALUE_ON_ZERO,NO_ENGINE_SUBSTITUTION |
+--------------------+----------------------------------------------+
Revert the SESSION.sql_mode
value to the GLOBAL.sql_mode
value
SET sql_mode = @@GLOBAL.sql_mode;
SELECT @@sql_mode, @@GLOBAL.sql_mode;
+----------------------------------------------+----------------------------------------------+
| @@sql_mode | @@GLOBAL.sql_mode |
+----------------------------------------------+----------------------------------------------+
| NO_AUTO_VALUE_ON_ZERO,NO_ENGINE_SUBSTITUTION | NO_AUTO_VALUE_ON_ZERO,NO_ENGINE_SUBSTITUTION |
+----------------------------------------------+----------------------------------------------+
sql_mode
using the option fileTo set the SQL mode at server startup, use the
--sql-mode="modes"
option on the command line, orsql-mode="modes"
in an option file such as my.cnf (Unix operating systems) or my.ini (Windows). [sic]
Please see your version of MySQL to determine the supported and default modes.
MySQL >= 5.7.5, <= 5.7.6 default
[mysqld]
sql-mode="ONLY_FULL_GROUP_BY,STRICT_TRANS_TABLES,NO_ENGINE_SUBSTITUTION"
Please see the Option File Syntax for more information.
The syntax for specifying options in an option file is similar to command-line syntax. However, in an option file, you omit the leading two dashes from the option name and you specify only one option per line. For example,
--quick
and--host=localhost
on the command line should be specified asquick
andhost=localhost
on separate lines in an option file. To specify an option of the form--loose-opt_name
in an option file, write it asloose-opt_name
.
The value optionally can be enclosed within single quotation marks or double quotation marks, which is useful if the value contains a
#
comment character.
sql_mode
valuesSince the MySQL documentation per-version values have been removed, I have added them here for your reference.
MySQL >= 8.0.11 8.0.5 - 8.0.10 Skipped
ONLY_FULL_GROUP_BY STRICT_TRANS_TABLES NO_ZERO_IN_DATE NO_ZERO_DATE ERROR_FOR_DIVISION_BY_ZERO NO_ENGINE_SUBSTITUTION
MySQL >= 5.7.8, <= 8.0.4
ONLY_FULL_GROUP_BY STRICT_TRANS_TABLES NO_ZERO_IN_DATE NO_ZERO_DATE ERROR_FOR_DIVISION_BY_ZERO NO_AUTO_CREATE_USER NO_ENGINE_SUBSTITUTION
MySQL 5.7.7
ONLY_FULL_GROUP_BY STRICT_TRANS_TABLES NO_AUTO_CREATE_USER NO_ENGINE_SUBSTITUTION
MySQL >= 5.7.5, <= 5.7.6
ONLY_FULL_GROUP_BY STRICT_TRANS_TABLES NO_ENGINE_SUBSTITUTION
MySQL >= 5.6.6, <= 5.7.4
NO_ENGINE_SUBSTITUTION
MySQL <= 5.6.5
''
I had exactly the same problem. And this is how I could fix it.
Step 1: Turn virtualization on in BIOS settings.
Step 2: Control Panel -> "Programs" -> "Turn Windows features on or off" (under "Programs and Features") and locate "Hyper-V", uncheck, reboot.
Step 3: In Avast->Settings->Troubleshooting. Uncheck "Enable hardware-assisted virtualization" & "Enable avast self-defense module"
Final step and the main:
Go to MyPC / right click / Advanced System Settings / Advanced / In Performance click SETTINGS / Data Execution Prevention and enable DEP for all programs and services.
The last step helped me to solve this problem. Hope you too.
After trying all these "solutions", nothing work. I did some research on W3Schools before and remember there was explanation of keeping values about radio.
But it also works for the Select
option. See below for an example. Just try it out and play with it.
<?php
$example = $_POST["example"];
?>
<form method="post">
<select name="example">
<option <?php if (isset($example) && $example=="a") echo "selected";?>>a</option>
<option <?php if (isset($example) && $example=="b") echo "selected";?>>b</option>
<option <?php if (isset($example) && $example=="c") echo "selected";?>>c</option>
</select>
<input type="submit" name="submit" value="submit" />
</form>
an simple solution!
setInterval(()=>console.clear(),1500);
There actually IS a way to do this. Think about how you might use Newtonsoft JSON to deserialize an object from json. It will (or at least can) ignore missing elements and populate all the elements that it does know about.
So here's how I did it. A small code sample will follow my explanation.
Create an instance of your object from the base class and populate it accordingly.
Using the "jsonconvert" class of Newtonsoft json, serialize that object into a json string.
Now create your sub class object by deserializing with the json string created in step 2. This will create an instance of your sub class with all the properties of the base class.
This works like a charm! So.. when is this useful? Some people asked when this would make sense and suggested changing the OP's schema to accommodate the fact that you can't natively do this with class inheritance (in .Net).
In my case, I have a settings class that contains all the "base" settings for a service. Specific services have more options and those come from a different DB table, so those classes inherit the base class. They all have a different set of options. So when retrieving the data for a service, it's much easier to FIRST populate the values using an instance of the base object. One method to do this with a single DB query. Right after that, I create the sub class object using the method outlined above. I then make a second query and populate all the dynamic values on the sub class object.
The final output is a derived class with all the options set. Repeating this for additional new sub classes takes just a few lines of code. It's simple, and it uses a very tried and tested package (Newtonsoft) to make the magic work.
This example code is vb.Net, but you can easily convert to c#.
' First, create the base settings object.
Dim basePMSettngs As gtmaPayMethodSettings = gtmaPayments.getBasePayMethodSetting(payTypeId, account_id)
Dim basePMSettingsJson As String = JsonConvert.SerializeObject(basePMSettngs, Formatting.Indented)
' Create a pmSettings object of this specific type of payment and inherit from the base class object
Dim pmSettings As gtmaPayMethodAimACHSettings = JsonConvert.DeserializeObject(Of gtmaPayMethodAimACHSettings)(basePMSettingsJson)
Lawrence has given you a good answer. But if you want more control over what gets exported to where in Excel see Modules: Sample Excel Automation - cell by cell which is slow and Modules: Transferring Records to Excel with Automation You can do things such as export the recordset starting in row 2 and insert custom text in row 1. As well as any custom formatting required.
Have you seen this already? The cause seems to be a very old libpam on one of the sides, probably on that customer.
Or the links for the version might be missing : http://www.linux.org/docs/ldp/howto/Program-Library-HOWTO/shared-libraries.html
Functions and stored procedures serve separate purposes. Although it's not the best analogy, functions can be viewed literally as any other function you'd use in any programming language, but stored procs are more like individual programs or a batch script.
Functions normally have an output and optionally inputs. The output can then be used as the input to another function (a SQL Server built-in such as DATEDIFF, LEN, etc) or as a predicate to a SQL Query - e.g., SELECT a, b, dbo.MyFunction(c) FROM table
or SELECT a, b, c FROM table WHERE a = dbo.MyFunc(c)
.
Stored procs are used to bind SQL queries together in a transaction, and interface with the outside world. Frameworks such as ADO.NET, etc. can't call a function directly, but they can call a stored proc directly.
Functions do have a hidden danger though: they can be misused and cause rather nasty performance issues: consider this query:
SELECT * FROM dbo.MyTable WHERE col1 = dbo.MyFunction(col2)
Where MyFunction is declared as:
CREATE FUNCTION MyFunction (@someValue INTEGER) RETURNS INTEGER
AS
BEGIN
DECLARE @retval INTEGER
SELECT localValue
FROM dbo.localToNationalMapTable
WHERE nationalValue = @someValue
RETURN @retval
END
What happens here is that the function MyFunction is called for every row in the table MyTable. If MyTable has 1000 rows, then that's another 1000 ad-hoc queries against the database. Similarly, if the function is called when specified in the column spec, then the function will be called for each row returned by the SELECT.
So you do need to be careful writing functions. If you do SELECT from a table in a function, you need to ask yourself whether it can be better performed with a JOIN in the parent stored proc or some other SQL construct (such as CASE ... WHEN ... ELSE ... END).
listOfStuff =([a,b], [c,d], [e,f], [f,g])
for item in listOfStuff[1:3]:
print item
You have to iterate over a slice of your tuple. The 1
is the first element you need and 3
(actually 2+1) is the first element you don't need.
Elements in a list are numerated from 0:
listOfStuff =([a,b], [c,d], [e,f], [f,g])
0 1 2 3
[1:3]
takes elements 1 and 2.
That totally depends of what do you need exactly. If you just need to store and retrieve a token in order to use it in your http requests, i suggest you to simply create a service and use it in your whole project.
example of basic integration:
import {Injectable} from 'angular@core'
@Injectable()
export class TokenManager {
private tokenKey:string = 'app_token';
private store(content:Object) {
localStorage.setItem(this.tokenKey, JSON.stringify(content));
}
private retrieve() {
let storedToken:string = localStorage.getItem(this.tokenKey);
if(!storedToken) throw 'no token found';
return storedToken;
}
public generateNewToken() {
let token:string = '...';//custom token generation;
let currentTime:number = (new Date()).getTime() + ttl;
this.store({ttl: currentTime, token});
}
public retrieveToken() {
let currentTime:number = (new Date()).getTime(), token = null;
try {
let storedToken = JSON.parse(this.retrieve());
if(storedToken.ttl < currentTime) throw 'invalid token found';
token = storedToken.token;
}
catch(err) {
console.error(err);
}
return token;
}
}
However if you need to use the local storage more often, by using the stored values in your app views for example. You can use one of the libraries that provides a wrapper of the webstorages like you did with angular2-localstorage.
I created some months ago ng2-webstorage that should respond to your needs. It provides two ng2 services and two decorators to sync the webstorage's values and the service/component's attributes.
import {Component} from '@angular/core';
import {LocalStorageService, LocalStorage} from 'ng2-webstorage';
@Component({
selector: 'foo',
template: `
<section>{{boundValue}}</section>
<section><input type="text" [(ngModel)]="attribute"/></section>
<section><button (click)="saveValue()">Save</button></section>
`,
})
export class FooComponent {
@LocalStorage()
boundValue; // attribute bound to the localStorage
value;
constructor(private storage:LocalStorageService) {
this.localSt.observe('boundValue')// triggers the callback each time a new value is set
.subscribe((newValue) => console.log('new value', newValue));
}
saveValue() {
this.storage.store('boundValue', this.value); // store the given value
}
}
In short it's because:
Floating point numbers cannot represent all decimals precisely in binary
So just like 3/10 which does not exist in base 10 precisely (it will be 3.33... recurring), in the same way 1/10 doesn't exist in binary.
So what? How to deal with it? Is there any workaround?
In order to offer The best solution I can say I discovered following method:
parseFloat((0.1 + 0.2).toFixed(10)) => Will return 0.3
Let me explain why it's the best solution. As others mentioned in above answers it's a good idea to use ready to use Javascript toFixed() function to solve the problem. But most likely you'll encounter with some problems.
Imagine you are going to add up two float numbers like 0.2
and 0.7
here it is: 0.2 + 0.7 = 0.8999999999999999
.
Your expected result was 0.9
it means you need a result with 1 digit precision in this case.
So you should have used (0.2 + 0.7).tofixed(1)
but you can't just give a certain parameter to toFixed() since it depends on the given number, for instance
0.22 + 0.7 = 0.9199999999999999
In this example you need 2 digits precision so it should be toFixed(2)
, so what should be the paramter to fit every given float number?
You might say let it be 10 in every situation then:
(0.2 + 0.7).toFixed(10) => Result will be "0.9000000000"
Damn! What are you going to do with those unwanted zeros after 9? It's the time to convert it to float to make it as you desire:
parseFloat((0.2 + 0.7).toFixed(10)) => Result will be 0.9
Now that you found the solution, it's better to offer it as a function like this:
function floatify(number){
return parseFloat((number).toFixed(10));
}
Let's try it yourself:
function floatify(number){
return parseFloat((number).toFixed(10));
}
function addUp(){
var number1 = +$("#number1").val();
var number2 = +$("#number2").val();
var unexpectedResult = number1 + number2;
var expectedResult = floatify(number1 + number2);
$("#unexpectedResult").text(unexpectedResult);
$("#expectedResult").text(expectedResult);
}
addUp();
_x000D_
input{
width: 50px;
}
#expectedResult{
color: green;
}
#unexpectedResult{
color: red;
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="number1" value="0.2" onclick="addUp()" onkeyup="addUp()"/> +
<input id="number2" value="0.7" onclick="addUp()" onkeyup="addUp()"/> =
<p>Expected Result: <span id="expectedResult"></span></p>
<p>Unexpected Result: <span id="unexpectedResult"></span></p>
_x000D_
You can use it this way:
var x = 0.2 + 0.7;
floatify(x); => Result: 0.9
As W3SCHOOLS suggests there is another solution too, you can multiply and divide to solve the problem above:
var x = (0.2 * 10 + 0.1 * 10) / 10; // x will be 0.3
Keep in mind that (0.2 + 0.1) * 10 / 10
won't work at all although it seems the same!
I prefer the first solution since I can apply it as a function which converts the input float to accurate output float.
var_dump
displays structured information about the object / variable. This includes type and values. Like print_r
arrays are recursed through and indented.
print_r
displays human readable information about the values with a format presenting keys and elements for arrays and objects.
The most important thing to notice is var_dump
will output type as well as values while print_r
does not.
I defined a median function for a list of numbers as
def median(numbers):
return (sorted(numbers)[int(round((len(numbers) - 1) / 2.0))] + sorted(numbers)[int(round((len(numbers) - 1) // 2.0))]) / 2.0
It's a GNU extension. In a nutshell it's a convenient way to declare an object having the same type as another. For example:
int x; /* Plain old int variable. */
typeof(x) y; /* Same type as x. Plain old int variable. */
It works entirely at compile-time and it's primarily used in macros. One famous example of macro relying on typeof
is container_of
.
You cannot open Java Applets (nor any other NPAPI plugin) in Microsoft Edge - they aren't supported and won't be added in the future.
Further you should be aware that in the next release of Google Chrome (v45 - due September 2015) NPAPI plugins will also no longer be supported.
There are a couple of things that you can do:
Use Internet Explorer 11
You will find that in Windows 10 you will already have Internet Explorer 11 installed. IE 11 continues to support NPAPI (incl Java Applets).
IE11 is squirrelled away (c:\program files\internet explorer\iexplore.exe
). Just pin this exe to your task bar for easy access.
Use FireFox
You can also install and use a Firefox 32-bit Extended Support Release in Win10. Firefox have disabled NPAPI by default, but this can be overridden. This will only be supported until early 2018.
Use an extension method with method chaining.
public static List<T> WithItems(this List<T> list, params T[] items)
{
list.AddRange(items);
return list;
}
This would let you do this:
List<string> strings = new List<string>().WithItems("Yes");
or
List<string> strings = new List<string>().WithItems("Yes", "No", "Maybe So");
Update
You can now use list initializers:
var strings = new List<string> { "This", "That", "The Other" };
See http://msdn.microsoft.com/en-us/library/bb384062(v=vs.90).aspx
My 2 cents: Compile against any version of the SDK but take care not to call any APIs that your "minimum SDK version" does not support. That means you "could" compile against the latest version of the SDK.
As for "target version" it simply refers to what you planned to target in the first place and have possibly tested against. If you haven't done the due diligence then this is the way to inform Android that it needs to perform some additional checks before it deploys your lets say "Lollipop" targeted app on "Oreo".
So the "target version" is obviously not lower than your "minimum SDK version" but it can't be higher than your "compiled version".
The method [collectionView visibleCells] give you all visibleCells array you want. Use it when you want to get
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView{
for (UICollectionViewCell *cell in [self.mainImageCollection visibleCells]) {
NSIndexPath *indexPath = [self.mainImageCollection indexPathForCell:cell];
NSLog(@"%@",indexPath);
}
}
Update to Swift 5:
func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
for cell in yourCollectionView.visibleCells {
let indexPath = yourCollectionView.indexPath(for: cell)
print(indexPath)
}
}
From a command prompt using OSQL:
OSQL -E -d <*databasename*> -Q "exec sp_msforeachtable 'sp_spaceused [?]'" > result.txt
To edit Date in oracle you can try
select to_char(<columnName> + 5 / 24 + 30 / (24 * 60),
'DD/MM/RRRR hh:mi AM') AS <logicalName> from <tableName>
You can do an enhanced for loop (for java 5 and higher) for iteration on array's elements:
String[] elements = {"a", "a", "a", "a"};
for (String s: elements) {
//Do your stuff here
System.out.println(s);
}
NOTE: I wrote this answer in Jun 2013, so it's bit dated nowadays. Many things changed in Android platform since version 6 (Marshmallow, released late 2015), making the whole problem more/less obsolete. However I believe this post can still be worth reading as general problem analysis approach example.
Exception you are getting (SecurityException: Permission denied (missing INTERNET permission?)
), clearly indicates that you are not allowed to do networking. That's pretty indisputable fact. But how can this happen? Usually it's either due to missing <uses-permission android:name="android.permission.INTERNET" />
entry in your AndroidManifest.xml
file or, as internet permission is granted at installation not at run time, by long standing, missed bug in Android framework that causes your app to be successfully installed, but without expected permission grant.
My Manifest is correct, so how can this happen?
Theoretically, presence of uses-permission
in Manifest perfectly fulfills the requirement and from developer standpoint is all that's needed to be done to be able to do networking. Moreover, since permissions are shown to the user during installation, the fact your app ended installed on user's device means s/he granted what you asked for (otherwise installation is cancelled), so assumption that if your code is executed then all requested permissions are granted is valid. And once granted, user cannot revoke the permission other way than uninstalling the app completely as standard Android framework (from AOSP) offers no such feature at the moment.
But things are getting more tricky if you also do not mind your app running on rooted devices too. There're tools available in Google Play your users can install to control permission granted to installed apps at run-time - for example: Permissions Denied and others. This can also be done with CyanogenMod, vendor brand (i.e. LG's) or other custom ROM, featuring various type of "privacy managers" or similar tools.
So if app is blocked either way, it's basically blocked intentionally by the user and if so, it is really more user problem in this case (or s/he do not understand what certain options/tools really do and what would be the consequences) than yours, because standard SDK (and most apps are written with that SDK in mind) simply does not behave that way. So I strongly doubt this problem occurs on "standard", non-rooted device with stock (or vendor like Samsung, HTC, Sony etc) ROM.
I do not want to crash...
Properly implemented permission management and/org blocking must deal with the fact that most apps may not be ready for the situation where access to certain features is both granted and not accessible at the same time, as this is kind of contradiction where app uses manifest to request access at install time. Access control done right should must make all things work as before, and still limit usability using techniques in scope of expected behavior of the feature. For example, when certain permission is granted (i.e. GPS, Internet access) such feature can be made available from the app/user perspective (i.e. you can turn GPS on. or try to connect), the altered implementation can provide no real data - i.e. GPS can always return no coordinates, like when you are indoor or have no satellite "fix". Internet access can granted as before, but you can make no successful connection as there's no data coverage or routing. Such scenarios should be expected in normal usage as well, therefore it should be handled by the apps already. As this simply can happen during normal every day usage, any crash in such situation should be most likely be related to application bugs.
We lack too much information about the environment on which this problem occurs to diagnose problem w/o guessing, but as kind of solution, you may consider using setDefaultUncaughtExceptionHandler() to catch such unexpected exceptions in future and i.e. simply show user detailed information what permission your app needs instead of just crashing. Please note that using this will most likely conflict with tools like Crittercism, ACRA and others, so be careful if you use any of these.
Notes
Please be aware that android.permission.INTERNET
is not the only networking related permission you may need to declare in manifest in attempt to successfully do networking. Having INTERNET
permission granted simply allows applications to open network sockets (which is basically fundamental requirement to do any network data transfer). But in case your network stack/library would like to get information about networks as well, then you will also need android.permission.ACCESS_NETWORK_STATE
in your Manifest (which is i.e. required by HttpUrlConnection client (see tutorial).
Addendum (2015-07-16)
Please note that Android 6 (aka Marshmallow) introduced completely new permission management mechanism called Runtime Permissions. It gives user more control on what permission are granted (also allows selective grant) or lets one revoke already granted permissions w/o need to app removal:
This [...] introduces a new permissions model, where users can now directly manage app permissions at runtime. This model gives users improved visibility and control over permissions, while streamlining the installation and auto-update processes for app developers. Users can grant or revoke permissions individually for installed apps.
However, the changes do not affect INTERNET
or ACCESS_NETWORK_STATE
permissions, which are considered "Normal" permissions. The user does not need to explicitly grant these permission.
See behavior changes description page for details and make sure your app will behave correctly on newer systems too. It's is especially important when your project set targetSdk
to at least 23
as then you must support new permissions model (detailed documentation). If you are not ready, ensure you keep targetSdk
to at most 22
as this ensures even new Android will use old permission system when your app is installed.