In my case I had another project open in IntelliJ, and had Tomcat running in debug mode in that project. Stopping that instance of Tomcat resolved the issue.
You could subclass str
and create your own case-insenstive string class but IMHO that would be extremely unwise and create far more trouble than it's worth.
I'm working on an open-source project called Todoc which analyzes words to produce proper documentation output automatically when saving a file. It respects existing comments and is really fast and fluid.
Maybe your code is missing this line from the Microsoft example:
MyDataAdapter.SelectCommand.CommandType = CommandType.StoredProcedure
Not sure its faster with VBA - the fastest way to do it in the normal Excel programm would be:
Ctrl-G
A1:X50 Enter
Delete
Unless you have to do this very often, entering and then triggering the VBAcode is more effort.
And in case you only want to delete formulas or values, you can insert Ctrl-G, Alt-S
to select Goto Special and here select Formulas or Values.
The difference is that raw_input()
does not exist in Python 3.x, while input()
does. Actually, the old raw_input()
has been renamed to input()
, and the old input()
is gone, but can easily be simulated by using eval(input())
. (Remember that eval()
is evil. Try to use safer ways of parsing your input if possible.)
After uncommenting disable_overscan=1 follow my lead. In the link, http://elinux.org/RPiconfig when you search for Video options, you'll also get hdmi_group and hdmi_mode. For, hdmi_group choose 1 if you're using you TV as an video output or choose 2 for monitors. Then in hdmi_mode, you can select the resolution you want from the list. I chose :- hdmi_group=2 hdmi_mode=23 And it worked.
function htmlEscape(str) {
var stringval="";
$.each(str, function (i, element) {
alert(element);
stringval += element
.replace(/&/g, '&')
.replace(/"/g, '"')
.replace(/'/g, ''')
.replace(/</g, '<')
.replace(/>/g, '>')
.replace(' ', '-')
.replace('?', '-')
.replace(':', '-')
.replace('|', '-')
.replace('.', '-');
});
alert(stringval);
return String(stringval);
}
In my case, I had two of three projects with this problem in my current workspace. I opened workspace catalog and made a backup of corrupted projects, deleted them afterwards. Then opened eclipse once again. Obviously there was missing data to work with. Closed eclipse once again and added back earlier saved projects without metadata catalogs.
TL;DR. Just remove metadata catalogs from projects in your workspace.
CDATA is a better general solution.
$scope.$watch('age + name', function () {
//called when name or age changed
});
Go to run : ctrl + R
Type : %temp%
delete All files & folders
Rebuild Project.
done!
Since :last-child
is a CSS3 pseudo-class, it is not supported in IE8. I believe :first-child
is supported, as it's defined in the CSS2.1 specification.
One possible solution is to simply give the last child a class name and style that class.
Another would be to use JavaScript. jQuery makes this particularly easy as it provides a :last-child
pseudo-class which should work in IE8. Unfortunately, that could result in a flash of unstyled content while the DOM loads.
To sort a 1D vector or a single column of data, just call the sort function and pass in your sequence.
On the other hand, the order function is necessary to sort data two-dimensional data--i.e., multiple columns of data collected in a matrix or dataframe.
Stadium Home Week Qtr Away Off Def Result Kicker Dist
751 Out PHI 14 4 NYG PHI NYG Good D.Akers 50
491 Out KC 9 1 OAK OAK KC Good S.Janikowski 32
702 Out OAK 15 4 CLE CLE OAK Good P.Dawson 37
571 Out NE 1 2 OAK OAK NE Missed S.Janikowski 43
654 Out NYG 11 2 PHI NYG PHI Good J.Feely 26
307 Out DEN 14 2 BAL DEN BAL Good J.Elam 48
492 Out KC 13 3 DEN KC DEN Good L.Tynes 34
691 Out NYJ 17 3 BUF NYJ BUF Good M.Nugent 25
164 Out CHI 13 2 GB CHI GB Good R.Gould 25
80 Out BAL 1 2 IND IND BAL Good M.Vanderjagt 20
Here is an excerpt of data for field goal attempts in the 2008 NFL season, a dataframe i've called 'fg'. suppose that these 10 data points represent all of the field goals attempted in 2008; further suppose you want to know the the distance of the longest field goal attempted that year, who kicked it, and whether it was good or not; you also want to know the second-longest, as well as the third-longest, etc.; and finally you want the shortest field goal attempt.
Well, you could just do this:
sort(fg$Dist, decreasing=T)
which returns: 50 48 43 37 34 32 26 25 25 20
That is correct, but not very useful--it does tell us the distance of the longest field goal attempt, the second-longest,...as well as the shortest; however, but that's all we know--eg, we don't know who the kicker was, whether the attempt was successful, etc. Of course, we need the entire dataframe sorted on the "Dist" column (put another way, we want to sort all of the data rows on the single attribute Dist. that would look like this:
Stadium Home Week Qtr Away Off Def Result Kicker Dist
751 Out PHI 14 4 NYG PHI NYG Good D.Akers 50
307 Out DEN 14 2 BAL DEN BAL Good J.Elam 48
571 Out NE 1 2 OAK OAK NE Missed S.Janikowski 43
702 Out OAK 15 4 CLE CLE OAK Good P.Dawson 37
492 Out KC 13 3 DEN KC DEN Good L.Tynes 34
491 Out KC 9 1 OAK OAK KC Good S.Janikowski 32
654 Out NYG 11 2 PHI NYG PHI Good J.Feely 26
691 Out NYJ 17 3 BUF NYJ BUF Good M.Nugent 25
164 Out CHI 13 2 GB CHI GB Good R.Gould 25
80 Out BAL 1 2 IND IND BAL Good M.Vanderjagt 20
This is what order does. It is 'sort' for two-dimensional data; put another way, it returns a 1D integer index comprised of the row numbers such that sorting the rows according to that vector, would give you a correct row-oriented sort on the column, Dist
Here's how it works. Above, sort was used to sort the Dist column; to sort the entire dataframe on the Dist column, we use 'order' exactly the same way as 'sort' is used above:
ndx = order(fg$Dist, decreasing=T)
(i usually bind the array returned from 'order' to the variable 'ndx', which stands for 'index', because i am going to use it as an index array to sort.)
that was step 1, here's step 2:
'ndx', what is returned by 'sort' is then used as an index array to re-order the dataframe, 'fg':
fg_sorted = fg[ndx,]
fg_sorted is the re-ordered dataframe immediately above.
In sum, 'sort' is used to create an index array (which specifies the sort order of the column you want sorted), which then is used as an index array to re-order the dataframe (or matrix).
If you provider does not support Invoke and you need to combine two expression, you can use an ExpressionVisitor to replace the parameter in the second expression by the parameter in the first expression.
class ParameterUpdateVisitor : ExpressionVisitor
{
private ParameterExpression _oldParameter;
private ParameterExpression _newParameter;
public ParameterUpdateVisitor(ParameterExpression oldParameter, ParameterExpression newParameter)
{
_oldParameter = oldParameter;
_newParameter = newParameter;
}
protected override Expression VisitParameter(ParameterExpression node)
{
if (object.ReferenceEquals(node, _oldParameter))
return _newParameter;
return base.VisitParameter(node);
}
}
static Expression<Func<T, bool>> UpdateParameter<T>(
Expression<Func<T, bool>> expr,
ParameterExpression newParameter)
{
var visitor = new ParameterUpdateVisitor(expr.Parameters[0], newParameter);
var body = visitor.Visit(expr.Body);
return Expression.Lambda<Func<T, bool>>(body, newParameter);
}
[TestMethod]
public void ExpressionText()
{
string text = "test";
Expression<Func<Coco, bool>> expr1 = p => p.Item1.Contains(text);
Expression<Func<Coco, bool>> expr2 = q => q.Item2.Contains(text);
Expression<Func<Coco, bool>> expr3 = UpdateParameter(expr2, expr1.Parameters[0]);
var expr4 = Expression.Lambda<Func<Recording, bool>>(
Expression.OrElse(expr1.Body, expr3.Body), expr1.Parameters[0]);
var func = expr4.Compile();
Assert.IsTrue(func(new Coco { Item1 = "caca", Item2 = "test pipi" }));
}
Applications that require intensive memory access eg. image manipulation are usually better off written in unmanaged environment (C++) than managed (C#). Optimized inner loops with pointer arithmetics are much easier to have control of in C++. In C# you might need to resort to unsafe code to even get near the same performance.
This works. Tested.
.popover {
top: 71px !important;
left: 379px !important;
}
XML is so versatile...
<DATA>
<BINARY>
<BIT index="0">0</BIT>
<BIT index="1">0</BIT>
<BIT index="2">1</BIT>
...
<BIT index="n">1</BIT>
</BINARY>
</DATA>
XML is like violence - If it doesn't solve your problem, you're not using enough of it.
EDIT:
BTW: Base64 + CDATA is probably the best solution
(EDIT2:
Whoever upmods me, please also upmod the real answer. We don't want any poor soul to come here and actually implement my method because it was the highest ranked on SO, right?)
function something_cool(text, callback){
alert(text);
if(typeof(callback)=='function'){
callback();
};
}
Do you have installed the android plugin ?
Your project must be of the android type.
I use this, it works fine.
from django.utils import simplejson
from django.http import HttpResponse
def some_view(request):
to_json = {
"key1": "value1",
"key2": "value2"
}
return HttpResponse(simplejson.dumps(to_json), mimetype='application/json')
Alternative:
from django.utils import simplejson
class JsonResponse(HttpResponse):
"""
JSON response
"""
def __init__(self, content, mimetype='application/json', status=None, content_type=None):
super(JsonResponse, self).__init__(
content=simplejson.dumps(content),
mimetype=mimetype,
status=status,
content_type=content_type,
)
In Django 1.7 JsonResponse objects have been added to the Django framework itself which makes this task even easier:
from django.http import JsonResponse
def some_view(request):
return JsonResponse({"key": "value"})
If you're doing it via CMD as you say, then you can just enter the command like so:
path\to\your.exe
which will open it within the same window. For example in C++:
system("path\\to\\your.exe"); // Double backslash for escaping
will open your.exe
in the current CMD window. Likewise to start with a new window, just go for:
system("start path\\to\\your.exe");
If you go for the first option, you would have to clear your screen unless you wanted to have the command to open your.exe
on the screen still.
I got a silly error it took me an embarrassingly long to solve.... Check out my pom.xml ...
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.outbottle</groupId>
<artifactId>PersonalDetailsMVC</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>war</packaging>
<name>PersonalDetailsMVC</name>
<properties>
<endorsed.dir>${project.build.directory}/endorsed</endorsed.dir>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<spring.version>4.0.1.RELEASE</spring.version>
<jstl.version>1.2</jstl.version>
<javax.servlet.version>3.0.1</javax.servlet.version>
</properties>
<dependencies>
<dependency>
<groupId>javax</groupId>
<artifactId>javaee-web-api</artifactId>
<version>7.0</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>${javax.servlet.version}</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>jstl</groupId>
<artifactId>jstl</artifactId>
<version>${jstl.version}</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.1</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
<compilerArguments>
<endorseddirs>${endorsed.dir}</endorseddirs>
</compilerArguments>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-war-plugin</artifactId>
<version>2.3</version>
<configuration>
<failOnMissingWebXml>false</failOnMissingWebXml>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-dependency-plugin</artifactId>
<version>2.6</version>
<executions>
<execution>
<phase>validate</phase>
<goals>
<goal>copy</goal>
</goals>
<configuration>
<outputDirectory>${endorsed.dir}</outputDirectory>
<silent>true</silent>
<artifactItems>
<artifactItem>
<groupId>javax</groupId>
<artifactId>javaee-endorsed-api</artifactId>
<version>7.0</version>
<type>jar</type>
</artifactItem>
</artifactItems>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
Problem was my package name. It MUST be "com.outbottle" (then config/controllers/model/etc) for it to work. As you can see above, I used Maven (for the first time), Spring, 1.8 JDK and nearly had a stroke debugging this issue. All running on Glassfish (Tomcat is ok too for the above pom config). That said, I'm all happy with myself now and know Maven and Spring much better for the next step of my Spring learning curve. Hoping this helps you also!
I was able to call my callback function at minimum of 250ms using audio tag and handling its ontimeupdate event. Its called 3-4 times in a second. Its better than one second lagging setTimeout
$http
service returns a promise
which has two callback methods as shown below.
$http({method: 'GET', url: '/someUrl'}).
success(function(data, status, headers, config) {
var anchor = angular.element('<a/>');
anchor.attr({
href: 'data:attachment/csv;charset=utf-8,' + encodeURI(data),
target: '_blank',
download: 'filename.csv'
})[0].click();
}).
error(function(data, status, headers, config) {
// handle error
});
We can use
params.require(:person).permit(:name, :age)
where person is Model, you can pass this code on a method person_params & use in place of params[:person] in create method or else method
Try binding your DataGridView
to the DefaultView
of the DataTable
:
dataGridView1.DataSource = table.DefaultView;
ephemeral is just another name of root volume when you launch Instance from AMI backed from Amazon EC2 instance store
So Everything will be stored on ephemeral.
if you have launched your instance from AMI backed by EBS volume then your instance does not have ephemeral.
Put the following code in your CSS file:
table {
font-size: inherit;
}
If your Session instance is null and your in an 'ashx' file, just implement the 'IRequiresSessionState' interface.
This interface doesn't have any members so you just need to add the interface name after the class declaration (C#):
public class MyAshxClass : IHttpHandler, IRequiresSessionState
Readonly textbox in Asp.net
<asp:TextBox ID="t" runat="server" Style="margin-left: 20px; margin-top: 24px;"
Width="335px" Height="41px" ReadOnly="true"></asp:TextBox>
For all the issue related to KeyBoard just use IQKeyBoardManager it's helpful. https://github.com/hackiftekhar/IQKeyboardManager.
Knowing the user id the URL for their profile picture is:-
http://graph.facebook.com/[UID]/picture
where in place of [UID] you place your $uid variable, and that URL can be passed to flash
URL url = new URL(yourUrl, "/api/v1/status.xml");
According to the javadocs this constructor just appends whatever resource to the end of your domain, so you would want to create 2 urls:
URL domain = new URL("http://example.com");
URL url = new URL(domain + "/files/resource.xml");
Sources: http://docs.oracle.com/javase/6/docs/api/java/net/URL.html
The main problem was that you were opening/closing files repeatedly inside your loop.
Try this approach:
with open('new.txt') as text_file, open('xyz.txt', 'w') as myfile:
for line in text_file:
var1, var2 = line.split(",");
myfile.write(var1+'\n')
We open both files at once and because we are using with
they will be automatically closed when we are done (or an exception occurs). Previously your output file was repeatedly openend inside your loop.
We are also processing the file line-by-line, rather than reading all of it into memory at once (which can be a problem when you deal with really big files).
Note that write()
doesn't append a newline ('\n'
) so you'll have to do that yourself if you need it (I replaced your writelines()
with write()
as you are writing a single item, not a list of items).
When opening a file for r
read, the 'r'
is optional since it's the default mode.
SHA is a family of "Secure Hash Algorithms" that have been developed by the National Security Agency. There is currently a competition among dozens of options for who will become SHA-3, the new hash algorithm for 2012+.
You use SHA functions to take a large document and compute a "digest" (also called "hash") of the input. It's important to realize that this is a one-way process. You can't take a digest and recover the original document.
AES, the Advanced Encryption Standard is a symmetric block algorithm. This means that it takes 16 byte blocks and encrypts them. It is "symmetric" because the key allows for both encryption and decryption.
UPDATE: Keccak was named the SHA-3 winner on October 2, 2012.
You can accomplish this with a slightly different syntax:
ng-class="{'approved': selectedForApproval.indexOf(jobSet) === -1}"
For Mongo version > 2.2, add a field multi and set it to true
db.Collection.update({query},
{$set: {field1: "f1", field2: "f2"}},
{multi: true })
How about:
import java.io.File;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;
import org.w3c.dom.NodeList;
public class Demo {
public static void main(String[] args) throws Exception {
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document document = db.parse(new File("input.xml"));
NodeList nodeList = document.getElementsByTagName("Item");
for(int x=0,size= nodeList.getLength(); x<size; x++) {
System.out.println(nodeList.item(x).getAttributes().getNamedItem("name").getNodeValue());
}
}
}
In case of springboot app on tomcat, I needed to create an additional class as below and this worked:
@SpringBootApplication
public class SpringBootTomcatApplication extends SpringBootServletInitializer {
}
In WPF
apps This code working perfectly
private void txt1_KeyDown(object sender, KeyEventArgs e)
{
if (Keyboard.IsKeyDown(Key.Enter) )
{
Button_Click(this, new RoutedEventArgs());
}
}
Colin is correct that a profile should be used. However, his answer hard-codes the target directory in the profile. An alternate solution would be to add a profile like this:
<profile>
<id>alternateBuildDir</id>
<activation>
<property>
<name>alt.build.dir</name>
</property>
</activation>
<build>
<directory>${alt.build.dir}</directory>
</build>
</profile>
Doing so would have the effect of changing the build directory to whatever is given by the alt.build.dir property, which can be given in a POM, in the user's settings, or on the command line. If the property is not present, the compilation will happen in the normal target directory.
R.color.red
is an ID (which is also an int
), but is not a color.
Use one of the following instead:
// If you're in an activity:
Button11.setBackgroundColor(getResources().getColor(R.color.red));
// OR, if you're not:
Button11.setBackgroundColor(Button11.getContext().getResources().getColor(R.color.red));
Or, alternatively:
Button11.setBackgroundColor(Color.RED); // From android.graphics.Color
Or, for more pro skills:
Button11.setBackgroundColor(0xFFFF0000); // 0xAARRGGBB
Here is a solution with shell parameter expansion that replaces multiple contiguous occurrences with a single _
:
$ var=AxxBCyyyDEFzzLMN
$ echo "${var//+([xyz])/_}"
A_BC_DEF_LMN
Notice that the +(pattern)
pattern requires extended pattern matching, turned on with
shopt -s extglob
Alternatively, with the -s
("squeeze") option of tr
:
$ tr -s xyz _ <<< "$var"
A_BC_DEF_LMN
Try this:
TO_DATE('2011-07-28T23:54:14Z', 'YYYY-MM-DD"T"HH24:MI:SS"Z"')
Was trying one of the same scenario but found one different and simple solution to convert JSONArray into List.
import java.lang.reflect.Type;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
String jsonStringArray = "[\"JSON\",\"To\",\"Java\"]";
//creating Gson instance to convert JSON array to Java array
Gson converter = new Gson();
Type type = new TypeToken<List<String>>(){}.getType();
List<String> list = converter.fromJson(jsonStringArray, type );
Give a try
if(MyGuid!=Guild.Empty)
{
//Valid Guild
}
else {
// Invalid Guild
}
git reset
is all about moving HEAD
, and generally the branch ref.
Question: what about the working tree and index?
When employed with --soft
, moves HEAD
, most often updating the branch ref, and only the HEAD
.
This differ from commit --amend
as:
commit --amend
is only about not moving HEAD, while allowing to redo the current commit)Just found this example of combining:
all into one (octopus, since there is more than two branches merged) commit merge.
Tomas "wereHamster" Carnecky explains in his "Subtree Octopus merge" article:
- The subtree merge strategy can be used if you want to merge one project into a subdirectory of another project, and the subsequently keep the subproject up to date. It is an alternative to git submodules.
- The octopus merge strategy can be used to merge three or more branches. The normal strategy can merge only two branches and if you try to merge more than that, git automatically falls back to the octopus strategy.
The problem is that you can choose only one strategy. But I wanted to combine the two in order to get a clean history in which the whole repository is atomically updated to a new version.
I have a superproject, let's call it
projectA
, and a subproject,projectB
, that I merged into a subdirectory ofprojectA
.
(that's the subtree merge part)
I'm also maintaining a few local commits.
ProjectA
is regularly updated,projectB
has a new version every couple days or weeks and usually depends on a particular version ofprojectA
.When I decide to update both projects, I don't simply pull from
projectA
andprojectB
as that would create two commits for what should be an atomic update of the whole project.
Instead, I create a single merge commit which combinesprojectA
,projectB
and my local commits.
The tricky part here is that this is an octopus merge (three heads), butprojectB
needs to be merged with the subtree strategy. So this is what I do:
# Merge projectA with the default strategy:
git merge projectA/master
# Merge projectB with the subtree strategy:
git merge -s subtree projectB/master
Here the author used a reset --hard
, and then read-tree
to restore what the first two merges had done to the working tree and index, but that is where reset --soft
can help:
How to I redo those two merges, which have worked, i.e. my working tree and index are fine, but without having to record those two commits?
# Move the HEAD, and just the HEAD, two commits back!
git reset --soft HEAD@{2}
Now, we can resume Tomas's solution:
# Pretend that we just did an octopus merge with three heads:
echo $(git rev-parse projectA/master) > .git/MERGE_HEAD
echo $(git rev-parse projectB/master) >> .git/MERGE_HEAD
# And finally do the commit:
git commit
So, each time:
git reset --soft
is the answer.
public boolean compareMap(Map<String, String> map1, Map<String, String> map2) {
if (map1 == null || map2 == null)
return false;
for (String ch1 : map1.keySet()) {
if (!map1.get(ch1).equalsIgnoreCase(map2.get(ch1)))
return false;
}
for (String ch2 : map2.keySet()) {
if (!map2.get(ch2).equalsIgnoreCase(map1.get(ch2)))
return false;
}
return true;
}
In Python, lambda is a keyword used to define anonymous functions(functions with no name) and that's why they are known as lambda functions.
Basically it is used for defining anonymous functions that can/can't take argument(s) and returns value of data/expression. Let's see an example.
>>> # Defining a lambda function that takes 2 parameters(as integer) and returns their sum
...
>>> lambda num1, num2: num1 + num2
<function <lambda> at 0x1004b5de8>
>>>
>>> # Let's store the returned value in variable & call it(1st way to call)
...
>>> addition = lambda num1, num2: num1 + num2
>>> addition(62, 5)
67
>>> addition(1700, 29)
1729
>>>
>>> # Let's call it in other way(2nd way to call, one line call )
...
>>> (lambda num1, num2: num1 + num2)(120, 1)
121
>>> (lambda num1, num2: num1 + num2)(-68, 2)
-66
>>> (lambda num1, num2: num1 + num2)(-68, 2**3)
-60
>>>
Now let me give an answer of your 2nd question. The 1st answer is also great. This is my own way to explain with another example.
Suppose we have a list of items(integers and strings with numeric contents) as follows,
nums = ["2", 1, 3, 4, "5", "8", "-1", "-10"]
and I want to sort it using sorted() function, lets see what happens.
>>> nums = ["2", 1, 3, 4, "5", "8", "-1", "-10"]
>>> sorted(nums)
[1, 3, 4, '-1', '-10', '2', '5', '8']
>>>
It didn't give me what I expected as I wanted like below,
['-10', '-1', 1, '2', 3, 4, '5', '8']
It means we need some strategy(so that sorted could treat our string items as an ints) to achieve this. This is why the key keyword argument is used. Please look at the below one.
>>> nums = ["2", 1, 3, 4, "5", "8", "-1", "-10"]
>>> sorted(nums, key=int)
['-10', '-1', 1, '2', 3, 4, '5', '8']
>>>
Lets use lambda function as a value of key
>>> names = ["Rishikesh", "aman", "Ajay", "Hemkesh", "sandeep", "Darshan", "Virendra", "Shwetabh"]
>>> names2 = sorted(names)
>>> names2
['Ajay', 'Darshan', 'Hemkesh', 'Rishikesh', 'Shwetabh', 'Virendra', 'aman', 'sandeep']
>>> # But I don't want this o/p(here our intention is to treat 'a' same as 'A')
...
>>> names3 = sorted(names, key=lambda name:name.lower())
>>> names3
['Ajay', 'aman', 'Darshan', 'Hemkesh', 'Rishikesh', 'sandeep', 'Shwetabh', 'Virendra']
>>>
You can define your own function(callable) and provide it as value of key.
Dear programers, I have written the below code for you, just try to understand it and comment your explanation. I would be glad to see your explanation(it's simple).
>>> def validator(item):
... try:
... return int(item)
... except:
... return 0
...
>>> sorted(['gurmit', "0", 5, 2, 1, "front", -2, "great"], key=validator)
[-2, 'gurmit', '0', 'front', 'great', 1, 2, 5]
>>>
I hope it would be useful.
You can bind the DropDownList in different ways by using List, Dictionary, Enum, DataSet DataTable
.
Main you have to consider three thing while binding the datasource of a dropdown.
you can use following code to bind a dropdownlist to a datasource as a datatable
:
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnString"].ConnectionString);
SqlCommand cmd = new SqlCommand("Select * from tblQuiz", con);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataTable dt=new DataTable();
da.Fill(dt);
DropDownList1.DataTextField = "QUIZ_Name";
DropDownList1.DataValueField = "QUIZ_ID"
DropDownList1.DataSource = dt;
DropDownList1.DataBind();
if you want to process on selection of dropdownlist, then you have to change AutoPostBack="true"
you can use SelectedIndexChanged
event to write your code.
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
string strQUIZ_ID=DropDownList1.SelectedValue;
string strQUIZ_Name=DropDownList1.SelectedItem.Text;
// Your code..............
}
You can use Visual Studio Team Services for free. Also you can import a TFS repo to this cloud space.
From react documentation : https://reactjs.org/blog/2018/06/07/you-probably-dont-need-derived-state.html
Erasing state when props change is an Anti Pattern
Since React 16, componentWillReceiveProps is deprecated. From react documentation, the recommended approach in this case is use
ParentComponent
of the ModalBody
will own the start_time
state. This is not my prefer approach in this case since i think the modal should own this state. start_time
state from your ModalBody
and use getInitialState
just like you have already done. To reset the start_time
state, you simply change the key from the ParentComponent
I tried lots of the above answers. None of them worked for me. My app is installed in /home
and as user, not as root. This probably means that when the above mentioned start scripts run, /home
is not mounted yet, so the app is not started.
Then I found these instructions by Digital Ocean:
Using PM2 as explained was very simple and works perfectly: My virtual servers had two physical crashes since - downtime was only about a minute.
This funny solution works really good actually!
public static int countLines(File input) throws IOException {
try (InputStream is = new FileInputStream(input)) {
int count = 1;
for (int aChar = 0; aChar != -1;aChar = is.read())
count += aChar == '\n' ? 1 : 0;
return count;
}
}
data.matrix(SFI)
From ?data.matrix
:
Description:
Return the matrix obtained by converting all the variables in a
data frame to numeric mode and then binding them together as the
columns of a matrix. Factors and ordered factors are replaced by
their internal codes.
When I had this problem I've done it from command line:
zip file.zip uncompressed
EDIT, after many downvotes: I was using this option for some time ago and I don't know where I learnt it, so I can't give you a better explanation. Chris Johnson's answer is correct, but I won't delete mine. As one comment says, it's more accurate to what OP is asking, as it compress without those files, instead of removing them from a compressed file. I find it easier to remember, too.
This cross-browser lib seems safer - just zoom and moz-transform won't cover as many browsers as jquery.transform2d's scale().
http://louisremi.github.io/jquery.transform.js/
For example
$('#div').css({ transform: 'scale(.5)' });
OK - I see people are voting this down without an explanation. The other answer here won't work in old Safari (people running Tiger), and it won't work consistently in some older browsers - that is, it does scale things but it does so in a way that's either very pixellated or shifts the position of the element in a way that doesn't match other browsers.
http://www.browsersupport.net/CSS/zoom
Or just look at this question, which this one is likely just a dupe of:
import os
import cv2
rootdir = "directory path"
for subdir, dirs, files in os.walk(rootdir):
for file in files:
frame = cv2.imread(os.path.join(subdir, file))
There is an open issue for this on their github page: https://github.com/npm/npm/issues/18712
This issue is most severe when developers are using different operating systems.
It seems this is one of the rare occasions on which use of an attribute is actually appropriate. jQuery's attr()
method will not help you because in most cases (including this) it actually sets a property, not an attribute, making the choice of its name look somewhat foolish. [UPDATE: Since jQuery 1.6.1, the situation has changed slightly]
IE has some problems with the DOM setAttribute
method but in this case it should be fine:
this.setAttribute("checked", "checked");
In IE, this will always actually make the checkbox checked. In other browsers, if the user has already checked and unchecked the checkbox, setting the attribute will have no visible effect. Therefore, if you want to guarantee the checkbox is checked as well as having the checked
attribute, you need to set the checked
property as well:
this.setAttribute("checked", "checked");
this.checked = true;
To uncheck the checkbox and remove the attribute, do the following:
this.setAttribute("checked", ""); // For IE
this.removeAttribute("checked"); // For other browsers
this.checked = false;
I've run into this issue when trying to build a fixed positioned sidebar with both vertically scrollable content and nested absolute positioned children to be displayed outside sidebar boundaries.
My approach consisted of separately apply:
overflow: visible
property to the sidebar elementoverflow-y: auto
property to sidebar inner wrapperPlease check the example below or an online codepen.
html {_x000D_
min-height: 100%;_x000D_
}_x000D_
body {_x000D_
min-height: 100%;_x000D_
background: linear-gradient(to bottom, white, DarkGray 80%);_x000D_
margin: 0;_x000D_
padding: 0;_x000D_
}_x000D_
_x000D_
.sidebar {_x000D_
position: fixed;_x000D_
top: 0;_x000D_
right: 0;_x000D_
height: 100%;_x000D_
width: 200px;_x000D_
overflow: visible; /* Just apply overflow-x */_x000D_
background-color: DarkOrange;_x000D_
}_x000D_
_x000D_
.sidebarWrapper {_x000D_
padding: 10px;_x000D_
overflow-y: auto; /* Just apply overflow-y */_x000D_
height: 100%;_x000D_
width: 100%;_x000D_
}_x000D_
_x000D_
.element {_x000D_
position: absolute;_x000D_
top: 0;_x000D_
right: 100%;_x000D_
background-color: CornflowerBlue;_x000D_
padding: 10px;_x000D_
width: 200px;_x000D_
}
_x000D_
<p>Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium, totam rem aperiam, eaque ipsa quae ab illo inventore veritatis et quasi architecto beatae vitae dicta sunt explicabo. Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt. Neque porro quisquam est, qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit, sed quia non numquam eius modi tempora incidunt ut labore et dolore magnam aliquam quaerat voluptatem. Ut enim ad minima veniam, quis nostrum exercitationem ullam corporis suscipit laboriosam, nisi ut aliquid ex ea commodi consequatur? Quis autem vel eum iure reprehenderit qui in ea voluptate velit esse quam nihil molestiae consequatur, vel illum qui dolorem eum fugiat quo voluptas nulla pariatur?</p>_x000D_
<div class="sidebar">_x000D_
<div class="sidebarWrapper">_x000D_
<div class="element">_x000D_
I'm a sidebar child element but I'm able to horizontally overflow its boundaries._x000D_
</div>_x000D_
<p>This is a 200px width container with optional vertical scroll.</p>_x000D_
<p>Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium, totam rem aperiam, eaque ipsa quae ab illo inventore veritatis et quasi architecto beatae vitae dicta sunt explicabo. Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt. Neque porro quisquam est, qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit, sed quia non numquam eius modi tempora incidunt ut labore et dolore magnam aliquam quaerat voluptatem. Ut enim ad minima veniam, quis nostrum exercitationem ullam corporis suscipit laboriosam, nisi ut aliquid ex ea commodi consequatur? Quis autem vel eum iure reprehenderit qui in ea voluptate velit esse quam nihil molestiae consequatur, vel illum qui dolorem eum fugiat quo voluptas nulla pariatur?</p>_x000D_
</div>_x000D_
</div>
_x000D_
You can assign it to a hidden field, and retrieve it using
var value= Request.Form["value"]
left: initial
This will also set left
back to the browser default.
But important to know property: initial
is not supported in IE.
The docs explicitly says that java.sql.Date
will throw:
IllegalArgumentException
- if the date given is not in the JDBC date escape format (yyyy-[m]m-[d]d
)
Also you shouldn't need to convert a date to a String
then to a sql.date
, this seems superfluous (and bug-prone!). Instead you could:
java.sql.Date sqlDate := new java.sql.Date(now.getTime());
prs.setDate(2, sqlDate);
prs.setDate(3, sqlDate);
you have to place double-backslash
$str = str_replace('\\', '/', $str);
In short, REST emphasizes nouns over verbs. As your API becomes more complex, you add more things, rather than more commands.
How is this different from the following?
This line of code here:
String newString = new String(oldString.getBytes("UTF-8"), "UTF-8"));
constructs a new String object (i.e. a copy of oldString
), while this line of code:
String newString = oldString;
declares a new variable of type java.lang.String
and initializes it to refer to the same String object as the variable oldString
.
Is there any scenario in which the two lines will have different outputs?
Absolutely:
String newString = oldString;
boolean isSameInstance = newString == oldString; // isSameInstance == true
vs.
String newString = new String(oldString.getBytes("UTF-8"), "UTF-8"));
// isSameInstance == false (in most cases)
boolean isSameInstance = newString == oldString;
a_horse_with_no_name (see comment) is right of course. The equivalent of
String newString = new String(oldString.getBytes("UTF-8"), "UTF-8"));
is
String newString = new String(oldString);
minus the subtle difference wrt the encoding that Peter Lawrey explains in his answer.
When doing this I found it easiest to:
You will need to melt
your dataframe to get it into the so-called long format:
require(reshape2)
sample.data.M <- melt(sample.data)
Now your field values are represented by their own rows and identified through the variable column. This can now be leveraged within the ggplot aesthetics:
require(ggplot2)
c <- ggplot(sample.data.M, aes(x = Rank, y = value, fill = variable))
c + geom_bar(stat = "identity")
Instead of stacking you may also be interested in showing multiple plots using facets:
c <- ggplot(sample.data.M, aes(x = Rank, y = value))
c + facet_wrap(~ variable) + geom_bar(stat = "identity")
Here is my implementation of TRUNC function
private static object Tranc(List<Expression.Expression> p)
{
var target = (decimal)p[0].Evaluate();
// check if formula contains only one argument
var digits = p.Count > 1
? (decimal) p[1].Evaluate()
: 0;
return Math.Truncate((double)target * Math.Pow(10, (int)digits)) / Math.Pow(10, (int)digits);
}
Aligning text in native markdown is not possible. However, you can align the text using inline HTML tags.
<div style="text-align: right"> your-text-here </div>
To justify, replace right
with justify
in the above.
An old thread, but since I didn't find it elsewhere, here is one more possibility:
If you're using servlet-api 3.0+, then your web.xml must NOT include metadata-complete="true"
attribute
This tells tomcat to map the servlets using data given in web.xml
instead of using the @WebServlet
annotation.
What is it about your existing query that you don't like? If you are concerned that DISTINCT
across two columns does not return just the unique permutations why not try it?
It certainly works as you might expect in Oracle.
SQL> select distinct deptno, job from emp
2 order by deptno, job
3 /
DEPTNO JOB
---------- ---------
10 CLERK
10 MANAGER
10 PRESIDENT
20 ANALYST
20 CLERK
20 MANAGER
30 CLERK
30 MANAGER
30 SALESMAN
9 rows selected.
SQL> select count(*) from (
2 select distinct deptno, job from emp
3 )
4 /
COUNT(*)
----------
9
SQL>
edit
I went down a blind alley with analytics but the answer was depressingly obvious...
SQL> select count(distinct concat(deptno,job)) from emp
2 /
COUNT(DISTINCTCONCAT(DEPTNO,JOB))
---------------------------------
9
SQL>
edit 2
Given the following data the concatenating solution provided above will miscount:
col1 col2
---- ----
A AA
AA A
So we to include a separator...
select col1 + '*' + col2 from t23
/
Obviously the chosen separator must be a character, or set of characters, which can never appear in either column.
As you are looking for form object changes, the best watching approach is to use
$watchCollection
. Please have a look into official documentation for different performance characteristics.
1. Create Method: If you pass your exception to the following function, it will give you all methods and details which are reasons of the exception.
public string GetAllFootprints(Exception x)
{
var st = new StackTrace(x, true);
var frames = st.GetFrames();
var traceString = new StringBuilder();
foreach (var frame in frames)
{
if (frame.GetFileLineNumber() < 1)
continue;
traceString.Append("File: " + frame.GetFileName());
traceString.Append(", Method:" + frame.GetMethod().Name);
traceString.Append(", LineNumber: " + frame.GetFileLineNumber());
traceString.Append(" --> ");
}
return traceString.ToString();
}
2. Call Method: You can call the method like this.
try
{
// code part which you want to catch exception on it
}
catch(Exception ex)
{
Debug.Writeline(GetAllFootprints(ex));
}
3. Get the Result:
File: c:\MyProject\Program.cs, Method:MyFunction, LineNumber: 29 -->
File: c:\MyProject\Program.cs, Method:Main, LineNumber: 16 -->
UPDATE: For Bootstrap 5
The class name is now "float-end" instead of "pull-right"
<div class="alert alert-info clearfix">
<a href="#" class="alert-link">
Summary:Its some description.......testtesttest
</a>
<button type="button" class="btn btn-primary btn-lg float-end">
Large button
</button>
</div>
For Bootstrap 4 and under
Just add a simple pull-right class to the button, and make sure the container div is clearfixed:
<div class="alert alert-info clearfix">
<a href="#" class="alert-link">
Summary:Its some description.......testtesttest
</a>
<button type="button" class="btn btn-primary btn-lg pull-right">
Large button
</button>
</div>
Came across this some time ago
def clearscreen(numlines=100):
"""Clear the console.
numlines is an optional argument used only as a fall-back.
"""
# Thanks to Steven D'Aprano, http://www.velocityreviews.com/forums
if os.name == "posix":
# Unix/Linux/MacOS/BSD/etc
os.system('clear')
elif os.name in ("nt", "dos", "ce"):
# DOS/Windows
os.system('CLS')
else:
# Fallback for other operating systems.
print('\n' * numlines)
Then just use clearscreen()
Redis supports 5 data types. You need to know what type of value that a key maps to, as for each data type, the command to retrieve it is different.
Here are the commands to retrieve key value:
<key>
<key>
<key> <start> <end>
<key>
<key> <min> <max>
Use the TYPE
command to check the type of value a key is mapping to:
<key>
This example illustrates how to extract the sign (the leftmost bit), exponent (the 8 following bits) and mantissa (the 23 rightmost bits) from a float in Java.
int bits = Float.floatToIntBits(-0.005f);
int sign = bits >>> 31;
int exp = (bits >>> 23 & ((1 << 8) - 1)) - ((1 << 7) - 1);
int mantissa = bits & ((1 << 23) - 1);
System.out.println(sign + " " + exp + " " + mantissa + " " +
Float.intBitsToFloat((sign << 31) | (exp + ((1 << 7) - 1)) << 23 | mantissa));
The same approach can be used for double’s (11 bit exponent and 52 bit mantissa).
long bits = Double.doubleToLongBits(-0.005);
long sign = bits >>> 63;
long exp = (bits >>> 52 & ((1 << 11) - 1)) - ((1 << 10) - 1);
long mantissa = bits & ((1L << 52) - 1);
System.out.println(sign + " " + exp + " " + mantissa + " " +
Double.longBitsToDouble((sign << 63) | (exp + ((1 << 10) - 1)) << 52 | mantissa));
Credit: http://s-j.github.io/java-float/
You can use LinkedBlockingQueue I use it in my projects. It's part of standard java and quite easy to use
Don't rescue Exception => e
(and not re-raise the exception) - or you might drive off a bridge.
Let's say you are in a car (running Ruby). You recently installed a new steering wheel with the over-the-air upgrade system (which uses eval
), but you didn't know one of the programmers messed up on syntax.
You are on a bridge, and realize you are going a bit towards the railing, so you turn left.
def turn_left
self.turn left:
end
oops! That's probably Not Good™, luckily, Ruby raises a SyntaxError
.
The car should stop immediately - right?
Nope.
begin
#...
eval self.steering_wheel
#...
rescue Exception => e
self.beep
self.log "Caught #{e}.", :warn
self.log "Logged Error - Continuing Process.", :info
end
beep beep
Warning: Caught SyntaxError Exception.
Info: Logged Error - Continuing Process.
You notice something is wrong, and you slam on the emergency breaks (^C
: Interrupt
)
beep beep
Warning: Caught Interrupt Exception.
Info: Logged Error - Continuing Process.
Yeah - that didn't help much. You're pretty close to the rail, so you put the car in park (kill
ing: SignalException
).
beep beep
Warning: Caught SignalException Exception.
Info: Logged Error - Continuing Process.
At the last second, you pull out the keys (kill -9
), and the car stops, you slam forward into the steering wheel (the airbag can't inflate because you didn't gracefully stop the program - you terminated it), and the computer in the back of your car slams into the seat in front of it. A half-full can of Coke spills over the papers. The groceries in the back are crushed, and most are covered in egg yolk and milk. The car needs serious repair and cleaning. (Data Loss)
Hopefully you have insurance (Backups). Oh yeah - because the airbag didn't inflate, you're probably hurt (getting fired, etc).
But wait! There's more reasons why you might want to use rescue Exception => e
!
Let's say you're that car, and you want to make sure the airbag inflates if the car is exceeding its safe stopping momentum.
begin
# do driving stuff
rescue Exception => e
self.airbags.inflate if self.exceeding_safe_stopping_momentum?
raise
end
Here's the exception to the rule: You can catch Exception
only if you re-raise the exception. So, a better rule is to never swallow Exception
, and always re-raise the error.
But adding rescue is both easy to forget in a language like Ruby, and putting a rescue statement right before re-raising an issue feels a little non-DRY. And you do not want to forget the raise
statement. And if you do, good luck trying to find that error.
Thankfully, Ruby is awesome, you can just use the ensure
keyword, which makes sure the code runs. The ensure
keyword will run the code no matter what - if an exception is thrown, if one isn't, the only exception being if the world ends (or other unlikely events).
begin
# do driving stuff
ensure
self.airbags.inflate if self.exceeding_safe_stopping_momentum?
end
Boom! And that code should run anyways. The only reason you should use rescue Exception => e
is if you need access to the exception, or if you only want code to run on an exception. And remember to re-raise the error. Every time.
Note: As @Niall pointed out, ensure always runs. This is good because sometimes your program can lie to you and not throw exceptions, even when issues occur. With critical tasks, like inflating airbags, you need to make sure it happens no matter what. Because of this, checking every time the car stops, whether an exception is thrown or not, is a good idea. Even though inflating airbags is a bit of an uncommon task in most programming contexts, this is actually pretty common with most cleanup tasks.
Android complete source code for adding events and reminders with start and end time format.
/** Adds Events and Reminders in Calendar. */
private void addReminderInCalendar() {
Calendar cal = Calendar.getInstance();
Uri EVENTS_URI = Uri.parse(getCalendarUriBase(true) + "events");
ContentResolver cr = getContentResolver();
TimeZone timeZone = TimeZone.getDefault();
/** Inserting an event in calendar. */
ContentValues values = new ContentValues();
values.put(CalendarContract.Events.CALENDAR_ID, 1);
values.put(CalendarContract.Events.TITLE, "Sanjeev Reminder 01");
values.put(CalendarContract.Events.DESCRIPTION, "A test Reminder.");
values.put(CalendarContract.Events.ALL_DAY, 0);
// event starts at 11 minutes from now
values.put(CalendarContract.Events.DTSTART, cal.getTimeInMillis() + 11 * 60 * 1000);
// ends 60 minutes from now
values.put(CalendarContract.Events.DTEND, cal.getTimeInMillis() + 60 * 60 * 1000);
values.put(CalendarContract.Events.EVENT_TIMEZONE, timeZone.getID());
values.put(CalendarContract.Events.HAS_ALARM, 1);
Uri event = cr.insert(EVENTS_URI, values);
// Display event id
Toast.makeText(getApplicationContext(), "Event added :: ID :: " + event.getLastPathSegment(), Toast.LENGTH_SHORT).show();
/** Adding reminder for event added. */
Uri REMINDERS_URI = Uri.parse(getCalendarUriBase(true) + "reminders");
values = new ContentValues();
values.put(CalendarContract.Reminders.EVENT_ID, Long.parseLong(event.getLastPathSegment()));
values.put(CalendarContract.Reminders.METHOD, Reminders.METHOD_ALERT);
values.put(CalendarContract.Reminders.MINUTES, 10);
cr.insert(REMINDERS_URI, values);
}
/** Returns Calendar Base URI, supports both new and old OS. */
private String getCalendarUriBase(boolean eventUri) {
Uri calendarURI = null;
try {
if (android.os.Build.VERSION.SDK_INT <= 7) {
calendarURI = (eventUri) ? Uri.parse("content://calendar/") : Uri.parse("content://calendar/calendars");
} else {
calendarURI = (eventUri) ? Uri.parse("content://com.android.calendar/") : Uri
.parse("content://com.android.calendar/calendars");
}
} catch (Exception e) {
e.printStackTrace();
}
return calendarURI.toString();
}
<uses-permission android:name="android.permission.READ_CALENDAR" />
<uses-permission android:name="android.permission.WRITE_CALENDAR" />
I do not know how to solve this using code, but I do manually adjust the control panel at the right bottom in the plot figure, and adjust the figure size like:
f, ax = plt.subplots(figsize=(16, 12))
at the meantime until you get a matched size colobar. This worked for me.
What is the problem here is that you somehow installed into virtualenv using sudo
. Probably by accident. This means root
user will rewrite Python package data, making all file owned by root and your normal user cannot write those files anymore. Usually virtualenv should be used and owned by your normal UNIX user only.
You can fix the issue by changing UNIX file permissions pack to your user. Try:
$ sudo chown -R USERNAME /Users/USERNAME/Library/Logs/pip
$ sudo chown -R USERNAME /Users/USERNAME/Library/Caches/pip
then pip
should be able to write those files again.
You may want to look at http://tug.ctan.org/tex-archive/macros/latex/contrib/float/ which allows you to define new floats using \newfloat
I say this because captions are usually applied to floats.
Straight ahead equations (those written with $ ... $
, $$ ... $$
, begin{equation}...
) are in-line objects that do not support \caption
.
This can be done using the following snippet just before \begin{document}
\usepackage{float}
\usepackage{aliascnt}
\newaliascnt{eqfloat}{equation}
\newfloat{eqfloat}{h}{eqflts}
\floatname{eqfloat}{Equation}
\newcommand*{\ORGeqfloat}{}
\let\ORGeqfloat\eqfloat
\def\eqfloat{%
\let\ORIGINALcaption\caption
\def\caption{%
\addtocounter{equation}{-1}%
\ORIGINALcaption
}%
\ORGeqfloat
}
and when adding an equation use something like
\begin{eqfloat}
\begin{equation}
f( x ) = ax + b
\label{eq:linear}
\end{equation}
\caption{Caption goes here}
\end{eqfloat}
MYISAM:
INNODB:
Investigating this error on my new Win 7 laptop, I found my ADT plugin to be missing. By adding this I solved the problem: Downloading the ADT Plugin
Use the Update Manager feature of your Eclipse installation to install the latest revision of ADT on your development computer.
Assuming that you have a compatible version of the Eclipse IDE installed, as described in Preparing for Installation, above, follow these steps to download the ADT plugin and install it in your Eclipse environment.
Start Eclipse, then select Help > Install New Software.... Click Add, in the top-right corner. In the Add Repository dialog that appears, enter "ADT Plugin" for the Name and the following URL for the Location: https://dl-ssl.google.com/android/eclipse/ Click OK
Note: If you have trouble acquiring the plugin, try using "http" in the Location URL, instead of "https" (https is preferred for security reasons). In the Available Software dialog, select the checkbox next to Developer Tools and click Next. In the next window, you'll see a list of the tools to be downloaded. Click Next. Read and accept the license agreements, then click Finish.
Note: If you get a security warning saying that the authenticity or validity of the software can't be established, click OK. When the installation completes, restart Eclipse.
Another variant using $env
environment variable to grab hostname:
Test-Connection -ComputerName $env:computername -count 1 | Select-Object IPV4Address
or if you just want the IP address returned without the property header
(Test-Connection -ComputerName $env:computername -count 1).IPV4Address.ipaddressTOstring
I had the same issue when I was using x64 box(chef/ubuntu-14.04).
I changed to x32 and it worked(hashicorp/precise32).
Here is the code help you to download file from server at the same time you can see the progress of downloading on your status bar.
See the functionality in below image of my code:
STEP - 1 : Create on DownloadFileFromURL.java class file to download file content from server. Here i create an asynchronous task to download file.
public class DownloadFileFromURL extends AsyncTask<String, Integer, String> {
private NotificationManager mNotifyManager;
private NotificationCompat.Builder build;
private File fileurl;
int id = 123;
OutputStream output;
private Context context;
private String selectedDate;
private String ts = "";
public DownloadFileFromURL(Context context, String selectedDate) {
this.context = context;
this.selectedDate = selectedDate;
}
protected void onPreExecute() {
super.onPreExecute();
mNotifyManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
build = new NotificationCompat.Builder(context);
build.setContentTitle("Download")
.setContentText("Download in progress")
.setChannelId(id + "")
.setAutoCancel(false)
.setDefaults(0)
.setSmallIcon(R.drawable.ic_menu_download);
// Since android Oreo notification channel is needed.
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationChannel channel = new NotificationChannel(id + "",
"Social Media Downloader",
NotificationManager.IMPORTANCE_HIGH);
channel.setDescription("no sound");
channel.setSound(null, null);
channel.enableLights(false);
channel.setLightColor(Color.BLUE);
channel.enableVibration(false);
mNotifyManager.createNotificationChannel(channel);
}
build.setProgress(100, 0, false);
mNotifyManager.notify(id, build.build());
String msg = "Download started";
//CustomToast.showToast(context,msg);
}
@Override
protected String doInBackground(String... f_url) {
int count;
ts = selectedDate.split("T")[0];
try {
URL url = new URL(f_url[0]);
URLConnection conection = url.openConnection();
conection.connect();
int lenghtOfFile = conection.getContentLength();
InputStream input = new BufferedInputStream(url.openStream(),
8192);
// Output stream
output = new FileOutputStream(Environment
.getExternalStorageDirectory().toString()
+ Const.DownloadPath + ts + ".pdf");
fileurl = new File(Environment.getExternalStorageDirectory()
+ Const.DownloadPath + ts + ".pdf");
byte[] data = new byte[1024];
long total = 0;
while ((count = input.read(data)) != -1) {
total += count;
int cur = (int) ((total * 100) / lenghtOfFile);
publishProgress(Math.min(cur, 100));
if (Math.min(cur, 100) > 98) {
try {
Thread.sleep(500);
} catch (InterruptedException e) {
Log.d("Failure", "sleeping failure");
}
}
Log.i("currentProgress", "currentProgress: " + Math.min(cur, 100) + "\n " + cur);
output.write(data, 0, count);
}
output.flush();
output.close();
input.close();
} catch (Exception e) {
Log.e("Error: ", e.getMessage());
}
return null;
}
protected void onProgressUpdate(Integer... progress) {
build.setProgress(100, progress[0], false);
mNotifyManager.notify(id, build.build());
super.onProgressUpdate(progress);
}
@Override
protected void onPostExecute(String file_url) {
build.setContentText("Download complete");
build.setProgress(0, 0, false);
mNotifyManager.notify(id, build.build());
} }
Note: If you want code with import package then Click Here
Now Step 2: You need to call above ayncronous task on your click event. for example i have set on pdf image icon. To call AsyncTask use below code:
new DownloadFileFromURL(fContext,filename).execute(serverFileUrl);
Note: Here You can see filename variable in file parameter. This is the name which i use to save my downloaded file in local device. currently i am downloading only pdf file but you can use you url in serverFileUrl parameter.
If method 1 has to be executed after method 2, 3, 4. The following code snippet can be the solution for this using Deferred object in JavaScript.
function method1(){_x000D_
var dfd = new $.Deferred();_x000D_
setTimeout(function(){_x000D_
console.log("Inside Method - 1"); _x000D_
method2(dfd); _x000D_
}, 5000);_x000D_
return dfd.promise();_x000D_
}_x000D_
_x000D_
function method2(dfd){_x000D_
setTimeout(function(){_x000D_
console.log("Inside Method - 2"); _x000D_
method3(dfd); _x000D_
}, 3000);_x000D_
}_x000D_
_x000D_
function method3(dfd){_x000D_
setTimeout(function(){_x000D_
console.log("Inside Method - 3"); _x000D_
dfd.resolve();_x000D_
}, 3000);_x000D_
}_x000D_
_x000D_
function method4(){ _x000D_
console.log("Inside Method - 4"); _x000D_
}_x000D_
_x000D_
var call = method1();_x000D_
_x000D_
$.when(call).then(function(cb){_x000D_
method4();_x000D_
});
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
_x000D_
This link works with me: video
The answer posted before didn't work for me until the second click
So what I did is Directly call:
new NewForm().setVisible(true);
this.dispose();//to close the current jframe
In addition to accepted answer, if you're using Entity Migrations for updating database, you should add this line at the beggining of the Up()
function in your migration file:
Sql("alter table dbo.CompanyTransactions drop constraint [df__CompanyTr__Creat__0cdae408];");
You can find the constraint name in the error at nuget packet manager console which starts with FK_dbo.
If using a BeansWrapper with an exposure level of Expose.SAFE or Expose.ALL, then the standard Java approach of iterating the entry set can be employed:
For example, the following will work in Freemarker (since at least version 2.3.19):
<#list map.entrySet() as entry>
<input type="hidden" name="${entry.key}" value="${entry.value}" />
</#list>
In Struts2, for instance, an extension of the BeanWrapper is used with the exposure level defaulted to allow this manner of iteration.
No, the dataType
option is for parsing the received data.
To post JSON, you will need to stringify it yourself via JSON.stringify
and set the processData
option to false
.
$.ajax({
url: url,
type: "POST",
data: JSON.stringify(data),
processData: false,
contentType: "application/json; charset=UTF-8",
complete: callback
});
Note that not all browsers support the JSON
object, and although jQuery has .parseJSON
, it has no stringifier included; you'll need another polyfill library.
A process performing I/O will be put in D state (uninterruptable sleep), which frees the CPU until there is a hardware interrupt which tells the CPU to return to executing the program. See man ps
for the other process states.
Depending on your kernel, there is a process scheduler, which keeps track of a runqueue of processes ready to execute. It, along with a scheduling algorithm, tells the kernel which process to assign to which CPU. There are kernel processes and user processes to consider. Each process is allocated a time-slice, which is a chunk of CPU time it is allowed to use. Once the process uses all of its time-slice, it is marked as expired and given lower priority in the scheduling algorithm.
In the 2.6 kernel, there is a O(1) time complexity scheduler, so no matter how many processes you have up running, it will assign CPUs in constant time. It is more complicated though, since 2.6 introduced preemption and CPU load balancing is not an easy algorithm. In any case, it’s efficient and CPUs will not remain idle while you wait for the I/O.
use Javascript sort() function
var $tbody = $('table tbody');
$tbody.find('tr').sort(function(a,b){
var tda = $(a).find('td:eq(1)').text(); // can replace 1 with the column you want to sort on
var tdb = $(b).find('td:eq(1)').text(); // this will sort on the second column
// if a < b return 1
return tda < tdb ? 1
// else if a > b return -1
: tda > tdb ? -1
// else they are equal - return 0
: 0;
}).appendTo($tbody);
If you want ascending you just have to reverse the > and <
Change the logic accordingly for you.
You need to include a body with the request. Angular removes the content-type header otherwise.
Add data: ''
to the argument to $http
.
add layout_gravity="center"
or "center_horizontal"
to the parent layout.
On a side note, your LinearLayout
inside your TableRow
seems un-necessary, as a TableRow
is already an horizontal LinearLayout
.
I'm not sure what you're trying to do: If you added the file via
svn add myfile
you only told svn to put this file into your repository when you do your next commit. There's no change to the repository before you type an
svn commit
If you delete the file before the commit, svn
has it in its records (because you added it) but cannot send it to the repository because the file no longer exist.
So either you want to save the file in the repository and then delete it from your working copy: In this case try to get your file back (from the trash?), do the commit and delete the file afterwards via
svn delete myfile
svn commit
If you want to undo the add
and just throw the file away, you can to an
svn revert myfile
which tells svn
(in this case) to undo the add-Operation.
EDIT
Sorry, I wasn't aware that you're using the "Versions" GUI client for Max OSX. So either try a revert on the containing directory using the GUI or jump into the cold water and fire up your hidden Mac command shell :-) (it's called "Terminal" in the german OSX, no idea how to bring it up in the english version...)
Strings are immutable, so you need to say
sInputString = sInputString("\"","");
not just the right side of the =
You're looking for this on the command line (for a class called MyClass):
On Unix/Linux:
javap -verbose MyClass | grep "major"
On Windows:
javap -verbose MyClass | findstr "major"
You want the major version from the results. Here are some example values:
I would like to describe a very good example of why negative padding
would be useful and awesome.
As all of us CSS developers know, vertically aligning a dynamically sizing div within another is a hassle, and for the most part, viewed as being impossible only using CSS. The incorporation of negative padding
could change this.
Please review the following HTML:
<div style="height:600px; width:100%;">
<div class="vertical-align" style="width:100%;height:auto;" >
This DIV's height will change based the width of the screen.
</div>
</div>
With the following CSS, we would be able to vertically center the content of the inner div
within the outer div
:
.vertical-align {
position: absolute;
top:50%;
padding-top:-50%;
overflow: visible;
}
Allow me to explain...
Absolutely positioning the inner div's top at 50% places the top edge of the inner div at the center of the outer div. Pretty simple. This is because percentage based positioning is relative to the inner dimensions of the parent element.
Percentage based padding, on the other hand, is based on the inner dimensions of the targeted element. So, by applying the property of padding-top: -50%;
we have shifted the content of the inner div upward by a distance of 50% of the height of the inner div's content, therefore centering the inner div's content within the outer div and still allowing the height dimension of the inner div to be dynamic!
If you ask me OP, this would be the best use-case, and I think it should be implemented just so I can do this hack. lol. Or, they should just fix the functionality of vertical-align
and give us a version of vertical-align
that works on all elements.
This is how I solved this problem. I created a special event handler that went into the code behind:
private void TextBox_KeyEnterUpdate(object sender, KeyEventArgs e)
{
if (e.Key == Key.Enter)
{
TextBox tBox = (TextBox)sender;
DependencyProperty prop = TextBox.TextProperty;
BindingExpression binding = BindingOperations.GetBindingExpression(tBox, prop);
if (binding != null) { binding.UpdateSource(); }
}
}
Then I just added this as a KeyUp event handler in the XAML:
<TextBox Text="{Binding TextValue1}" KeyUp="TextBox_KeyEnterUpdate" />
<TextBox Text="{Binding TextValue2}" KeyUp="TextBox_KeyEnterUpdate" />
The event handler uses its sender
reference to cause it's own binding to get updated. Since the event handler is self-contained then it should work in a complex DataTemplate. This one event handler can now be added to all the textboxes that need this feature.
find($id)
takes an id and returns a single model. If no matching model exist, it returns null
.
findOrFail($id)
takes an id and returns a single model. If no matching model exist, it throws an error1.
first()
returns the first record found in the database. If no matching model exist, it returns null
.
firstOrFail()
returns the first record found in the database. If no matching model exist, it throws an error1.
get()
returns a collection of models matching the query.
pluck($column)
returns a collection of just the values in the given column. In previous versions of Laravel this method was called lists
.
toArray()
converts the model/collection into a simple PHP array.
Note: a collection is a beefed up array. It functions similarly to an array, but has a lot of added functionality, as you can see in the docs.
Unfortunately, PHP doesn't let you use a collection object everywhere you can use an array. For example, using a collection in a foreach
loop is ok, put passing it to array_map
is not. Similarly, if you type-hint an argument as array
, PHP won't let you pass it a collection. Starting in PHP 7.1, there is the iterable
typehint, which can be used to accept both arrays and collections.
If you ever want to get a plain array from a collection, call its all()
method.
1 The error thrown by the findOrFail
and firstOrFail
methods is a ModelNotFoundException
. If you don't catch this exception yourself, Laravel will respond with a 404, which is what you want most of the time.
So I used to use a for loop for iterating through the dictionary as well, but one thing I've found that works much faster is to convert to a panel and then to a dataframe. Say you have a dictionary d
import pandas as pd
d
{'RAY Index': {datetime.date(2014, 11, 3): {'PX_LAST': 1199.46,
'PX_OPEN': 1200.14},
datetime.date(2014, 11, 4): {'PX_LAST': 1195.323, 'PX_OPEN': 1197.69},
datetime.date(2014, 11, 5): {'PX_LAST': 1200.936, 'PX_OPEN': 1195.32},
datetime.date(2014, 11, 6): {'PX_LAST': 1206.061, 'PX_OPEN': 1200.62}},
'SPX Index': {datetime.date(2014, 11, 3): {'PX_LAST': 2017.81,
'PX_OPEN': 2018.21},
datetime.date(2014, 11, 4): {'PX_LAST': 2012.1, 'PX_OPEN': 2015.81},
datetime.date(2014, 11, 5): {'PX_LAST': 2023.57, 'PX_OPEN': 2015.29},
datetime.date(2014, 11, 6): {'PX_LAST': 2031.21, 'PX_OPEN': 2023.33}}}
The command
pd.Panel(d)
<class 'pandas.core.panel.Panel'>
Dimensions: 2 (items) x 2 (major_axis) x 4 (minor_axis)
Items axis: RAY Index to SPX Index
Major_axis axis: PX_LAST to PX_OPEN
Minor_axis axis: 2014-11-03 to 2014-11-06
where pd.Panel(d)[item] yields a dataframe
pd.Panel(d)['SPX Index']
2014-11-03 2014-11-04 2014-11-05 2014-11-06
PX_LAST 2017.81 2012.10 2023.57 2031.21
PX_OPEN 2018.21 2015.81 2015.29 2023.33
You can then hit the command to_frame() to turn it into a dataframe. I use reset_index as well to turn the major and minor axis into columns rather than have them as indices.
pd.Panel(d).to_frame().reset_index()
major minor RAY Index SPX Index
PX_LAST 2014-11-03 1199.460 2017.81
PX_LAST 2014-11-04 1195.323 2012.10
PX_LAST 2014-11-05 1200.936 2023.57
PX_LAST 2014-11-06 1206.061 2031.21
PX_OPEN 2014-11-03 1200.140 2018.21
PX_OPEN 2014-11-04 1197.690 2015.81
PX_OPEN 2014-11-05 1195.320 2015.29
PX_OPEN 2014-11-06 1200.620 2023.33
Finally, if you don't like the way the frame looks you can use the transpose function of panel to change the appearance before calling to_frame() see documentation here http://pandas.pydata.org/pandas-docs/dev/generated/pandas.Panel.transpose.html
Just as an example
pd.Panel(d).transpose(2,0,1).to_frame().reset_index()
major minor 2014-11-03 2014-11-04 2014-11-05 2014-11-06
RAY Index PX_LAST 1199.46 1195.323 1200.936 1206.061
RAY Index PX_OPEN 1200.14 1197.690 1195.320 1200.620
SPX Index PX_LAST 2017.81 2012.100 2023.570 2031.210
SPX Index PX_OPEN 2018.21 2015.810 2015.290 2023.330
Hope this helps.
With your own Code and a Slight Change withou jQuery,
function testingAPI(){
var key = "8a1c6a354c884c658ff29a8636fd7c18";
var url = "https://api.fantasydata.net/nfl/v2/JSON/PlayerSeasonStats/2015";
console.log(httpGet(url,key));
}
function httpGet(url,key){
var xmlHttp = new XMLHttpRequest();
xmlHttp.open( "GET", url, false );
xmlHttp.setRequestHeader("Ocp-Apim-Subscription-Key",key);
xmlHttp.send(null);
return xmlHttp.responseText;
}
Thank You
Arrays.asList()
this method returns its own implementation of List.It takes an array as an argument and builds methods and attributes on top of it, since it is not copying any data from an array but using the original array this causes alteration in original array when you modify list returned by the Arrays.asList()
method.
on the other hand.
ArrayList(Arrays.asList());
is a constructor of ArrayList
class which takes a list as argument and returns an ArrayList
that is independent of list ie. Arrays.asList()
in this case passed as an argument.
that is why you see these results;
This single line works better imho:
Application.Evaluate("SUMPRODUCT(--(E10:E14<>""""))=0")
in this case, it evaluates if range E10:E14 is empty.
Is it literally just the second line you want to indent, or is it from the second line (ie. a hanging indent)?
If it is the latter, something along the lines of this JSFiddle would be appropriate.
div {_x000D_
padding-left: 1.5em;_x000D_
text-indent:-1.5em;_x000D_
}_x000D_
_x000D_
span {_x000D_
padding-left: 1.5em;_x000D_
text-indent:-1.5em;_x000D_
}
_x000D_
<div>Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod tincidunt ut laoreet dolore magna aliquam erat volutpat. Ut wisi enim ad minim veniam, quis nostrud exerci tation ullamcorper suscipit lobortis nisl ut aliquip ex ea commodo consequat.</div>_x000D_
_x000D_
<span>Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod tincidunt ut laoreet dolore magna aliquam erat volutpat. Ut wisi enim ad minim veniam, quis nostrud exerci tation ullamcorper suscipit lobortis nisl ut aliquip ex ea commodo consequat.</span>
_x000D_
This example shows how using the same CSS syntax in a DIV or SPAN produce different effects.
Its easy to switch between prefork or worker mpm in Apache 2.4 on RHEL7
Check MPM type by executing
sudo httpd -V
Server version: Apache/2.4.6 (Red Hat Enterprise Linux)
Server built: Jul 26 2017 04:45:44
Server's Module Magic Number: 20120211:24
Server loaded: APR 1.4.8, APR-UTIL 1.5.2
Compiled using: APR 1.4.8, APR-UTIL 1.5.2
Architecture: 64-bit
Server MPM: prefork
threaded: no
forked: yes (variable process count)
Server compiled with....
-D APR_HAS_SENDFILE
-D APR_HAS_MMAP
-D APR_HAVE_IPV6 (IPv4-mapped addresses enabled)
-D APR_USE_SYSVSEM_SERIALIZE
-D APR_USE_PTHREAD_SERIALIZE
-D SINGLE_LISTEN_UNSERIALIZED_ACCEPT
-D APR_HAS_OTHER_CHILD
-D AP_HAVE_RELIABLE_PIPED_LOGS
-D DYNAMIC_MODULE_LIMIT=256
-D HTTPD_ROOT="/etc/httpd"
-D SUEXEC_BIN="/usr/sbin/suexec"
-D DEFAULT_PIDLOG="/run/httpd/httpd.pid"
-D DEFAULT_SCOREBOARD="logs/apache_runtime_status"
-D DEFAULT_ERRORLOG="logs/error_log"
-D AP_TYPES_CONFIG_FILE="conf/mime.types"
-D SERVER_CONFIG_FILE="conf/httpd.conf"
Now to change MPM edit following file and uncomment required MPM
/etc/httpd/conf.modules.d/00-mpm.conf
# Select the MPM module which should be used by uncommenting exactly
# one of the following LoadModule lines:
# prefork MPM: Implements a non-threaded, pre-forking web server
# See: http://httpd.apache.org/docs/2.4/mod/prefork.html
LoadModule mpm_prefork_module modules/mod_mpm_prefork.so
# worker MPM: Multi-Processing Module implementing a hybrid
# multi-threaded multi-process web server
# See: http://httpd.apache.org/docs/2.4/mod/worker.html
#
#LoadModule mpm_worker_module modules/mod_mpm_worker.so
# event MPM: A variant of the worker MPM with the goal of consuming
# threads only for connections with active processing
# See: http://httpd.apache.org/docs/2.4/mod/event.html
#
#LoadModule mpm_event_module modules/mod_mpm_event.so
It looks like there was an issue with my migration.
I ran ./manage.py schemamigration research --auto
and found that many of the fields didn't have a default specified.
So, I ran ./manage.py schemamigration research --init
followed by ./manage.py migrate research
Rerunning the server from there did the trick!
I don't think the camel case is the issue in that example, but I imagine a more RESTful naming convention for the above example would be:
api.service.com/helloWorld/userId/x
rather then making userId a query parameter (which is perfectly legal) my example denotes that resource in, IMO, a more RESTful way.
Just use setTimeOut
with recursion:
waitUntilElementIsPresent(callback: () => void): void {
if (!this.methodToCheckIfElementIsPresent()) {
setTimeout(() => this.waitUntilElementIsPresent(callback), 500);
return;
}
callback();
}
Usage:
this.waitUntilElementIsPresent(() => console.log('Element is present!'));
You can limit amount of attempts, so an error will be thrown when the element is not present after the limit:
waitUntilElementIsPresent(callback: () => void, attempt: number = 0): void {
const maxAttempts = 10;
if (!this.methodToCheckIfElementIsPresent()) {
attempt++;
setTimeout(() => this.waitUntilElementIsPresent(callback, attempt), 500);
return;
} else if (attempt >= maxAttempts) {
return;
}
callback();
}
you should change cr_date(str) to datetime object then you 'll change the date to the specific format:
cr_date = '2013-10-31 18:23:29.000227'
cr_date = datetime.datetime.strptime(cr_date, '%Y-%m-%d %H:%M:%S.%f')
cr_date = cr_date.strftime("%m/%d/%Y")
$table->date('user_id')->nullable();
In your file create_file
, the null option must be enabled.
Here is a quick and easy solution:
CREATE FUNCTION dbo.vaValidEmail(@EMAIL varchar(100))
RETURNS bit as
BEGIN
DECLARE @bitRetVal as Bit
IF (@EMAIL <> '' AND @EMAIL NOT LIKE '_%@__%.__%')
SET @bitRetVal = 0 -- Invalid
ELSE
SET @bitRetVal = 1 -- Valid
RETURN @bitRetVal
END
Then you can find all rows by using the function:
SELECT * FROM users WHERE dbo.vaValidEmail(email) = 0
If you are not happy with creating a function in your database, you can use the LIKE-clause directly in your query:
SELECT * FROM users WHERE email NOT LIKE '_%@__%.__%'
Click on the line or element you want to copy. Copy to clipboard. Paste.
The only tricky thing is if you click on a line, you get everything that line includes if it was folded. For example if you click on a div, and copy, you get everything that the div includes.
You can also get only what you want by Right Clicking, and select 'Edit as HTML'. This will make that section essentially text, with none of the folding activated. You can then select, copy and paste the relevant bits.
Another one is to use the -F option but pass it regex to print the text between left and or right parenthesis ()
.
The file content:
528(smbw)
529(smbt)
530(smbn)
10115(smbs)
The command:
awk -F"[()]" '{print $2}' filename
result:
smbw
smbt
smbn
smbs
Using awk to just print the text between []
:
Use awk -F'[][]'
but awk -F'[[]]'
will not work.
http://stanlo45.blogspot.com/2020/06/awk-multiple-field-separators.html
I -strongly- recommend build your HtmlHelpers. I think that apsx code will be more readable, reliable and durable.
Follow the link; http://msdn.microsoft.com/en-us/library/system.web.mvc.htmlhelper.aspx
NAudio wraps the WaveOutXXXX API. I haven't looked at the source, but if NAudio exposes the waveOutWrite() function in a way that doesn't automatically stop playback on each call, then you should be able to do what you really want, which is to start playing the audio stream before you've received all the data.
Using the waveOutWrite() function allows you to "read ahead" and dump smaller chunks of audio into the output queue - Windows will automatically play the chunks seamlessly. Your code would have to take the compressed audio stream and convert it to small chunks of WAV audio on the fly; this part would be really difficult - all the libraries and components I've ever seen do MP3-to-WAV conversion an entire file at a time. Probably your only realistic chance is to do this using WMA instead of MP3, because you can write simple C# wrappers around the multimedia SDK.
There are two issues in your code.
getElementByName
instead of getElement**s**ByName
value
in lowercase instead of Value
.What ever attribute is added to the button/anchor/link to disable it, bootstrap is just adding style to it and user will still be able to click it while there is still onclick event. So my simple solution is to check if it is disabled and remove/add onclick event:
if (!('#button').hasAttr('disabled'))
$('#button').attr('onclick', 'someFunction();');
else
$('#button').removeattr('onclick');
You can increase that in php.ini
; Maximum allowed size for uploaded files.
upload_max_filesize = 2M
If you're using spring boot with starters - this dependency adds both tomcat-embed-el
and hibernate-validator
dependencies:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-validation</artifactId>
</dependency>
In the cell you want your result to appear, use the following formula:
=COUNTIF(A1:A200,"<>")
That will count all cells which have a value and ignore all empty cells in the range of A1 to A200.
You can use np.logaddexp
(which implements the idea in @gg349's answer):
In [33]: d = np.array([[1089, 1093]])
In [34]: e = np.array([[1000, 4443]])
In [35]: log_res = np.logaddexp(-3*d[0,0], -3*d[0,1]) - np.logaddexp(-3*e[0,0], -3*e[0,1])
In [36]: log_res
Out[36]: -266.99999385580668
In [37]: res = exp(log_res)
In [38]: res
Out[38]: 1.1050349147204485e-116
Or you can use scipy.special.logsumexp
:
In [52]: from scipy.special import logsumexp
In [53]: res = np.exp(logsumexp(-3*d) - logsumexp(-3*e))
In [54]: res
Out[54]: 1.1050349147204485e-116
I have used Emacs as my primary environment for both development and mail/news for about 10 year (1994-2004). I discovered the power of IDEs when I forced myself to learn Java in 2004, and to my surprise that I actually liked the IDE (IntelliJ IDEA).
I will not go into specific reasons since a lot of them have already been mentioned here -- just remember that the different people love different features. Me and a colleague used the same IDE, both of us used just a fraction of the features available, and we disliked each others way of using the IDE (but we both liked the IDE itself).
But there is one advantage with IDEs over Emacs/Vim related environments I want to focus on: You spend less time installing/configuring the features you want.
With Wing IDE (for Python) I'm ready to start developing 15-20 minutes after installation. No idea how many hours I would need to get the features I use up and running with Emacs/Vim. :)
We can set the width for ul tag then it will align center.
#header ul {
display: block;
margin: 0 auto;
width: 420px;
max-width: 100%;
}
A simple find and replace for a single character would go something like:
s.replace(s.find("x"), 1, "y")
To do this for the whole string, the easy thing to do would be to loop until your s.find
starts returning npos
. I suppose you could also catch range_error
to exit the loop, but that's kinda ugly.
The specific Date
constructor is deprecated, and Calendar
should be used instead.
The JavaDoc
for Date describes which constructors are deprecated and how to replace them using a Calendar
.
There really aren't any differences.
"
is processed as "
which is the decimal equivalent of &x22;
which is the ISO 8859-1 equivalent of "
.
The only reason you may be against using "
is because it was mistakenly omitted from the HTML 3.2 specification.
Otherwise it all boils down to personal preference.
This Works
function saveBase64AsFile(base64, fileName) {
var link = document.createElement("a");
document.body.appendChild(link);
link.setAttribute("type", "hidden");
link.href = "data:text/plain;base64," + base64;
link.download = fileName;
link.click();
document.body.removeChild(link);
}
Based on the answer above but with some changes
I don´t know if this is relevant anymore, but I fixed it with the @RequestMapping annotation.
@RequestMapping(method=RequestMethod.GET, produces={"application/json; charset=UTF-8"})
'\u0000'
stands for null
. So if you print an uninitialized char variable , you'll get nothing.
I solved this like this:
<section className="container-fluid">
<div className="row justify-content-center">
<article className="d-flex flex-column justify-content-center align-items-center vh-100">
<!-- content -->
</article>
</div>
</section>
I feed a 514 dimensional real-valued input to a Sequential
model in Keras.
My model is constructed in following way :
predictivemodel = Sequential()
predictivemodel.add(Dense(514, input_dim=514, W_regularizer=WeightRegularizer(l1=0.000001,l2=0.000001), init='normal'))
predictivemodel.add(Dense(257, W_regularizer=WeightRegularizer(l1=0.000001,l2=0.000001), init='normal'))
predictivemodel.compile(loss='mean_squared_error', optimizer='adam', metrics=['accuracy'])
When I print model.summary()
I get following result:
Layer (type) Output Shape Param # Connected to
================================================================
dense_1 (Dense) (None, 514) 264710 dense_input_1[0][0]
________________________________________________________________
activation_1 (None, 514) 0 dense_1[0][0]
________________________________________________________________
dense_2 (Dense) (None, 257) 132355 activation_1[0][0]
================================================================
Total params: 397065
________________________________________________________________
For the dense_1 layer , number of params is 264710. This is obtained as : 514 (input values) * 514 (neurons in the first layer) + 514 (bias values)
For dense_2 layer, number of params is 132355. This is obtained as : 514 (input values) * 257 (neurons in the second layer) + 257 (bias values for neurons in the second layer)
No jQuery tag, so I'm assuming pure JavaScript
var spanText = document.getElementById('targetSpanId').innerText;
Is what you need
But in your case:
var spans = document.getElementById('test').getElementsByTagName('span');//returns node-list of spans
for (var i=0;i<spans.length;i++)
{
console.log(spans[i].innerText);//logs 1 for i === 0, 2 for i === 1 etc
}
Many thanks to @Ciro Santilli answer! I found that his choice for boundary is quite "unhappy" because all of thoose hyphens: in fact, as @Fake Name commented, when you are using your boundary inside request it comes with two more hyphens on front:
Example:
POST / HTTP/1.1
HOST: host.example.com
Cookie: some_cookies...
Connection: Keep-Alive
Content-Type: multipart/form-data; boundary=12345
--12345
Content-Disposition: form-data; name="sometext"
some text that you wrote in your html form ...
--12345
Content-Disposition: form-data; name="name_of_post_request" filename="filename.xyz"
content of filename.xyz that you upload in your form with input[type=file]
--12345
Content-Disposition: form-data; name="image" filename="picture_of_sunset.jpg"
content of picture_of_sunset.jpg ...
--12345--
I found on this w3.org page that is possible to incapsulate multipart/mixed header in a multipart/form-data, simply choosing another boundary string inside multipart/mixed and using that one to incapsulate data. At the end, you must "close" all boundary used in FILO order to close the POST request (like:
POST / HTTP/1.1
...
Content-Type: multipart/form-data; boundary=12345
--12345
Content-Disposition: form-data; name="sometext"
some text sent via post...
--12345
Content-Disposition: form-data; name="files"
Content-Type: multipart/mixed; boundary=abcde
--abcde
Content-Disposition: file; file="picture.jpg"
content of jpg...
--abcde
Content-Disposition: file; file="test.py"
content of test.py file ....
--abcde--
--12345--
Take a look at the link above.
There are multiple ways to do this in particular with Python 3.0 and above
Approach 1
This is simple approach but not recommended because you would not know exactly which line of code is actually throwing the exception:
def bad_method():
try:
sqrt = 0**-1
except Exception as e:
print(e)
bad_method()
Approach 2
This approach is recommended because it provides more detail about each exception. It includes:
The only drawback is tracback needs to be imported.
import traceback
def bad_method():
try:
sqrt = 0**-1
except Exception:
print(traceback.print_exc())
bad_method()
In pictures URL found in the Graph responses (the "http://photos-c.ak.fbcdn.net/" ones), just replace the default "_s.jpg" by "_n.jpg" (? normal size) or "_b.jpg" (? big size) or "_t.jpg" (thumbnail).
Hacakable URLs/REST API make the Web better.
I find jackson fasterxml
is one good choice to serializing/deserializing
bean with XML.
In order to copy a file from a container to the host, you can use the command
docker cp <containerId>:/file/path/within/container /host/path/target
Here's an example:
$ sudo docker cp goofy_roentgen:/out_read.jpg .
Here goofy_roentgen is the container name I got from the following command:
$ sudo docker ps
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
1b4ad9311e93 bamos/openface "/bin/bash" 33 minutes ago Up 33 minutes 0.0.0.0:8000->8000/tcp, 0.0.0.0:9000->9000/tcp goofy_roentgen
You can also use (part of) the Container ID. The following command is equivalent to the first
$ sudo docker cp 1b4a:/out_read.jpg .
char* str = "HELLO";
char c = str[1];
Keep in mind that arrays and strings in C begin indexing at 0 rather than 1, so "H" is str[0]
, "E" is str[1]
, the first "L" is str[2]
and so on.
You have no way to see who has checked out your repository using standard git commands such as git clone
, but you can see who has forked your repository on GitHub using the Network Graph Visualizer. At the time of this answer, you can access this feature in at least two ways:
For example, here is a partial screenshot of the rbenv network graph:
The "Members" tab at the top of the Network Graph will also show you a different view, listing the names of the people who currently have forks on GitHub. It obviously will not show people who cloned outside of GitHub, or folks who have subsequently deleted their forks.
The prompt command will echo text to the output:
prompt A useful comment.
select(*) from TableA;
Will be displayed as:
SQL> A useful comment.
SQL>
COUNT(*)
----------
0
git rev-parse --show-toplevel
could be enough if executed within a git repo.
From git rev-parse
man page:
--show-toplevel
Show the absolute path of the top-level directory.
For older versions (before 1.7.x), the other options are listed in "Is there a way to get the git root directory in one command?":
git rev-parse --git-dir
That would give the path of the .git
directory.
The OP mentions:
git rev-parse --show-prefix
which returns the local path under the git repo root. (empty if you are at the git repo root)
Note: for simply checking if one is in a git repo, I find the following command quite expressive:
git rev-parse --is-inside-work-tree
And yes, if you need to check if you are in a .git
git-dir folder:
git rev-parse --is-inside-git-dir
You can think it like php.ini files sub files.. php.ini file stores most of the configuration about php like curl enable disable. Where .htaccess makes this setting only for perticular directory and php.ini file store settings for its server' all directory...
I use this
$ cat ~/.wgetrc
check_certificate = off
$ wget https://raw.github.com/jquery/jquery/master/grunt.js
HTTP request sent, awaiting response... 200 OK
Length: 11339 (11K) [text/plain]
Saving to: `grunt.js'
I found a better way of doing this
function genrateJSONEngine() {
var XLSX = require('xlsx');
var workbook = XLSX.readFile('test.xlsx');
var sheet_name_list = workbook.SheetNames;
sheet_name_list.forEach(function (y) {
var array = workbook.Sheets[y];
var first = array[0].join()
var headers = first.split(',');
var jsonData = [];
for (var i = 1, length = array.length; i < length; i++) {
var myRow = array[i].join();
var row = myRow.split(',');
var data = {};
for (var x = 0; x < row.length; x++) {
data[headers[x]] = row[x];
}
jsonData.push(data);
}
You have to create your own log4j.properties
in the classpath folder.
This code worked nicely for me, thanks.
This is what i did with it. Some methods for stepping forward or backwards and one for going directly to a particular page. Its for a 6 page document in portrait view. It will work ok if you paste it into the implementation of the RootController of the pageViewController template.
-(IBAction)pageGoto:(id)sender {
//get page to go to
NSUInteger pageToGoTo = 4;
//get current index of current page
DataViewController *theCurrentViewController = [self.pageViewController.viewControllers objectAtIndex:0];
NSUInteger retreivedIndex = [self.modelController indexOfViewController:theCurrentViewController];
//get the page(s) to go to
DataViewController *targetPageViewController = [self.modelController viewControllerAtIndex:(pageToGoTo - 1) storyboard:self.storyboard];
DataViewController *secondPageViewController = [self.modelController viewControllerAtIndex:(pageToGoTo) storyboard:self.storyboard];
//put it(or them if in landscape view) in an array
NSArray *theViewControllers = nil;
theViewControllers = [NSArray arrayWithObjects:targetPageViewController, secondPageViewController, nil];
//check which direction to animate page turn then turn page accordingly
if (retreivedIndex < (pageToGoTo - 1) && retreivedIndex != (pageToGoTo - 1)){
[self.pageViewController setViewControllers:theViewControllers direction:UIPageViewControllerNavigationDirectionForward animated:YES completion:NULL];
}
if (retreivedIndex > (pageToGoTo - 1) && retreivedIndex != (pageToGoTo - 1)){
[self.pageViewController setViewControllers:theViewControllers direction:UIPageViewControllerNavigationDirectionReverse animated:YES completion:NULL];
}
}
-(IBAction)pageFoward:(id)sender {
//get current index of current page
DataViewController *theCurrentViewController = [self.pageViewController.viewControllers objectAtIndex:0];
NSUInteger retreivedIndex = [self.modelController indexOfViewController:theCurrentViewController];
//check that current page isn't first page
if (retreivedIndex < 5){
//get the page to go to
DataViewController *targetPageViewController = [self.modelController viewControllerAtIndex:(retreivedIndex + 1) storyboard:self.storyboard];
//put it(or them if in landscape view) in an array
NSArray *theViewControllers = nil;
theViewControllers = [NSArray arrayWithObjects:targetPageViewController, nil];
//add page view
[self.pageViewController setViewControllers:theViewControllers direction:UIPageViewControllerNavigationDirectionForward animated:YES completion:NULL];
}
}
-(IBAction)pageBack:(id)sender {
//get current index of current page
DataViewController *theCurrentViewController = [self.pageViewController.viewControllers objectAtIndex:0];
NSUInteger retreivedIndex = [self.modelController indexOfViewController:theCurrentViewController];
//check that current page isn't first page
if (retreivedIndex > 0){
//get the page to go to
DataViewController *targetPageViewController = [self.modelController viewControllerAtIndex:(retreivedIndex - 1) storyboard:self.storyboard];
//put it(or them if in landscape view) in an array
NSArray *theViewControllers = nil;
theViewControllers = [NSArray arrayWithObjects:targetPageViewController, nil];
//add page view
[self.pageViewController setViewControllers:theViewControllers direction:UIPageViewControllerNavigationDirectionReverse animated:YES completion:NULL];
}
}
The simplest (Non Win32) way is to add a UserForm to your VBA project (if you don't already have one) or alternatively add a reference to Microsoft Forms 2 Object Library, then from a sheet/module you can simply:
With New MSForms.DataObject
.SetText "http://zombo.com"
.PutInClipboard
End With
Here is a theoretical answer. That can be found here
A { get set } property cannot be a constant stored property. It should be a computed property and both get and set should be implemented.
I think that this one is the simplest one and it accepts European and USA way of writing numbers e.g. USA 10,555.12 European 10.555,12 Also this one does not allow several commas or dots one after each other e.g. 10..22 or 10,.22 In addition to this numbers like .55 or ,55 would pass. This may be handy.
^([,|.]?[0-9])+$
pytest captures the stdout from individual tests and displays them only on certain conditions, along with the summary of the tests it prints by default.
Extra summary info can be shown using the '-r' option:
pytest -rP
shows the captured output of passed tests.
pytest -rx
shows the captured output of failed tests (default behaviour).
The formatting of the output is prettier with -r than with -s.
When the Device displays the message go to Run->Attach debbuger, then select a debbuger. it'll start the activity.
In your pattern, you simply want to match all text between the two tags. Thus, you could use for example a [\w\W]
to match all characters.
function getTextBetweenTags($string, $tagname) {
$pattern = "/<$tagname>([\w\W]*?)<\/$tagname>/";
preg_match($pattern, $string, $matches);
return $matches[1];
}
There is no mention about nine-patch files here. Yes, you have to create the file, however it's quite easy job and it's really "cross-version and transparency supporting" solution. If the file is placed to the drawable-nodpi
directory, it works px
based, and in the drawable-mdpi
works approximately as dp base (thanks to resample).
Example file for the original question (border-right:1px solid red;) is here:
Just place it to the drawable-nodpi
directory.
I also got this terrible error and found a solution for this...
- Right Click on the Solution name
- Click Clean Solution
- Restart Visual Studio
- Goto project Properties >> Build
- Change Configuration to Release
- Start Debugging (F5)
1) , 2)
4) , 5)
Hope this will help you also.
You can try that too, for solve timeout problem:
If you didn't add httpRuntime to your webconfig, add that in <system.web>
tag
<sytem.web>
<httpRuntime maxRequestLength="20000" executionTimeout="999999"/>
</system.web>
and
Modify your connection string like this;
<add name="connstring" connectionString="Data Source=DSourceName;Initial Catalog=DBName;Integrated Security=True;Max Pool Size=50000;Pooling=True;" providerName="System.Data.SqlClient" />
At last use
try
{...}
catch
{...}
finaly
{
connection.close();
}
I think cffi for python can be an option.
The goal is to call C code from Python. You should be able to do so without learning a 3rd language: every alternative requires you to learn their own language (Cython, SWIG) or API (ctypes). So we tried to assume that you know Python and C and minimize the extra bits of API that you need to learn.
What you're doing is valid for the current session (limited to the terminal that you're working in). You need to persist those changes. Consider adding commands in steps 1-3 above to your ${HOME}/.bashrc
.
pgAdmin has GUI for data import since 1.16. You have to create your table first and then you can import data easily - just right-click on the table name and click on Import.
First of all, your description is misleading. Double
is a floating point data type. You presumably want to pad your digits with leading zeros in a string. The following code does that:
$s = sprintf('%02d', $digit);
For more information, refer to the documentation of sprintf
.
A bit late but I used jQuery ajax method. But I did not want to send a request every second if I haven't got the response back from the last request, so I did this.
function request(){
if(response == true){
// This makes it unable to send a new request
// unless you get response from last request
response = false;
var req = $.ajax({
type:"post",
url:"request-handler.php",
data:{data:"Hello World"}
});
req.done(function(){
console.log("Request successful!");
// This makes it able to send new request on the next interval
response = true;
});
}
setTimeout(request(),1000);
}
request();
I would use Different IDs but assign each DIV the same class.
<div id="c-1" class="countdown"></div>
<div id="c-2" class="countdown"></div>
This also has the added benefit of being able to reconstruct the IDs based off of the return of jQuery('.countdown').length
Ok what about adding multiple classes to each countdown timer. IE:
<div class="countdown c-1"></div>
<div class="countdown c-2"></div>
<div class="countdown c-1"></div>
That way you get the best of both worlds. It even allows repeat 'IDS'
Ok, I know I'm late to the party, but here is the syntax I think is best. Add a schema name if needed to the OBJECT_ID clause.
IF OBJECTPROPERTY(OBJECT_ID(N'My_FK_name'),'IsConstraint') =1
ALTER TABLE dbo.TableName DROP CONSTRAINT My_FK_name
I know this is quite an old question, but with Java 8's Streams you can get a range of int
s like this:
// gives an IntStream of integers from 0 through Integer.MAX_VALUE
IntStream.rangeClosed(0, Integer.MAX_VALUE);
Then you can do something like this:
if (IntStream.rangeClosed(0, Integer.MAX_VALUE).matchAny(n -> n == A)) {
// do something
} else {
// do something else
}
Why write complicated code when you could make it simple?
Indeed, if you are absolutely going to use the Optional
class, the most simple code is what you have already written ...
if (user.isPresent())
{
doSomethingWithUser(user.get());
}
This code has the advantages of being
Just because Oracle has added the Optional
class in Java 8 doesn't mean that this class must be used in all situation.
Stored procedure is the best way to do it. Because Meherzad's solution would work only if the data follows the same order.
If we have a table structure like this
col1 | col2 | col3
-----+------+------
3 | k | 7
5 | d | 3
1 | a | 5
6 | o | 2
2 | 0 | 8
It wont work. SQL Fiddle Demo
Here is a sample procedure code to achieve the same.
delimiter //
CREATE PROCEDURE chainReaction
(
in inputNo int
)
BEGIN
declare final_id int default NULL;
SELECT col3
INTO final_id
FROM table1
WHERE col1 = inputNo;
IF( final_id is not null) THEN
INSERT INTO results(SELECT col1, col2, col3 FROM table1 WHERE col1 = inputNo);
CALL chainReaction(final_id);
end if;
END//
delimiter ;
call chainReaction(1);
SELECT * FROM results;
DROP TABLE if exists results;
Try this option:
radio1.Items.FindByValue("1").Selected = true;
In opposite to the most comments, I think it is possible to get the client's hostname (machine name) in plain PHP, but it's a little bit "dirty".
By requesting "NTLM" authorization via HTTP header...
if (!isset($headers['AUTHORIZATION']) || substr($headers['AUTHORIZATION'],0,4) !== 'NTLM'){
header('HTTP/1.1 401 Unauthorized');
header('WWW-Authenticate: NTLM');
exit;
}
You can force the client to send authorization credentials via NTLM format. The NTLM hash sent by the client to server contains, besides the login credtials, the clients machine name. This works cross-browser and PHP only.
$auth = $headers['AUTHORIZATION'];
if (substr($auth,0,5) == 'NTLM ') {
$msg = base64_decode(substr($auth, 5));
if (substr($msg, 0, 8) != "NTLMSSPx00")
die('error header not recognised');
if ($msg[8] == "x01") {
$msg2 = "NTLMSSPx00x02"."x00x00x00x00".
"x00x00x00x00".
"x01x02x81x01".
"x00x00x00x00x00x00x00x00".
"x00x00x00x00x00x00x00x00".
"x00x00x00x00x30x00x00x00";
header('HTTP/1.1 401 Unauthorized');
header('WWW-Authenticate: NTLM '.trim(base64_encode($msg2)));
exit;
}
else if ($msg[8] == "x03") {
function get_msg_str($msg, $start, $unicode = true) {
$len = (ord($msg[$start+1]) * 256) + ord($msg[$start]);
$off = (ord($msg[$start+5]) * 256) + ord($msg[$start+4]);
if ($unicode)
return str_replace("\0", '', substr($msg, $off, $len));
else
return substr($msg, $off, $len);
}
$user = get_msg_str($msg, 36);
$domain = get_msg_str($msg, 28);
$workstation = get_msg_str($msg, 44);
print "You are $user from $workstation.$domain";
}
}
And yes, it's not a plain and easy "read the machine name function", because the user is prompted with an dialog, but it's an example, that it is indeed possible (against the other statements here).
Full code can be found here: https://en.code-bude.net/2017/05/07/how-to-read-client-hostname-in-php/
You can increase the capacity of the stack by the following :
import sys
sys.setrecursionlimit(10000)
To avoid that exception, if you are using JUnit and Spring try adding this in every test class:
@DirtiesContext(classMode = DirtiesContext.ClassMode.AFTER_CLASS)
I know that this is rather old also. I recently had a need to create a context menu that I inject into other sites that have different properties based n the element clicked.
It's rather rough, and there are probable better ways to achieve this. It uses the jQuery Context menu Library Located Here
I enjoyed creating it and though that you guys might have some use out of it.
Here is the fiddle. I hope that it can hopefully help someone out there.
$(function() {
function createSomeMenu() {
var all_array = '{';
var x = event.clientX,
y = event.clientY,
elementMouseIsOver = document.elementFromPoint(x, y);
if (elementMouseIsOver.closest('a')) {
all_array += '"Link-Fold": {"name": "Link", "icon": "fa-external-link", "items": {"fold2-key1": {"name": "Open Site in New Tab"}, "fold2-key2": {"name": "Open Site in Split Tab"}, "fold2-key3": {"name": "Copy URL"}}},';
}
if (elementMouseIsOver.closest('img')) {
all_array += '"Image-Fold": {"name": "Image","icon": "fa-picture-o","items": {"fold1-key1": {"name":"Download Image"},"fold1-key2": {"name": "Copy Image Location"},"fold1-key3": {"name": "Go To Image"}}},';
}
all_array += '"copy": {"name": "Copy","icon": "copy"},"paste": {"name": "Paste","icon": "paste"},"edit": {"name": "Edit HTML","icon": "fa-code"}}';
return JSON.parse(all_array);
}
// setup context menu
$.contextMenu({
selector: 'body',
build: function($trigger, e) {
return {
callback: function(key, options) {
var m = "clicked: " + key;
console.log(m);
},
items: createSomeMenu()
};
}
});
});
To read from the stdin:
char string[512];
fgets(string, sizeof(string), stdin); /* no buffer overflows here, you're safe! */
Unfortunately, the error message doesn't provide clear information about what the real problem is. For that, some debugging is required.
From the stack trace, here's the origin of the error in the multer
package:
function wrappedFileFilter (req, file, cb) {
if ((filesLeft[file.fieldname] || 0) <= 0) {
return cb(makeError('LIMIT_UNEXPECTED_FILE', file.fieldname))
}
filesLeft[file.fieldname] -= 1
fileFilter(req, file, cb)
}
And the strange (possibly mistaken) translation applied here is the source of the message itself...
'LIMIT_UNEXPECTED_FILE': 'Unexpected field'
filesLeft
is an object that contains the name of the field your server is expecting, and file.fieldname
contains the name of the field provided by the client. The error is thrown when there is a mismatch between the field name provided by the client and the field name expected by the server.
The solution is to change the name on either the client or the server so that the two agree.
For example, when using fetch
on the client...
var theinput = document.getElementById('myfileinput')
var data = new FormData()
data.append('myfile',theinput.files[0])
fetch( "/upload", { method:"POST", body:data } )
And the server would have a route such as the following...
app.post('/upload', multer(multerConfig).single('myfile'),function(req, res){
res.sendStatus(200)
}
Notice that it is myfile
which is the common name (in this example).
It's a toss up between Head First Design Patterns, for many of the reasons cited above, and Perl Testing: A Developer's Notebook, which should be one of the bibles for any Perl programmer wanting to write maintainable code.
[].concat.apply([], [array1, array2, ...])
edit: proof of efficiency: http://jsperf.com/multi-array-concat/7
edit2: Tim Supinie mentions in the comments that this may cause the interpreter to exceed the call stack size. This is perhaps dependent on the js engine, but I've also gotten "Maximum call stack size exceeded" on Chrome at least. Test case: [].concat.apply([], Array(300000).fill().map(_=>[1,2,3]))
. (I've also gotten the same error using the currently accepted answer, so one is anticipating such use cases or building a library for others, special testing may be necessary no matter which solution you choose.)
with open("input", "rb") as input:
with open("output", "wb") as output:
while True:
data = input.read(1024)
if data == "":
break
output.write(data)
The above will read 1 kilobyte at a time, and write it. You can support incredibly large files this way, as you won't need to read the entire file into memory.
A quick, clean approach using very little JS and CSS padding: http://jsfiddle.net/benjamincharity/ZcTsT/14/
var headerHeight = $('#header').height(),
footerHeight = $('#footer').height();
$('#content').css({
'padding-top': headerHeight,
'padding-bottom': footerHeight
});
Use this
//*[@id='popover-search']/div/div/ul/li[1]/a/span[contains(text(),'Some text')]
OR
//*[@id='popover-search']/div/div/ul/li[1]/a/span[contains(.,'Some text')]
Angular has several timepoints to start executing functions. If you seek for something like jQuery's
$(document).ready();
You may find this analog in angular to be very useful:
$scope.$watch('$viewContentLoaded', function(){
//do something
});
This one is helpful when you want to manipulate the DOM elements. It will start executing only after all te elements are loaded.
UPD: What is said above works when you want to change css properties. However, sometimes it doesn't work when you want to measure the element properties, such as width, height, etc. In this case you may want to try this:
$scope.$watch('$viewContentLoaded',
function() {
$timeout(function() {
//do something
},0);
});
You can use
x = [1, 2, 3]
disp(sprintf('Answer: (%d, %d, %d)', x))
This results in
Answer: (1, 2, 3)
For vectors of arbitrary size, you can use
disp(strrep(['Answer: (' sprintf(' %d,', x) ')'], ',)', ')'))
An alternative way would be
disp(strrep(['Answer: (' num2str(x, ' %d,') ')'], ',)', ')'))
Here you go:
InputStream is = new ByteArrayInputStream( myString.getBytes() );
Update For multi-byte support use (thanks to Aaron Waibel's comment):
InputStream is = new ByteArrayInputStream(Charset.forName("UTF-16").encode(myString).array());
Please see ByteArrayInputStream manual.
It is safe to use a charset argument in String#getBytes(charset) method above.
After JDK 7+ you can use
java.nio.charset.StandardCharsets.UTF_16
instead of hardcoded encoding string:
InputStream is = new ByteArrayInputStream(StandardCharsets.UTF_16.encode(myString).array());
You can use the Bean Comparator to sort on any property in your custom class.
Basically BindingResult
is an interface which dictates how the object that stores the result of validation should store and retrieve the result of the validation(errors, attempt to bind to disallowed fields etc)
From Spring MVC Form Validation with Annotations Tutorial:
[
BindingResult
] is Spring’s object that holds the result of the validation and binding and contains errors that may have occurred. TheBindingResult
must come right after the model object that is validated or else Spring will fail to validate the object and throw an exception.When Spring sees
@Valid
, it tries to find the validator for the object being validated. Spring automatically picks up validation annotations if you have “annotation-driven” enabled. Spring then invokes the validator and puts any errors in theBindingResult
and adds the BindingResult to the view model.
As a complement to the answers given above; do not forget about Form MinimumSize Property, in case you require to create smaller Forms.
Example Bellow:
private void SetDefaultWindowSize()
{
int sizeW, sizeH;
sizeW = 180;
sizeH = 100;
var size = new Size(sizeW, sizeH);
Size = size;
MinimumSize = size;
}
private void SetNewSize()
{
Size = new Size(Width, 10);
}
I use a combination of json.get() and instanceof to read in values that might be either integers or integer strings.
These three test cases illustrate:
int val;
Object obj;
JSONObject json = new JSONObject();
json.put("number", 1);
json.put("string", "10");
json.put("other", "tree");
obj = json.get("number");
val = (obj instanceof Integer) ? (int) obj : (int) Integer.parseInt((String) obj);
System.out.println(val);
obj = json.get("string");
val = (obj instanceof Integer) ? (int) obj : (int) Integer.parseInt((String) obj);
System.out.println(val);
try {
obj = json.get("other");
val = (obj instanceof Integer) ? (int) obj : (int) Integer.parseInt((String) obj);
} catch (Exception e) {
// throws exception
}
var select = $('#mySelect');
select.find('option').remove().end()
.append($('<option/>').val('').text('Select'));
var data = [{"id":1,"title":"Option one"}, {"id":2,"title":"Option two"}];
for(var i in data) {
var d = data[i];
var option = $('<option/>').val(d.id).text(d.title);
select.append(option);
}
select.val('');
<br />
will take as much space as text-filled row of your <p>
, you can't change that. If you want larger, it means you want to separate into paragraph, so add other <p>
. Don't forget to be the most semantic you can ;)
Here is elegant solution using Kotlin
extensions:
data class ApiError(val code: Int, val message: String?) {
companion object {
val EMPTY_API_ERROR = ApiError(-1, null)
}
}
fun Throwable.getApiError(): ApiError? {
if (this is HttpException) {
try {
val errorJsonString = this.response()?.errorBody()?.string()
return Gson().fromJson(errorJsonString, ApiError::class.java)
} catch (exception: Exception) {
// Ignore
}
}
return EMPTY_API_ERROR
}
and usage:
showError(retrofitThrowable.getApiError()?.message)
You go to http://www.rpmfind.net and search for the file.
You'll get results for a lot of different distros and versions, but quite likely Fedora and/or CentOS will pop up too and you'll know the package name to install with yum
Sameer:
float l = new Float(x/y)
will not work, as it will compute integer division of x and y first, then construct a float from it.
float result = (float) x / (float) y;
Is semantically the best candidate.