In case if you get this exception in SpringBoot
application even though the entities are annotated with Entity
annotation, it might be due to the spring not aware of where to scan for entities
To explicitly specify the package, add below
@SpringBootApplication
@EntityScan({"model.package.name"})
public class SpringBootApp {...}
note: If you model classes resides in the same or sub packages of SpringBootApplication
annotated class, no need to explicitly declare the EntityScan
, by default it will scan
I had this problem when I try to write a very long url, the following works.
image_url = %w(
http://minio.127.0.0.1.xip.io:9000/
bucket29/docs/b7cfab0e-0119-452c-b262-1b78e3fccf38/
28ed3774-b234-4de2-9a11-7d657707f79c?
X-Amz-Algorithm=AWS4-HMAC-SHA256&
X-Amz-Credential=ABABABABABABABABA
%2Fus-east-1%2Fs3%2Faws4_request&
X-Amz-Date=20170702T000940Z&
X-Amz-Expires=3600&X-Amz-SignedHeaders=host&
X-Amz-Signature=ABABABABABABABABABABAB
ABABABABABABABABABABABABABABABABABABA
).join
Note, there must not be any newlines, white spaces when the url string is formed. If you want newlines, then use HEREDOC.
Here you have indentation for readability, ease of modification, without the fiddly quotes and backslashes on every line. The cost of joining the strings should be negligible.
GRANT ALL ON *.* TO 'user'@'localhost' with GRANT OPTION;
Just log in from root using the respective password if any and simply run the above command to whatever the user is.
For example:
GRANT ALL ON *.* TO 'root'@'%' with GRANT OPTION;
Additionally, this will only work if Value is of type bool. Normally this is used with predicates. Any predicate would be generally used find whether there is any element satisfying a given condition. Here you're just doing a map from your element i to a bool property. It will search for an "i" whose Value property is true. Once done, the method will return true.
A simple solution is using the scalers offered by the sklearn.preprocessing library.
scaler = sk.MinMaxScaler(feature_range=(0, 250))
scaler = scaler.fit(X)
X_scaled = scaler.transform(X)
# Checking reconstruction
X_rec = scaler.inverse_transform(X_scaled)
The error X_rec-X will be zero. You can adjust the feature_range for your needs, or even use a standart scaler sk.StandardScaler()
You need to pass the variable into the function:
$data = 'My data';
function menugen($data)
{
echo $data;
}
the answer https://stackoverflow.com/a/6132093/1498669 is right.
There is also an update to both 2002 and 2003 runtimes just do an search on microsoft download
and you find the offical updates to the products
however, the latest patches seem to be:
Using reshape2
and dplyr
. Your data:
df <- read.table(text=
"tea coke beer water gender
14.55 26.50793651 22.53968254 40 1
24.92997199 24.50980392 26.05042017 24.50980393 2
23.03732304 30.63063063 25.41827542 20.91377091 1
225.51781276 24.6064623 24.85501243 50.80645161 1
24.53662842 26.03706973 25.24271845 24.18358341 2", header=TRUE)
Getting data into correct form:
library(reshape2)
library(dplyr)
df.melt <- melt(df, id="gender")
bar <- group_by(df.melt, variable, gender)%.%summarise(mean=mean(value))
Plotting:
library(ggplot2)
ggplot(bar, aes(x=variable, y=mean, fill=factor(gender)))+
geom_bar(position="dodge", stat="identity")
Update, if you are running SQL Server 2012 see: https://stackoverflow.com/a/10309947
The problem is that the SQL Server implementation of the Over clause is somewhat limited.
Oracle (and ANSI-SQL) allow you to do things like:
SELECT somedate, somevalue,
SUM(somevalue) OVER(ORDER BY somedate
ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW)
AS RunningTotal
FROM Table
SQL Server gives you no clean solution to this problem. My gut is telling me that this is one of those rare cases where a cursor is the fastest, though I will have to do some benchmarking on big results.
The update trick is handy but I feel its fairly fragile. It seems that if you are updating a full table then it will proceed in the order of the primary key. So if you set your date as a primary key ascending you will probably
be safe. But you are relying on an undocumented SQL Server implementation detail (also if the query ends up being performed by two procs I wonder what will happen, see: MAXDOP):
Full working sample:
drop table #t
create table #t ( ord int primary key, total int, running_total int)
insert #t(ord,total) values (2,20)
-- notice the malicious re-ordering
insert #t(ord,total) values (1,10)
insert #t(ord,total) values (3,10)
insert #t(ord,total) values (4,1)
declare @total int
set @total = 0
update #t set running_total = @total, @total = @total + total
select * from #t
order by ord
ord total running_total
----------- ----------- -------------
1 10 10
2 20 30
3 10 40
4 1 41
You asked for a benchmark this is the lowdown.
The fastest SAFE way of doing this would be the Cursor, it is an order of magnitude faster than the correlated sub-query of cross-join.
The absolute fastest way is the UPDATE trick. My only concern with it is that I am not certain that under all circumstances the update will proceed in a linear way. There is nothing in the query that explicitly says so.
Bottom line, for production code I would go with the cursor.
Test data:
create table #t ( ord int primary key, total int, running_total int)
set nocount on
declare @i int
set @i = 0
begin tran
while @i < 10000
begin
insert #t (ord, total) values (@i, rand() * 100)
set @i = @i +1
end
commit
Test 1:
SELECT ord,total,
(SELECT SUM(total)
FROM #t b
WHERE b.ord <= a.ord) AS b
FROM #t a
-- CPU 11731, Reads 154934, Duration 11135
Test 2:
SELECT a.ord, a.total, SUM(b.total) AS RunningTotal
FROM #t a CROSS JOIN #t b
WHERE (b.ord <= a.ord)
GROUP BY a.ord,a.total
ORDER BY a.ord
-- CPU 16053, Reads 154935, Duration 4647
Test 3:
DECLARE @TotalTable table(ord int primary key, total int, running_total int)
DECLARE forward_cursor CURSOR FAST_FORWARD
FOR
SELECT ord, total
FROM #t
ORDER BY ord
OPEN forward_cursor
DECLARE @running_total int,
@ord int,
@total int
SET @running_total = 0
FETCH NEXT FROM forward_cursor INTO @ord, @total
WHILE (@@FETCH_STATUS = 0)
BEGIN
SET @running_total = @running_total + @total
INSERT @TotalTable VALUES(@ord, @total, @running_total)
FETCH NEXT FROM forward_cursor INTO @ord, @total
END
CLOSE forward_cursor
DEALLOCATE forward_cursor
SELECT * FROM @TotalTable
-- CPU 359, Reads 30392, Duration 496
Test 4:
declare @total int
set @total = 0
update #t set running_total = @total, @total = @total + total
select * from #t
-- CPU 0, Reads 58, Duration 139
Some of it is native, the rest is available through libraries.
For example Datejs is a good international date library.
For the rest, it's just about language translation, and JavaScript is natively Unicode compatible (as well as all major browsers).
You need to decode data from input string into unicode, before using it, to avoid encoding problems.
field.text = data.decode("utf8")
For those trouble shooting, it is important to know that ng-include requires the url path to be from the app root directory and not from the same directory where the partial.html lives. (whereas partial.html is the view file that the inline ng-include markup tag can be found).
For example:
Correct: div ng-include src=" '/views/partials/tabSlides/add-more.html' ">
Incorrect: div ng-include src=" 'add-more.html' ">
First I recommend you to read following book;
Here is some functions and their expected complexities. Numbers are indicating statement execution frequencies.
Following Big-O Complexity Chart also taken from bigocheatsheet
Lastly very simple showcase there is shows how it is calculated;
Anatomy of a program’s statement execution frequencies.
Analyzing the running time of a program (example).
None of the suggested solutions worked for me.
What actually works (with any encoding):
Copy/paste the data from the csv-file (open in a text editor), then perform "text to columns" --> data gets transformed incorrectly.
The next stap is to go to the nearest empty column or empty worksheet and copy/paste again (same thing what you already have in your clipboard) --> automagically works now.
People will learn your interface from code completion in their IDE or in Javadoc, not from reading the source. So there's no point in putting "public" in the source - nobody's reading the source.
Try this.(IE8+)
//Define function
function removeJsonAttrs(json,attrs){
return JSON.parse(JSON.stringify(json,function(k,v){
return attrs.indexOf(k)!==-1 ? undefined: v;
}));}
//use object
var countries = {};
countries.results = [
{id:'AF',name:'Afghanistan'},
{id:'AL',name:'Albania'},
{id:'DZ',name:'Algeria'}
];
countries = removeJsonAttrs(countries,["name"]);
//use array
var arr = [
{id:'AF',name:'Afghanistan'},
{id:'AL',name:'Albania'},
{id:'DZ',name:'Algeria'}
];
arr = removeJsonAttrs(arr,["name"]);
This error may also arise when you are trying to run a terminal command (that requires root password) from some non-shell script, eg sudo ls
(in backticks) from a Ruby program. In this case, you can use Expect utility (http://en.wikipedia.org/wiki/Expect) or its alternatives.
For example, in Ruby to execute sudo ls
without getting sudo: no tty present and no askpass program specified
, you can run this:
require 'ruby_expect'
exp = RubyExpect::Expect.spawn('sudo ls', :debug => true)
exp.procedure do
each do
expect "[sudo] password for _your_username_:" do
send _your_password_
end
end
end
[this uses one of the alternatives to Expect TCL extension: ruby_expect gem].
Bootstrap is the world’s most popular and widely used open-source framework for developing with HTML, CSS, and JS. It is a front end framework of HTML. Bootstrap helps in building responsive websites or web applications and a 12-column grid system that helps dynamically adjust the website to a suitable screen resolution. The current version of bootstrap is 4.3.1 and the bootstrap team has also officially announced Bootstrap 5 version and changes like removing jquery from bootstrap. Some of the crucial reasons why bootstrap framework is most preferable are
It is easy to use
Bootstrap has a big community support
Customizations can be done easily
It increases development speed
Responsiveness
For more details, you can check the official website: https://getbootstrap.com/
You are printing a formatted string. The {0} means to insert the first parameter following the format string; in this case the value associated with the key "rtf".
For String.Format, which is similar, if you had something like
// Format string {0} {1}
String.Format("This {0}. The value is {1}.", "is a test", 42 )
you'd create a string "This is a test. The value is 42".
You can also use expressions, and print values out multiple times:
// Format string {0} {1} {2}
String.Format("Fib: {0}, {0}, {1}, {2}", 1, 1+1, 1+2)
yielding "Fib: 1, 1, 2, 3"
See more at http://msdn.microsoft.com/en-us/library/txafckwd.aspx, which talks about composite formatting.
You haven't put the shared library in a location where the loader can find it. look inside the /usr/local/opencv
and /usr/local/opencv2
folders and see if either of them contains any shared libraries (files beginning in lib
and usually ending in .so
). when you find them, create a file called /etc/ld.so.conf.d/opencv.conf
and write to it the paths to the folders where the libraries are stored, one per line.
for example, if the libraries were stored under /usr/local/opencv/libopencv_core.so.2.4
then I would write this to my opencv.conf
file:
/usr/local/opencv/
Then run
sudo ldconfig -v
If you can't find the libraries, try running
sudo updatedb && locate libopencv_core.so.2.4
in a shell. You don't need to run updatedb
if you've rebooted since compiling OpenCV.
References:
About shared libraries on Linux: http://www.eyrie.org/~eagle/notes/rpath.html
About adding the OpenCV shared libraries: http://opencv.willowgarage.com/wiki/InstallGuide_Linux
Install GD Library
Which OS you are using?
http://php.net/manual/en/image.installation.php
Windows http://www.dmxzone.com/go/5001/how-do-i-install-gd-in-windows/
Linux http://www.cyberciti.biz/faq/ubuntu-linux-install-or-add-php-gd-support-to-apache/
If you use Bitnami installer for wampstack, go to:
c:/Bitnami/wampstack-5.6.24-0/apache/conf (of course your version number may be different)
Open the file: httpd.conf in a text editor like Visual Studio code or Notepad ++
Do a search for "DocumentRoot". See image.
You will be able to change the directory in this file.
You can directly use String.valueOf()
String.valueOf(charSequence)
Though this is same as toString()
it does a null check on the charSequence
before actually calling toString.
This is useful when a method can return either a charSequence
or null
value.
I had the same problem but I fixed it by saving the file in a different location and then copying the file and pasting it in the location where I wanted it to be. I used the option to replace the the existing file and that did the trick for me. I know this is not the most efficient way but it works and takes less than 15 seconds.
One general solution to such tiny errors is that you close eclipse and start is again.. 3 irritating problems were solved.. its the problem with eclipse.. some times it didn resolve "R.id", the it didn find @string/somebutton, and then again some random thing... if nothing logical comes in your mind, try this, n conjure d result.. :)
You can do this way, providing Json or Any other variable:
1) For exemple, in the controller, you can use Json.NET
to provide Json
to the ViewBag
:
ViewBag.Number = 10;
ViewBag.FooObj = JsonConvert.SerializeObject(new Foo { Text = "Im a foo." });
2) In the View
, put the script like this at the bottom of the page.
<script type="text/javascript">
var number = parseInt(@ViewBag.Number); //Accessing the number from the ViewBag
alert("Number is: " + number);
var model = @Html.Raw(@ViewBag.FooObj); //Accessing the Json Object from ViewBag
alert("Text is: " + model.Text);
</script>
I've created SQLite databases up to 3.5GB in size with no noticeable performance issues. If I remember correctly, I think SQLite2 might have had some lower limits, but I don't think SQLite3 has any such issues.
According to the SQLite Limits page, the maximum size of each database page is 32K. And the maximum pages in a database is 1024^3. So by my math that comes out to 32 terabytes as the maximum size. I think you'll hit your file system's limits before hitting SQLite's!
Use setInterval
instead of setTimeout
. Though in this case either will be fine but setTimeout
inherently triggers only once setInterval
continues indefinitely.
<script language="javascript">
setInterval(function(){
window.location.reload(1);
}, 30000);
</script>
Are you sure, that specified database and table exists? Did you try to look at your database using any database client? For example command-line MySQL client bundled with MySQL server. Or if you a developer newbie, there are dozens of a GUI and web interface clients (HeidiSQL, MySQL Workbench, phpMyAdmin and many more). So first check, if your table creation script was successful and had created what it have to.
BTW why do you have a script for creating the database structure? It's usualy a nonrecurring operation, so write the script to do this is unneeded. It's useful only in case of need of repeatedly creating and manipulating the database structure on the fly.
A function name can become a variable name (and thus be passed as an argument) by dropping the parentheses. A variable name can become a function name by adding the parentheses.
In your example, equate the variable rules
to one of your functions, leaving off the parentheses and the mention of the argument. Then in your game()
function, invoke rules( v )
with the parentheses and the v
parameter.
if puzzle == type1:
rules = Rule1
else:
rules = Rule2
def Game(listA, listB, rules):
if rules( v ) == True:
do...
else:
do...
Not sure why but none of the above solution work for me. So sharing what worked:
public void readXLS(string FilePath)
{
FileInfo existingFile = new FileInfo(FilePath);
using (ExcelPackage package = new ExcelPackage(existingFile))
{
//get the first worksheet in the workbook
ExcelWorksheet worksheet = package.Workbook.Worksheets[1];
int colCount = worksheet.Dimension.End.Column; //get Column Count
int rowCount = worksheet.Dimension.End.Row; //get row count
for (int row = 1; row <= rowCount; row++)
{
for (int col = 1; col <= colCount; col++)
{
Console.WriteLine(" Row:" + row + " column:" + col + " Value:" + worksheet.Cells[row, col].Value?.ToString().Trim());
}
}
}
}
run the below command in command prompt
tnsping Datasource
This should give a response like below
C:>tnsping *******
TNS Ping Utility for *** Windows: Version *** - Production on *****
Copyright (c) 1997, 2014, Oracle. All rights reserved.
Used parameter files: c:\oracle*****
Used **** to resolve the alias Attempting to contact (description=(address_list=(address=(protocol=tcp)(host=)(port=)))(connect_data=(server=)(service_name=)(failover_mode=(type=)(method=)(retries=)(delay=))))** OK (**** msec)
Add the text 'Datasource=' in beginning and credentials at the end. the final string should be
Data Source=(description=(address_list=(address=(protocol=tcp)(host=)(port=)))(connect_data=(server=)(service_name=)(failover_mode=(type=)(method=)(retries=)(delay=))));User Id=;Password=;**
Use this as the connection string to connect to oracle db.
If one want to keep getting updated processes (on the example, 2 seconds) on a shell session without having to manually interact with it use:
watch -n 2 'mysql -h 127.0.0.1 -P 3306 -u some_user -psome_pass some_database -e "show full processlist;"'
The only bad thing about the show [full] processlist
is that you can't filter the output result. On the other hand, issuing the SELECT * FROM INFORMATION_SCHEMA.PROCESSLIST
open possibilities to remove from the output anything you don't want to see:
SELECT * from INFORMATION_SCHEMA.PROCESSLIST
WHERE DB = 'somedatabase'
AND COMMAND <> 'Sleep'
AND HOST NOT LIKE '10.164.25.133%' \G
Based on @Staale's answer, and in an attempt not to rely on third party libraries, I would implement the File System approach by inspecting first package physical location with:
import java.io.File;
import java.io.FileFilter;
import java.util.ArrayList;
...
Class<?>[] foundClasses = new Class<?>[0];
final ArrayList<Class<?>> foundClassesDyn = new ArrayList<Class<?>>();
new java.io.File(
klass.getResource(
"/" + curPackage.replace( "." , "/")
).getFile()
).listFiles(
new java.io.FileFilter() {
public boolean accept(java.io.File file) {
final String classExtension = ".class";
if ( file.isFile()
&& file.getName().endsWith(classExtension)
// avoid inner classes
&& ! file.getName().contains("$") )
{
try {
String className = file.getName();
className = className.substring(0, className.length() - classExtension.length());
foundClassesDyn.add( Class.forName( curPackage + "." + className ) );
} catch (ClassNotFoundException e) {
e.printStackTrace(System.out);
}
}
return false;
}
}
);
foundClasses = foundClassesDyn.toArray(foundClasses);
Why invent wheels yourself while there is a car ready for you? I just find this tools super easy and intuitive to use: Advanced Installer. This one minute video should be enough to impress you. Here is the illustrative user guide.
According to some comments on Super User it still works :) It just should be copied back to the plugins folder (if it's in the disabled folder) or downloaded from Plugins Central. I have downloaded it a few minutes ago and succeeded in using it.
Of course, be warned: this plugin COULD be unstable in some situations - that's why it was disabled.
Delays are done with the time library, specifically the time.sleep()
function.
To just make it wait for a second:
from time import sleep
sleep(1)
This works because by doing:
from time import sleep
You extract the sleep function only from the time library, which means you can just call it with:
sleep(seconds)
Rather than having to type out
time.sleep()
Which is awkwardly long to type.
With this method, you wouldn't get access to the other features of the time library and you can't have a variable called sleep
. But you could create a variable called time
.
Doing from [library] import [function] (, [function2])
is great if you just want certain parts of a module.
You could equally do it as:
import time
time.sleep(1)
and you would have access to the other features of the time library like time.clock()
as long as you type time.[function]()
, but you couldn't create the variable time because it would overwrite the import. A solution to this to do
import time as t
which would allow you to reference the time library as t
, allowing you to do:
t.sleep()
This works on any library.
$('.nav a').click(function () {_x000D_
$('.navbar-collapse').collapse('hide');_x000D_
});
_x000D_
In this state:
The thread is reading and processing rows for a SELECT statement, and sending data to the client.
Because operations occurring during this this state tend to perform large amounts of disk access (reads).
That's why it takes more time to complete and so is the longest-running state over the lifetime of a given query.
You can also do what vs dev suggests programmatically by assigning the style with Javascript by iterating through the columns and setting the td element at a specific index to have that style.
Instead of "w"
use "a"
(append) mode with open
function:
with open("games.txt", "a") as text_file:
For those using newer versions Chart.js, you can set a label by setting the callback for tooltips.callbacks.label in options.
Example of this would be:
var chartOptions = {
tooltips: {
callbacks: {
label: function (tooltipItem, data) {
return 'label';
}
}
}
}
You can also use the following code to open new page in new tab.
<asp:Button ID="Button1" runat="server" Text="Go"
OnClientClick="window.open('yourPage.aspx');return false;"
onclick="Button3_Click" />
And just call Response.Redirect("yourPage.aspx"); behind button event.
dex2jar helps to decompile your apk but not 100%. You will have some problems with .smali files. Dex2jar cannot convert it to java. I know one application that can decompile your apk source files and no problems with .smali files. Here is a link http://www.hensence.com/en/smali2java/
There is no real difference. Out parameters are in C# to allow method return more then one value, that's all.
However There are some slight differences , but non of them are really important:
Using out parameter will enforce you to use two lines like:
int n;
GetValue(n);
while using return value will let you do it in one line:
int n = GetValue();
Another difference (correct only for value types and only if C# doesn't inline the function) is that using return value will necessarily make a copy of the value when the function return, while using OUT parameter will not necessarily do so.
array_splice($array, array_search(array_value, $array), 1);
The accepted convention of passing C-strings to functions is to use a pointer:
void function(char* name)
When the function modifies the string you should also pass in the length:
void function(char* name, size_t name_length)
Your first example:
char *functionname(char *string name[256])
passes an array of pointers to strings which is not what you need at all.
Your second example:
char functionname(char string[256])
passes an array of chars. The size of the array here doesn't matter and the parameter will decay to a pointer anyway, so this is equivalent to:
char functionname(char *string)
See also this question for more details on array arguments in C.
You need to import the module datetime
first:
>>> import datetime
After that it works:
>>> import datetime
>>> date = datetime.date.today()
>>> date
datetime.date(2013, 11, 12)
This should work:
var Timer;
$('.Scroll_Table_Div').on("scroll",function()
{
// do somethings
clearTimeout(Timer);
Timer = setTimeout(function()
{
console.log('scrolling is stop');
},50);
});
For your example, Dirk's answer is perfect. If you instead had a data frame and wanted to add that sort of sequence as a column, you could also use group
from groupdata2 (disclaimer: my package) to greedily divide the datapoints into groups.
# Attach groupdata2
library(groupdata2)
# Create a random data frame
df <- data.frame("x" = rnorm(27))
# Create groups with 5 members each (except last group)
group(df, n = 5, method = "greedy")
x .groups
<dbl> <fct>
1 0.891 1
2 -1.13 1
3 -0.500 1
4 -1.12 1
5 -0.0187 1
6 0.420 2
7 -0.449 2
8 0.365 2
9 0.526 2
10 0.466 2
# … with 17 more rows
There's a whole range of methods for creating this kind of grouping factor. E.g. by number of groups, a list of group sizes, or by having groups start when the value in some column differs from the value in the previous row (e.g. if a column is c("x","x","y","z","z")
the grouping factor would be c(1,1,2,3,3)
.
Don't know why, but only thing that worked for me was using asset_path instead of image_path, even though my images are under the assets/images/ directory:
Example:
app/assets/images/mypic.png
In Ruby:
asset_path('mypic.png')
In .scss:
url(asset-path('mypic.png'))
UPDATE:
Figured it out- turns out these asset helpers come from the sass-rails gem (which I had installed in my project).
Printing the exception's stack trace in itself doesn't constitute bad practice, but only printing the stace trace when an exception occurs is probably the issue here -- often times, just printing a stack trace is not enough.
Also, there's a tendency to suspect that proper exception handling is not being performed if all that is being performed in a catch
block is a e.printStackTrace
. Improper handling could mean at best an problem is being ignored, and at worst a program that continues executing in an undefined or unexpected state.
Example
Let's consider the following example:
try {
initializeState();
} catch (TheSkyIsFallingEndOfTheWorldException e) {
e.printStackTrace();
}
continueProcessingAssumingThatTheStateIsCorrect();
Here, we want to do some initialization processing before we continue on to some processing that requires that the initialization had taken place.
In the above code, the exception should have been caught and properly handled to prevent the program from proceeding to the continueProcessingAssumingThatTheStateIsCorrect
method which we could assume would cause problems.
In many instances, e.printStackTrace()
is an indication that some exception is being swallowed and processing is allowed to proceed as if no problem every occurred.
Why has this become a problem?
Probably one of the biggest reason that poor exception handling has become more prevalent is due to how IDEs such as Eclipse will auto-generate code that will perform a e.printStackTrace
for the exception handling:
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
(The above is an actual try-catch
auto-generated by Eclipse to handle an InterruptedException
thrown by Thread.sleep
.)
For most applications, just printing the stack trace to standard error is probably not going to be sufficient. Improper exception handling could in many instances lead to an application running in a state that is unexpected and could be leading to unexpected and undefined behavior.
Another alternative to see popular android resolutions or aspect ratios is Unity statistics:
LATEST UNITY STATISTICS (on 2019.06 return http503) web arhive
Top on 2017-01:
Display Resolutions:
Display Aspect Ratios:
version note: this is no longer value in iOS 9 & 10, as they support custom keyboard sizes.
This depends on the model and the QuickType bar:
I managed to find network.http.connect.timeout for much older versions of Mozilla:
This preference was one of several added to allow low-level tweaking of the HTTP networking code. After a portion of the same code was significantly rewritten in 2001, the preference ceased to have any effect (as noted in all.js as early as September 2001).
Currently, the timeout is determined by the system-level connection establishment timeout. Adding a way to configure this value is considered low-priority.
It would seem that network.http.connect.timeout
hasn't done anything for some time.
I also saw references to network.http.request.timeout
, so I did a Google search. The results include lots of links to people recommending that others include it in about:config
in what appears to be a mistaken belief that it actually does something, since the same search turns up this about:config entries article:
Pref removed (unused). Previously: HTTP-specific network timeout. Default value is 120.
The same page includes additional information about network.http.connect.timeout
:
Pref removed (unused). Previously: determines how long to wait for a response until registering a timeout. Default value is 30.
Disclaimer: The information on the MozillaZine Knowledge Base may be incorrect, incomplete or out-of-date.
HTML represents meaning; CSS represents appearance. How you mark up text in a document is not determined by how that text appears on screen, but simply what it means. As another example, some other HTML elements, like headings, are styled font-weight: bold
by default, but they are marked up using <h1>
–<h6>
, not <strong>
or <b>
.
In HTML5, you use <strong>
to indicate important parts of a sentence, for example:
<p><strong>Do not touch.</strong> Contains <strong>hazardous</strong> materials.
And you use <em>
to indicate linguistic stress, for example:
<p>A Gentleman: I suppose he does. But there's no point in asking.
<p>A Lady: Why not?
<p>A Gentleman: Because he doesn't row.
<p>A Lady: He doesn't <em>row</em>?
<p>A Gentleman: No. He <em>doesn't</em> row.
<p>A Lady: Ah. I see what you mean.
These elements are semantic elements that just happen to have bold and italic representations by default, but you can style them however you like. For example, in the <em>
sample above, you could represent stress emphasis in uppercase instead of italics, but the functional purpose of the <em>
element remains the same — to change the context of a sentence by emphasizing specific words or phrases over others:
em {
font-style: normal;
text-transform: uppercase;
}
Note that the original answer (below) applied to HTML standards prior to HTML5, in which <strong>
and <em>
had somewhat different meanings, <b>
and <i>
were purely presentational and had no semantic meaning whatsoever. Like <strong>
and <em>
respectively, they have similar presentational defaults but may be styled differently.
You use <strong>
and <em>
to indicate intense emphasis and normal emphasis respectively.
Or think of it this way: font-weight: bold
is closer to <b>
than <strong>
, and font-style: italic
is closer to <i>
than <em>
. These visual styles are purely visual: tools like screen readers aren't going to understand what bold and italic mean, but some screen readers are able to read <strong>
and <em>
text in a more emphasized tone.
It looks like derivedFactor
from the mosaic
package was designed for this. In this example, it would look something like:
library(mosaic)
myfile <- mutate(myfile, V5 = derivedFactor(
"1" = (V1==1 & V2!=4),
"2" = (V2==4 & V3!=1),
.method = "first",
.default = 0
))
(If you want the outcome to be numeric instead of a factor, wrap the derivedFactor
with an as.numeric
.)
Note that the .default
option combined with .method = "first"
sets the "else" condition -- this approach is described in the help file for derivedFactor
.
Add cmd.exe
as a new line below the code you want to execute:
c:\Python27\python D:\code\simple_http_server.py
cmd.exe
I hope this helps someone here: I encountered an issue where I needed to use JavaScript to manipulate some dynamically generated elements. After including the code to my external .js file which I had referenced to between the <script>
</script>
tags at the head section and it was working perfectly, nothing worked again from the script.Tried using developer tool on FF and it returned null value for the variable holding the new element. I decided to move my script tag to the bottom of the html file just before the </body>
tag and bingo every part of the script started to respond fine again.
SonarQube documentation recommends adding static
keyword to the class declaration.
That is, change public class FilePathHelper
to public static class FilePathHelper
.
Alternatively you can add a private or protected constructor.
public class FilePathHelper
{
// private or protected constructor
// because all public fields and methods are static
private FilePathHelper() {
}
}
If you've been doing performance tuning, you might have removed mod_dir. Try putting it back and that might fix your issue.
See Managing the Keyboard for a complete discussion on this topic.
IF your data won't overflow 4000 characters AND you're on SQL Server 2000 or compatibility level of 8 or SQL Server 2000:
UPDATE [CMS_DB_test].[dbo].[cms_HtmlText]
SET Content = CAST(REPLACE(CAST(Content as NVarchar(4000)),'ABC','DEF') AS NText)
WHERE Content LIKE '%ABC%'
For SQL Server 2005+:
UPDATE [CMS_DB_test].[dbo].[cms_HtmlText]
SET Content = CAST(REPLACE(CAST(Content as NVarchar(MAX)),'ABC','DEF') AS NText)
WHERE Content LIKE '%ABC%'
If you're processing a large amount of data (many megabytes) then you want to be using XmlReader
to stream parse the XML.
Anything else (XPathNavigator
, XElement
, XmlDocument
and even XmlSerializer
if you keep the full generated object graph) will result in high memory usage and also a very slow load time.
Of course, if you need all the data in memory anyway, then you may not have much choice.
Tested and working!
with https, user & password
<?php
//Data, connection, auth
$dataFromTheForm = $_POST['fieldName']; // request data from the form
$soapUrl = "https://connecting.website.com/soap.asmx?op=DoSomething"; // asmx URL of WSDL
$soapUser = "username"; // username
$soapPassword = "password"; // password
// xml post structure
$xml_post_string = '<?xml version="1.0" encoding="utf-8"?>
<soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
<soap:Body>
<GetItemPrice xmlns="http://connecting.website.com/WSDL_Service"> // xmlns value to be set to your WSDL URL
<PRICE>'.$dataFromTheForm.'</PRICE>
</GetItemPrice >
</soap:Body>
</soap:Envelope>'; // data from the form, e.g. some ID number
$headers = array(
"Content-type: text/xml;charset=\"utf-8\"",
"Accept: text/xml",
"Cache-Control: no-cache",
"Pragma: no-cache",
"SOAPAction: http://connecting.website.com/WSDL_Service/GetPrice",
"Content-length: ".strlen($xml_post_string),
); //SOAPAction: your op URL
$url = $soapUrl;
// PHP cURL for https connection with auth
$ch = curl_init();
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 1);
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_USERPWD, $soapUser.":".$soapPassword); // username and password - declared at the top of the doc
curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_ANY);
curl_setopt($ch, CURLOPT_TIMEOUT, 10);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $xml_post_string); // the SOAP request
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
// converting
$response = curl_exec($ch);
curl_close($ch);
// converting
$response1 = str_replace("<soap:Body>","",$response);
$response2 = str_replace("</soap:Body>","",$response1);
// convertingc to XML
$parser = simplexml_load_string($response2);
// user $parser to get your data out of XML response and to display it.
?>
IF you are using Vector3 this is what i did
1- I create a class Name it Player
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
[Serializable]
public class Player
{
public Vector3[] Position;
}
2- then i call it like this
if ( _ispressed == true)
{
Player playerInstance = new Player();
playerInstance.Position = newPos;
string jsonData = JsonUtility.ToJson(playerInstance);
reference.Child("Position" + Random.Range(0, 1000000)).SetRawJsonValueAsync(jsonData);
Debug.Log(jsonData);
_ispressed = false;
}
3- and this is the result
"Position":[ {"x":-2.8567452430725099,"y":-2.4323320388793947,"z":0.0}]}
var result;_x000D_
result = "1,2,3".split(","); _x000D_
console.log(result);
_x000D_
More info on W3Schools describing the String Split function.
There's nothing wrong with your code, the following works fine for me when I have the file.txt in the user.dir directory.
import java.io.File;
import java.util.Scanner;
public class testme {
public static void main(String[] args) {
System.out.println(System.getProperty("user.dir"));
File file = new File("file.txt");
try {
Scanner scanner = new Scanner(file);
} catch (Exception e) {
System.out.println(e);
}
}
}
Don't trust Eclipse with where it says the file is. Go out to the actual filesystem with Windows Explorer or equivalent and check.
Based on your edit, I think we need to see your import statements as well.
You need to ensure that any code that modifies the HTTP headers is executed before the headers are sent. This includes statements like session_start()
. The headers will be sent automatically when any HTML is output.
Your problem here is that you're sending the HTML ouput at the top of your page before you've executed any PHP at all.
Move the session_start()
to the top of your document :
<?php session_start(); ?> <html> <head> <title>PHP SDK</title> </head> <body> <?php require_once 'src/facebook.php'; // more PHP code here.
Here is the direct solution:
// POST api/<controller>
[HttpPost, Route("postproducts/{product1}/{product2}")]
public void PostProducts([FromUri]Product product, Product product2)
{
Product productOne = product;
Product productTwo = product2;
}
$scope.url = 'http://localhost:53263/api/Products/' +
$scope.product + '/' + $scope.product2
$http.post($scope.url)
.success(function(response) {
alert("success")
})
.error(function() { alert("fail") });
};
If you are sane you do this:
var $scope.products.product1 = product1;
var $scope.products.product2 = product2;
And then send products in the body (like a balla).
This is how I got sort to work in mongoose 2.3.0 :)
// Find First 10 News Items
News.find({
deal_id:deal._id // Search Filters
},
['type','date_added'], // Columns to Return
{
skip:0, // Starting Row
limit:10, // Ending Row
sort:{
date_added: -1 //Sort by Date Added DESC
}
},
function(err,allNews){
socket.emit('news-load', allNews); // Do something with the array of 10 objects
})
You can alternatively use NamedParameterJdbcTemplate
(naming can be useful when you have many parameters)
Map<String, Object> params = new HashMap<>();
params.put("var1",value1);
params.put("var2",value2);
namedJdbcTemplate.update(
"INSERT INTO schema.tableName (column1, column2) VALUES (:var1, :var2)",
params
);
It is enough to use in your xml file.
android:singleLine="false".
Hope it will work.
All the best!
Just use standard CSS variables:
Your global css (eg: styles.css)
body {
--my-var: #000
}
In your component's css or whatever it is:
span {
color: var(--my-var)
}
Then you can change the value of the variable directly with TS/JS by setting inline style to html element:
document.querySelector("body").style.cssText = "--my-var: #000";
Otherwise you can use jQuery for it:
$("body").css("--my-var", "#fff");
Try the Currency Format Specifier ("C"). It automatically takes the current UI culture into account and displays currency values accordingly.
You can use it with either String.Format
or the overloaded ToString
method for a numeric type.
For example:
double value = 12345.6789;
Console.WriteLine(value.ToString("C", CultureInfo.CurrentCulture));
Console.WriteLine(value.ToString("C3", CultureInfo.CurrentCulture));
Console.WriteLine(value.ToString("C3", CultureInfo.CreateSpecificCulture("da-DK")));
// The example displays the following output on a system whose
// current culture is English (United States):
// $12,345.68
// $12,345.679
// kr 12.345,679
break
will exit the loop, while continue
will start the next cycle of the loop immediately.
There is no direct string compare function in SQL Server
CASE
WHEN str1 = str2 THEN 0
WHEN str1 < str2 THEN -1
WHEN str1 > str2 THEN 1
ELSE NULL --one of the strings is NULL so won't compare (added on edit)
END
Notes
There is a bunch on here:
http://www.webservicex.net/WS/wscatlist.aspx
Just google for "Free WebService" or "Open WebService" and you'll find tons of open SOAP endpoints.
Remember, you can get a WSDL from any ASMX endpoint by adding ?WSDL to the url.
declare your date column as NOT NULL, but without a default. Then add this trigger:
USE `ddb`;
DELIMITER $$
CREATE TRIGGER `default_date` BEFORE INSERT ON `dtable` FOR EACH ROW
if ( isnull(new.query_date) ) then
set new.query_date=curdate();
end if;
$$
delimiter ;
Problem with data-dismiss="modal"
is it will shift your content to left
I am sharing what worked for me, problem statment was opening pop1
from pop2
JS CODE
var showPopup2 = false;
$('#popup1').on('hidden.bs.modal', function () {
if (showPopup2) {
$('#popup2').modal('show');
showPopup2 = false;
}
});
$("#popup2").click(function() {
$('#popup1').modal('hide');
showPopup2 = true;
});
Cookies are used to identify sessions. Visit any site that is using cookies and pull up either Chrome inspect element and then network or FireBug if using Firefox.
You can see that there is a header sent to a server and also received called Cookie. Usually it contains some personal information (like an ID) that can be used on the server to identify a session. These cookies stay on your computer and your browser takes care of sending them to only the domains that are identified with it.
If there were no cookies then you would be sending a unique ID on every request via GET or POST. Cookies are like static id's that stay on your computer for some time.
A session is a group of information on the server that is associated with the cookie information. If you're using PHP you can check the session.save_path location and actually "see sessions". They are either files on the server filesystem or backed in a database.
In my case I changed the datetime field in the SQL database to not allow null. SqlDataReader then allowed me to cast the value directly to a DateTime.
This is what you need : ternary operator, please take a look at this
http://msdn.microsoft.com/en-us/library/ty67wk28%28v=vs.80%29.aspx
I'm not really familiar with all those parameters of the Find
method; but upon shortening it, the following is working for me:
With WB.Sheets("ECM Overview")
Set FindRow = .Range("A:A").Find(What:="ProjTemp", LookIn:=xlValues)
End With
And if you solely need the row number, you can use this after:
Dim FindRowNumber As Long
.....
FindRowNumber = FindRow.Row
self.tableView.tableHeaderView = segmentedControl;
If you want it to obey your width and height properly though enclose your segmentedControl in a UIView first as the tableView likes to mangle your view a bit to fit the width.
I just spent the better part of an afternoon on this
There are two common ways of writing to a file, the first being a direct file access "write" statement. This adds the quotes.
The second is the "ActiveWorkbook.SaveAs" or "ActiveWorksheet.SaveAs" which both have the really bad side effect of changing the filename of the active workbook.
The solution here is a hybrid of a few solutions I found online. It basically does this: 1) Copy selected cells to a new worksheet 2) Iterate through each cell one at a time and "print" it to the open file 3) Delete the temporary worksheet.
The function works on the selected cells and takes in a string for a filename or prompts for a filename.
Function SaveFile(myFolder As String) As String
tempSheetName = "fileWrite_temp"
SaveFile = "False"
Dim FilePath As String
Dim CellData As String
Dim LastCol As Long
Dim LastRow As Long
Set myRange = Selection
'myRange.Select
Selection.Copy
'Ask user for folder to save text file to.
If myFolder = "prompt" Then
myFolder = Application.GetSaveAsFilename(fileFilter:="XML Files (*.xml), *.xml, All Files (*), *")
End If
If myFolder = "False" Then
End
End If
Open myFolder For Output As #2
'This temporarily adds a sheet named "Test."
Sheets.Add.Name = tempSheetName
Sheets(tempSheetName).Select
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
:=False, Transpose:=False
LastCol = ActiveSheet.UsedRange.SpecialCells(xlCellTypeLastCell).Column
LastRow = ActiveSheet.UsedRange.SpecialCells(xlCellTypeLastCell).Row
For i = 1 To LastRow
For j = 1 To LastCol
CellData = CellData + Trim(ActiveCell(i, j).Value) + " "
Next j
Print #2, CellData; " "
CellData = ""
Next i
Close #2
'Remove temporary sheet.
Application.ScreenUpdating = False
Application.DisplayAlerts = False
ActiveWindow.SelectedSheets.Delete
Application.DisplayAlerts = True
Application.ScreenUpdating = True
'Indicate save action.
MsgBox "Text File Saved to: " & vbNewLine & myFolder
SaveFile = myFolder
End Function
In the constructor. The constructor's purpose is to initialized it's data members.
Does the code work when not running the Maven-build jar, for example when running from your IDE? If so, make sure the file is actually included in the jar. The resources folder should be included in the pom file, in <build><resources>
.
I had this problem on a development machine. The dev
branch was pushing fine but the
the master
branch gave me (while git push
ing when being on the dev
branch):
! [rejected] master -> master (non-fast-forward)
So I tried:
git checkout master
git pull
Which gave me:
You asked me to pull without telling me which branch you
want to merge with, and 'branch.master.merge' in
your configuration file does not tell me, either.
I found out the master branch was missing from .git/config
and added:
[branch "master"]
remote = origin
merge = refs/heads/master
Afterwards git push
also worked fine on the dev
branch.
Add-Content is default ASCII and add new line however Add-Content brings locked files issues too.
What I did in the end is make a batch file to extract the CLASSPATH from the ant file, then run java directly using this:
In my build.xml:
<target name="printclasspath">
<pathconvert property="classpathProp" refid="project.class.path"/>
<echo>${classpathProp}</echo>
</target>
In another script called 'run.sh':
export CLASSPATH=$(ant -q printclasspath | grep echo | cut -d \ -f 7):build
java "$@"
It's no longer cross-platform, but at least it's relatively easy to use, and one could provide a .bat file that does the same as the run.sh. It's a very short batch script. It's not like migrating the entire build to platform-specific batch files.
I think it's a shame there's not some option in ant whereby you could do something like:
ant -- arg1 arg2 arg3
mpirun uses this type of syntax; ssh also can use this syntax I think.
Considering the previous answers, it is necessary to be careful with globalized characters.
Suppose the name of the file is: "Esdrújula prenda ñame - güena.jpg"
Raw result to download: "Esdrújula prenda ñame - güena.jpg" [Ugly]
HtmlEncode result to download: "Esdr&_250;jula prenda &_241;ame - g&_252;ena.jpg" [Ugly]
UrlEncode result to download: "Esdrújula+prenda+ñame+-+güena.jpg" [OK]
Then, you need almost always to use the UrlEncode over the file name. Moreover, if you set the content-disposition header as direct string, then you need to ensure surround with quotes to avoid browser compatibility issues.
Response.AddHeader("Content-Disposition", $"attachment; filename=\"{HttpUtility.UrlEncode(YourFilename)}\"");
or with class aid:
var cd = new ContentDisposition("attachment") { FileName = HttpUtility.UrlEncode(resultFileName) };
Response.AddHeader("Content-Disposition", cd.ToString());
The System.Net.Mime.ContentDisposition class takes care of quotes.
The reason for "permission denied" is because your Android machine has not been correctly rooted. Did you see $
after you started adb shell
? If you correctly rooted your machine, you would have seen #
instead.
If you see the $
, try entering Super User mode by typing su
. If Root is enabled, you will see the #
- without asking for password.
Use the verbatim keystroke, ^V
(CTRL+V
, C-v
, whatever).
When you type ^V
into the terminal (or in most Unix editors), the following character is taken verbatim. You can use this to type a literal tab character inside a string you are echoing.
Something like the following works:
echo "^V<tab>" # CTRL+V, TAB
Bash docs (q.v., "quoted-insert")
quoted-insert (C-q, C-v) Add the next character that you type to the line verbatim. This is how to insert key sequences like C-q, for example.
side note: according to this, ALT+TAB
should do the same thing, but we've all bound that sequence to window switching so we can't use it
tab-insert (M-TAB) Insert a tab character.
--
Note: you can use this strategy with all sorts of unusual characters. Like a carriage return:
echo "^V^M" # CTRL+V, CTRL+M
This is because carriage return is ASCII 13, and M is the 13th letter of the alphabet, so when you type ^M
, you get the 13th ASCII character. You can see it in action using ls^M
, at an empty prompt, which will insert a carriage return, causing the prompt to act just like you hit return. When these characters are normally interpreted, verbatim gets you get the literal character.
Changing the distribution of any function to another involves using the inverse of the function you want.
In other words, if you aim for a specific probability function p(x) you get the distribution by integrating over it -> d(x) = integral(p(x)) and use its inverse: Inv(d(x)). Now use the random probability function (which have uniform distribution) and cast the result value through the function Inv(d(x)). You should get random values cast with distribution according to the function you chose.
This is the generic math approach - by using it you can now choose any probability or distribution function you have as long as it have inverse or good inverse approximation.
Hope this helped and thanks for the small remark about using the distribution and not the probability itself.
I think it's worth mentioning how the Underscore's _.each() works internally. The _.each(list, iteratee) checks if the passed list is an array object, or an object.
In the case that the list is an array, iteratee arguments will be a list element and index as in the following example:
var a = ['I', 'like', 'pancakes', 'a', 'lot', '.'];
_.each( a, function(v, k) { console.log( k + " " + v); });
0 I
1 like
2 pancakes
3 a
4 lot
5 .
On the other hand, if the list argument is an object the iteratee will take a list element and a key:
var o = {name: 'mike', lastname: 'doe', age: 21};
_.each( o, function(v, k) { console.log( k + " " + v); });
name mike
lastname doe
age 21
For reference this is the _.each() code from Underscore.js 1.8.3
_.each = _.forEach = function(obj, iteratee, context) {
iteratee = optimizeCb(iteratee, context);
var i, length;
if (isArrayLike(obj)) {
for (i = 0, length = obj.length; i < length; i++) {
iteratee(obj[i], i, obj);
}
} else {
var keys = _.keys(obj);
for (i = 0, length = keys.length; i < length; i++) {
iteratee(obj[keys[i]], keys[i], obj);
}
}
return obj;
};
Let me give you another tutorial written by me. It answers your question, but also makes an explanation why we are doing some of the things. I also tried to make it concise.
So you have a list_of_documents
which is just an array of strings and another document
which is just a string. You need to find such document from the list_of_documents
that is the most similar to document
.
Let's combine them together: documents = list_of_documents + [document]
Let's start with dependencies. It will become clear why we use each of them.
from nltk.corpus import stopwords
import string
from nltk.tokenize import wordpunct_tokenize as tokenize
from nltk.stem.porter import PorterStemmer
from sklearn.feature_extraction.text import TfidfVectorizer
from scipy.spatial.distance import cosine
One of the approaches that can be uses is a bag-of-words approach, where we treat each word in the document independent of others and just throw all of them together in the big bag. From one point of view, it looses a lot of information (like how the words are connected), but from another point of view it makes the model simple.
In English and in any other human language there are a lot of "useless" words like 'a', 'the', 'in' which are so common that they do not possess a lot of meaning. They are called stop words and it is a good idea to remove them. Another thing that one can notice is that words like 'analyze', 'analyzer', 'analysis' are really similar. They have a common root and all can be converted to just one word. This process is called stemming and there exist different stemmers which differ in speed, aggressiveness and so on. So we transform each of the documents to list of stems of words without stop words. Also we discard all the punctuation.
porter = PorterStemmer()
stop_words = set(stopwords.words('english'))
modified_arr = [[porter.stem(i.lower()) for i in tokenize(d.translate(None, string.punctuation)) if i.lower() not in stop_words] for d in documents]
So how will this bag of words help us? Imagine we have 3 bags: [a, b, c]
, [a, c, a]
and [b, c, d]
. We can convert them to vectors in the basis [a, b, c, d]
. So we end up with vectors: [1, 1, 1, 0]
, [2, 0, 1, 0]
and [0, 1, 1, 1]
. The similar thing is with our documents (only the vectors will be way to longer). Now we see that we removed a lot of words and stemmed other also to decrease the dimensions of the vectors. Here there is just interesting observation. Longer documents will have way more positive elements than shorter, that's why it is nice to normalize the vector. This is called term frequency TF, people also used additional information about how often the word is used in other documents - inverse document frequency IDF. Together we have a metric TF-IDF which have a couple of flavors. This can be achieved with one line in sklearn :-)
modified_doc = [' '.join(i) for i in modified_arr] # this is only to convert our list of lists to list of strings that vectorizer uses.
tf_idf = TfidfVectorizer().fit_transform(modified_doc)
Actually vectorizer allows to do a lot of things like removing stop words and lowercasing. I have done them in a separate step only because sklearn does not have non-english stopwords, but nltk has.
So we have all the vectors calculated. The last step is to find which one is the most similar to the last one. There are various ways to achieve that, one of them is Euclidean distance which is not so great for the reason discussed here. Another approach is cosine similarity. We iterate all the documents and calculating cosine similarity between the document and the last one:
l = len(documents) - 1
for i in xrange(l):
minimum = (1, None)
minimum = min((cosine(tf_idf[i].todense(), tf_idf[l + 1].todense()), i), minimum)
print minimum
Now minimum will have information about the best document and its score.
If you happen to have IPython
in your packages (you should), it has (up to now, anyway) a very nice formatter for durations (in float seconds). That is used in various places, for example by the %%time
cell magic. I like the format it produces for short durations:
>>> from IPython.core.magics.execution import _format_time
>>>
>>> for v in range(-9, 10, 2):
... dt = 1.25 * 10**v
... print(_format_time(dt))
1.25 ns
125 ns
12.5 µs
1.25 ms
125 ms
12.5 s
20min 50s
1d 10h 43min 20s
144d 16h 13min 20s
14467d 14h 13min 20s
Code To insert Data in Access Db using c#
Code:-
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace access_db_csharp
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
public SqlConnection con = new SqlConnection(@"Place Your connection string");
private void Savebutton_Click(object sender, EventArgs e)
{
SqlCommand cmd = new SqlCommand("insert into Data (Name,PhoneNo,Address) values(@parameter1,@parameter2,@parameter3)",con);
cmd.Parameters.AddWithValue("@parameter1", (textBox1.Text));
cmd.Parameters.AddWithValue("@parameter2", textBox2.Text);
cmd.Parameters.AddWithValue("@parameter3", (textBox4.Text));
cmd.ExecuteNonQuery();
}
private void Form1_Load(object sender, EventArgs e)
{
con.ConnectionString = connectionstring;
con.Open();
}
}
}
The equals() method on your List implementation should do elementwise comparison, so
assertEquals(argumentComponents, returnedComponents);
is a lot easier.
for(int i = 0; i < n; i++) {
existing_string += 'c';
}
but you should use StringBuilder instead, and save memory
int n = 3;
String existing_string = "string";
StringBuilder builder = new StringBuilder(existing_string);
for (int i = 0; i < n; i++) {
builder.append(" append ");
}
System.out.println(builder.toString());
If you have the latest browsers window.orientation
might not work. In that case use following code for getting angle -
var orientation = window.screen.orientation.angle;
This is still an experimental technology, you can check the browser compatibility here
Open your Java source code document and navigate to the JTable object you have created inside of your Swing class.
Create a new TableModel object that holds a DatePickerTable. You must create the DatePickerTable with a range of date values in MMDDYYYY format. The first value is the begin date and the last is the end date. In code, this looks like:
TableModel datePicker = new DatePickerTable("01011999","12302000");
Set the display interval in the datePicker object. By default each day is displayed, but you may set a regular interval. To set a 15-day interval between date options, use this code:
datePicker.interval = 15;
Attach your table model into your JTable:
JTable newtable = new JTable (datePicker);
Your Java application now has a drop-down date selection dialog.
Function overloading is the ability of a programming language to create multiple functions of the same name with different implementations. when an overloaded function is called it will run function a specific implementation of that function appropriate to the context of the call. This context is usually the amount of arguments is receives, and it allows one function call to behave differently depending on context.
Javascript doesn't have built-in function overloading. However, this behaviour can be emulated in many ways. Here is a convenient simple one:
function sayHi(a, b) {_x000D_
console.log('hi there ' + a);_x000D_
if (b) { console.log('and ' + b) } // if the parameter is present, execute the block_x000D_
}_x000D_
_x000D_
sayHi('Frank', 'Willem');
_x000D_
In scenarios where you don't know how many arguments you will be getting you can use the rest operator which is three dots ...
. It will convert the remainder of the arguments into an array. Beware of browser compatibilty though. Here is an example:
function foo (a, ...b) {_x000D_
console.log(b);_x000D_
}_x000D_
_x000D_
foo(1,2,3,4);_x000D_
foo(1,2);
_x000D_
/*first of all, and this might be the problem amongst junior devs out there, like myself: make sure to use "lambda" >>>> "`" and not "'" in your fetch method! */
``` const response = await fetch(https://api....
);
/plus, the following article is highly recommended: https://developer.edamam.com/api/faq/
First Create folder same as path which you Specified. after then create File
File dir = new File("C:\\USER\\Semple_file\\");
File file = new File("C:\\USER\\Semple_file\\abc.txt");
if(!file.exists())
{
dir.mkdir();
file.createNewFile();
System.out.println("File,Folder Created.);
}
The __import__
function can be a bit hard to understand.
If you change
i = __import__('matplotlib.text')
to
i = __import__('matplotlib.text', fromlist=[''])
then i
will refer to matplotlib.text
.
In Python 2.7 and Python 3.1 or later, you can use importlib
:
import importlib
i = importlib.import_module("matplotlib.text")
Some notes
If you're trying to import something from a sub-folder e.g. ./feature/email.py
, the code will look like importlib.import_module("feature.email")
You can't import anything if there is no __init__.py
in the folder with file you are trying to import
Have a look at my related answer at
Designing a Test class for a custom Barrier
It's biased towards Java but has a reasonable summary of the options.
In summary though (IMO) its not the use of some fancy framework that will ensure correctness but how you go about designing you multithreaded code. Splitting the concerns (concurrency and functionality) goes a huge way towards raising confidence. Growing Object Orientated Software Guided By Tests explains some options better than I can.
Static analysis and formal methods (see, Concurrency: State Models and Java Programs) is an option but I've found them to be of limited use in commercial development.
Don't forget that any load/soak style tests are rarely guaranteed to highlight problems.
Good luck!
Currency pipe uses the number
one internally for number formatting. So you can use it like this:
{{ number | number : '1.2-2'}}
You don't need the jsp:useBean
to set the model if you already have a controller which prepared the model.
Just access it plain by EL:
<p>${Questions.questionPaperID}</p>
<p>${Questions.question}</p>
or by JSTL <c:out>
tag if you'd like to HTML-escape the values or when you're still working on legacy Servlet 2.3 containers or older when EL wasn't supported in template text yet:
<p><c:out value="${Questions.questionPaperID}" /></p>
<p><c:out value="${Questions.question}" /></p>
Unrelated to the problem, the normal practice is by the way to start attribute name with a lowercase, like you do with normal variable names.
session.setAttribute("questions", questions);
and alter EL accordingly to use ${questions}
.
Also note that you don't have any JSTL tag in your code. It's all plain JSP.
You want the path.join() function from os.path.
>>> from os import path
>>> path.join('foo', 'bar')
'foo/bar'
This builds your path with os.sep (instead of the less portable '/'
) and does it more efficiently (in general) than using +
.
However, this won't actually create the path. For that, you have to do something like what you do in your question. You could write something like:
start_path = '/my/root/directory'
final_path = os.join(start_path, *list_of_vars)
if not os.path.isdir(final_path):
os.makedirs (final_path)
Also worth mentioning -- if you were forced to use an older Java version prior to 1.5, and you are trying to use Collections, you won't be able to parameterize the collection with a type such as Double
.
You'll have to manually "box" to the class Double
when adding new items, and "unbox" to the primitive double
by parsing and casting, doing something like this:
LinkedList lameOldList = new LinkedList();
lameOldList.add( new Double(1.2) );
lameOldList.add( new Double(3.4) );
lameOldList.add( new Double(5.6) );
double total = 0.0;
for (int i = 0, len = lameOldList.size(); i < len; i++) {
total += Double.valueOf( (Double)lameOldList.get(i) );
}
The old-school list will contain only type Object
and so has to be cast to Double
.
Also, you won't be able to iterate through the list with an enhanced-for-loop in early Java versions -- only with a for-loop.
If you'd like the download to be offered as a download that can be opened directly in Excel, this may work for you: (copied from an old unreleased project of mine)
These functions setup the headers:
function setExcelContentType() {
if(headers_sent())
return false;
header('Content-type: application/vnd.ms-excel');
return true;
}
function setDownloadAsHeader($filename) {
if(headers_sent())
return false;
header('Content-disposition: attachment; filename=' . $filename);
return true;
}
This one sends a CSV to a stream using a mysql result
function csvFromResult($stream, $result, $showColumnHeaders = true) {
if($showColumnHeaders) {
$columnHeaders = array();
$nfields = mysql_num_fields($result);
for($i = 0; $i < $nfields; $i++) {
$field = mysql_fetch_field($result, $i);
$columnHeaders[] = $field->name;
}
fputcsv($stream, $columnHeaders);
}
$nrows = 0;
while($row = mysql_fetch_row($result)) {
fputcsv($stream, $row);
$nrows++;
}
return $nrows;
}
This one uses the above function to write a CSV to a file, given by $filename
function csvFileFromResult($filename, $result, $showColumnHeaders = true) {
$fp = fopen($filename, 'w');
$rc = csvFromResult($fp, $result, $showColumnHeaders);
fclose($fp);
return $rc;
}
And this is where the magic happens ;)
function csvToExcelDownloadFromResult($result, $showColumnHeaders = true, $asFilename = 'data.csv') {
setExcelContentType();
setDownloadAsHeader($asFilename);
return csvFileFromResult('php://output', $result, $showColumnHeaders);
}
For example:
$result = mysql_query("SELECT foo, bar, shazbot FROM baz WHERE boo = 'foo'");
csvToExcelDownloadFromResult($result);
Here is my example:
<div class="form-group">
<label for="contactMethod">Contact method</label>
<select
name="contactMethod"
id="contactMethod"
class="form-control"
[(ngModel)]="contact.contactMethod">
<option *ngFor="let method of contactMethods" [value]="method.id">{{ method.label }}</option>
</select>
</div>
And in component you must get values from select:
contactMethods = [
{ id: 1, label: "Email" },
{ id: 2, label: "Phone" }
]
So, if you want select to have a default value selected (and proabbly you want that):
contact = {
firstName: "CFR",
comment: "No comment",
subscribe: true,
contactMethod: 2 // this id you'll send and get from backend
}
You can execute raw sql in EF Core - Add this class to your project. This will allow you to execute raw SQL and get the raw results without having to define a POCO and a DBSet. See https://github.com/aspnet/EntityFramework/issues/1862#issuecomment-220787464 for original example.
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Internal;
using Microsoft.EntityFrameworkCore.Storage;
using System.Threading;
using System.Threading.Tasks;
namespace Microsoft.EntityFrameworkCore
{
public static class RDFacadeExtensions
{
public static RelationalDataReader ExecuteSqlQuery(this DatabaseFacade databaseFacade, string sql, params object[] parameters)
{
var concurrencyDetector = databaseFacade.GetService<IConcurrencyDetector>();
using (concurrencyDetector.EnterCriticalSection())
{
var rawSqlCommand = databaseFacade
.GetService<IRawSqlCommandBuilder>()
.Build(sql, parameters);
return rawSqlCommand
.RelationalCommand
.ExecuteReader(
databaseFacade.GetService<IRelationalConnection>(),
parameterValues: rawSqlCommand.ParameterValues);
}
}
public static async Task<RelationalDataReader> ExecuteSqlQueryAsync(this DatabaseFacade databaseFacade,
string sql,
CancellationToken cancellationToken = default(CancellationToken),
params object[] parameters)
{
var concurrencyDetector = databaseFacade.GetService<IConcurrencyDetector>();
using (concurrencyDetector.EnterCriticalSection())
{
var rawSqlCommand = databaseFacade
.GetService<IRawSqlCommandBuilder>()
.Build(sql, parameters);
return await rawSqlCommand
.RelationalCommand
.ExecuteReaderAsync(
databaseFacade.GetService<IRelationalConnection>(),
parameterValues: rawSqlCommand.ParameterValues,
cancellationToken: cancellationToken);
}
}
}
}
Here's an example of how to use it:
// Execute a query.
using(var dr = await db.Database.ExecuteSqlQueryAsync("SELECT ID, Credits, LoginDate FROM SamplePlayer WHERE " +
"Name IN ('Electro', 'Nitro')"))
{
// Output rows.
var reader = dr.DbDataReader;
while (reader.Read())
{
Console.Write("{0}\t{1}\t{2} \n", reader[0], reader[1], reader[2]);
}
}
I tried below code its worked for fine
var modWidth = 250;
var modHeight = 150;
example below :-
$( "#ContainerId .sDashboard li" ).width( modWidth ).height(modHeight);
Use an object - with an integer as the key - rather than an array.
If
width = img.width;
height = img.height;
var ctx = canvas.getContext('2d');
Then you can use these transformations to turn the image to orientation 1
From orientation:
ctx.transform(1, 0, 0, 1, 0, 0);
ctx.transform(-1, 0, 0, 1, width, 0);
ctx.transform(-1, 0, 0, -1, width, height);
ctx.transform(1, 0, 0, -1, 0, height);
ctx.transform(0, 1, 1, 0, 0, 0);
ctx.transform(0, 1, -1, 0, height, 0);
ctx.transform(0, -1, -1, 0, height, width);
ctx.transform(0, -1, 1, 0, 0, width);
Before drawing the image on ctx
There's an Abstract Class Dictionary
http://docs.oracle.com/javase/6/docs/api/java/util/Dictionary.html
However this requires implementation.
Java gives us a nice implementation called a Hashtable
http://docs.oracle.com/javase/6/docs/api/java/util/Hashtable.html
public bool roomSelected()
{
int a = 0;
foreach (RadioButton rb in GroupBox1.Controls)
{
if (rb.Checked == true)
{
a = 1;
}
}
if (a == 1)
{
return true;
}
else
{
return false;
}
}
this how I solved my problem
Derp! I signed into the account and there was a "Suspicious login attempt" warning message at the top of the page. After clicking the warning and authorizing the access, everything works.
Just need to add version of which you want
upgrade or downgrade
npm install -g npm@version
Example if you want to downgrade from npm 5.6.0 to 4.6.1 then,
npm install -g [email protected]
It is tested on linux
For regular remote notifications, the maximum size is 4KB (4096 bytes) https://developer.apple.com/library/content/documentation/NetworkingInternet/Conceptual/RemoteNotificationsPG/CreatingtheNotificationPayload.html
###iOS the size limit is 256 bytes, but since the introduction of iOS 8 has changed to 2kb!
https://forums.aws.amazon.com/ann.jspa?annID=2626
With iOS 8, Apple introduced new features that enable some rich new use cases for mobile push notifications — interactive push notifications, third party widgets, and larger (2 KB) payloads. Today, we are pleased to announce support for the new mobile push capabilities announced with iOS 8. We are publishing a new iOS 8 Sample App that demonstrates how these new features can be implemented with SNS, and have also implemented support for larger 2KB payloads.
With having the freedom of using all possible ls options:
find -type f | xargs ls -1
As ping
works, but telnet
to port 80
does not, the HTTP port 80
is closed on your machine. I assume that your browser's HTTP connection goes through a proxy (as browsing works, how else would you read stackoverflow?).
You need to add some code to your python program, that handles the proxy, like described here:
There is also this way of specifying the viewmodel:
using Wpf = System.Windows;
public partial class App : Wpf.Application //your skeleton app already has this.
{
protected override void OnStartup( Wpf.StartupEventArgs e ) //you need to add this.
{
base.OnStartup( e );
MainWindow = new MainView();
MainWindow.DataContext = new MainViewModel( e.Args );
MainWindow.Show();
}
}
<Rant>
All of the solutions previously proposed require that MainViewModel
must have a parameterless constructor.
Microsoft is under the impression that systems can be built using parameterless constructors. If you are also under that impression, go ahead and use some of the other solutions.
For those that know that constructors must have parameters, and therefore the instantiation of objects cannot be left in the hands of magic frameworks, the proper way of specifying the viewmodel is the one I showed above.
</Rant>
Let me quote this:
Hibernate created a new language named Hibernate Query Language (HQL), the syntax is quite similar to database SQL language. The main difference between is HQL uses class name instead of table name, and property names instead of column name.
As far as I can see you are using the table name.
So it should be like this:
Query query = session.createQuery("from Employee");
The jsonify()
function in flask returns a flask.Response()
object that already has the appropriate content-type header 'application/json' for use with json responses. Whereas, the json.dumps()
method will just return an encoded string, which would require manually adding the MIME type header.
See more about the jsonify()
function here for full reference.
Edit:
Also, I've noticed that jsonify()
handles kwargs or dictionaries, while json.dumps()
additionally supports lists and others.
Give your radiobutton a custom style:
<style name="MyRadioButtonStyle" parent="@android:style/Widget.CompoundButton.RadioButton">
<item name="android:button">@drawable/custom_btn_radio</item>
</style>
custom_btn_radio.xml
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_checked="true" android:state_window_focused="false"
android:drawable="@drawable/btn_radio_on" />
<item android:state_checked="false" android:state_window_focused="false"
android:drawable="@drawable/btn_radio_off" />
<item android:state_checked="true" android:state_pressed="true"
android:drawable="@drawable/btn_radio_on_pressed" />
<item android:state_checked="false" android:state_pressed="true"
android:drawable="@drawable/btn_radio_off_pressed" />
<item android:state_checked="true" android:state_focused="true"
android:drawable="@drawable/btn_radio_on_selected" />
<item android:state_checked="false" android:state_focused="true"
android:drawable="@drawable/btn_radio_off_selected" />
<item android:state_checked="false" android:drawable="@drawable/btn_radio_off" />
<item android:state_checked="true" android:drawable="@drawable/btn_radio_on" />
</selector>
Replace the drawables with your own.
The <button>
element, when placed in a form, will submit the form automatically unless otherwise specified. You can use the following 2 strategies:
<button type="button">
to override default submission behaviorevent.preventDefault()
in the onSubmit event to prevent form submissionInsert extra type
attribute to your button markup:
<button id="button" type="button" value="send" class="btn btn-primary">Submit</button>
Prevent default form submission when button is clicked. Note that this is not the ideal solution because you should be in fact listening to the submit event, not the button click event:
$(document).ready(function () {
// Listen to click event on the submit button
$('#button').click(function (e) {
e.preventDefault();
var name = $("#name").val();
var email = $("#email").val();
$.post("process.php", {
name: name,
email: email
}).complete(function() {
console.log("Success");
});
});
});
In this improvement, we listen to the submit event emitted from the <form>
element:
$(document).ready(function () {
// Listen to submit event on the <form> itself!
$('#main').submit(function (e) {
e.preventDefault();
var name = $("#name").val();
var email = $("#email").val();
$.post("process.php", {
name: name,
email: email
}).complete(function() {
console.log("Success");
});
});
});
.serialize()
to serialize your form, but remember to add name
attributes to your input:The name
attribute is required for .serialize()
to work, as per jQuery's documentation:
For a form element's value to be included in the serialized string, the element must have a name attribute.
<input type="text" id="name" name="name" class="form-control mb-2 mr-sm-2 mb-sm-0" id="inlineFormInput" placeholder="Jane Doe">
<input type="text" id="email" name="email" class="form-control" id="inlineFormInputGroup" placeholder="[email protected]">
And then in your JS:
$(document).ready(function () {
// Listen to submit event on the <form> itself!
$('#main').submit(function (e) {
// Prevent form submission which refreshes page
e.preventDefault();
// Serialize data
var formData = $(this).serialize();
// Make AJAX request
$.post("process.php", formData).complete(function() {
console.log("Success");
});
});
});
That's probably as fast as you can do it in pure python for reasonably large inputs:
def choose(n, k):
if k == n: return 1
if k > n: return 0
d, q = max(k, n-k), min(k, n-k)
num = 1
for n in xrange(d+1, n+1): num *= n
denom = 1
for d in xrange(1, q+1): denom *= d
return num / denom
If you have access to the Java 8 Comparable API, Comparable.comparingToInt()
may be of use. (See Java 8 Comparable Documentation).
For example, a Comparator<Dog>
to sort Dog
instances descending by age could be created with the following:
Comparable.comparingToInt(Dog::getDogAge).reversed();
The function take a lambda mapping T
to Integer
, and creates an ascending comparator. The chained function .reversed()
turns the ascending comparator into a descending comparator.
Note: while this may not be useful for most versions of Android out there, I came across this question while searching for similar information for a non-Android Java application. I thought it might be useful to others in the same spot to see what I ended up settling on.
You might no need to having export, just add this line in catalina.sh :
CATALINA_OPTS="-Xms512M -Xmx1024M"
Funny, I was doing precisely this yesterday. You just need this in your css file
.ablock table td {
padding:5px;
}
then wrap the table in a suitable div
<div class="ablock ">
<table>
<tr>
<td>
Getters and Setters in C# are something that simplifies the code.
private string name = "spots";
public string Name
{
get { return name; }
set { name = value; }
}
And calling it (assume we have a person obj with a name property):
Console.WriteLine(Person.Name); //prints "spots"
Person.Name = "stops";
Console.Writeline(Person.Name); //prints "stops"
This simplifies your code. Where in Java you might have to have two methods, one to Get() and one to Set() the property, in C# it is all done in one spot. I usually do this at the start of my classes:
public string foobar {get; set;}
This creates a getter and setter for my foobar property. Calling it is the same way as shown before. Somethings to note are that you don't have to include both get and set. If you don't want the property being modified, don't include set!
This is the code I'm using right now for a website I'm making that needs to get the leading paragraphs / summary / section 0 of off Wikipedia articles, and it's all done within the browser (client side javascript) thanks to the magick of JSONP! --> http://jsfiddle.net/gautamadude/HMJJg/1/
It uses the Wikipedia API to get the leading paragraphs (called section 0) in HTML like so: http://en.wikipedia.org/w/api.php?format=json&action=parse&page=Stack_Overflow&prop=text§ion=0&callback=?
It then strips the HTML and other undesired data, giving you a clean string of an article summary, if you want you can, with a little tweaking, get a "p" html tag around the leading paragraphs but right now there is just a newline character between them.
Code:
var url = "http://en.wikipedia.org/wiki/Stack_Overflow";
var title = url.split("/").slice(4).join("/");
//Get Leading paragraphs (section 0)
$.getJSON("http://en.wikipedia.org/w/api.php?format=json&action=parse&page=" + title + "&prop=text§ion=0&callback=?", function (data) {
for (text in data.parse.text) {
var text = data.parse.text[text].split("<p>");
var pText = "";
for (p in text) {
//Remove html comment
text[p] = text[p].split("<!--");
if (text[p].length > 1) {
text[p][0] = text[p][0].split(/\r\n|\r|\n/);
text[p][0] = text[p][0][0];
text[p][0] += "</p> ";
}
text[p] = text[p][0];
//Construct a string from paragraphs
if (text[p].indexOf("</p>") == text[p].length - 5) {
var htmlStrip = text[p].replace(/<(?:.|\n)*?>/gm, '') //Remove HTML
var splitNewline = htmlStrip.split(/\r\n|\r|\n/); //Split on newlines
for (newline in splitNewline) {
if (splitNewline[newline].substring(0, 11) != "Cite error:") {
pText += splitNewline[newline];
pText += "\n";
}
}
}
}
pText = pText.substring(0, pText.length - 2); //Remove extra newline
pText = pText.replace(/\[\d+\]/g, ""); //Remove reference tags (e.x. [1], [4], etc)
document.getElementById('textarea').value = pText
document.getElementById('div_text').textContent = pText
}
});
(Assuming you don't have/want line breaks in your string...)
How long is this string really?
I suspect there is a limit to how long a line read from a file or from the commandline can be, and because the end of the line gets choped off the parser sees something like s1="some very long string..........
(without an ending "
) and thus throws a parsing error?
You can split long lines up in multiple lines by escaping linebreaks in your source like this:
s1="some very long string.....\
...\
...."
The new Chosen libraries don't use the liszt. I used the following:
document.getElementById('autoship_option').selectedIndex = 0;
$("#autoship_option").trigger("chosen:updated");
In a general way, if you want to pick up the first N rows from the J column from pandas dataframe
the best way to do this is:
data = dataframe[0:N][:,J]
You simply have to pipe an iconv command before the sed command. Ex with file.txt input :
iconv -f ISO-8859-1 -t UTF8-MAC file.txt | sed 's/something/àéèêçùû/g' | .....
-f option is the 'from' codeset and -t option is the 'to' codeset conversion.
Take care of case, web pages usually show lowercase like that < charset=iso-8859-1"/> and iconv uses uppercase. You have list of iconv supported codesets in you system with command iconv -l
UTF8-MAC is modern OS Mac codeset for conversion.
$(document).ready(function(){
$('#characterLeft').text('140 characters left');
$('#message').keydown(function () {
var max = 140;
var len = $(this).val().length;
if (len >= max) {
$('#characterLeft').text('You have reached the limit');
$('#characterLeft').addClass('red');
$('#btnSubmit').addClass('disabled');
}
else {
var ch = max - len;
$('#characterLeft').text(ch + ' characters left');
$('#btnSubmit').removeClass('disabled');
$('#characterLeft').removeClass('red');
}
});
});
if you are using netbeans you can add a jlabel to the frame and through properties change its icon to your image and remove the text. then move the jlabel to the bottom of the Jframe or any content pane through navigator
No comma after the last property.
Semicolon after alert(date);
Case on datepicker (not datePicker)
Check your other uppercase / lowercase for the properties.
$(function() {
$('.date-pick').datepicker( {
onSelect: function(date) {
alert(date);
},
selectWeek: true,
inline: true,
startDate: '01/01/2000',
firstDay: 1
});
});
I know that this topic is quite old, but this need is still alive. I read many documents, forum and script and build a new advanced one which supports compressed and uncompressed pdf :
https://gist.github.com/smalot/6183152
Hope it helps everone
check out the implode function, since the values are in an array, you want to put the values of the array into a mysql query that inserts the values into a table.
$query = "INSERT INto hardware (specifications) VALUES (".implode(",",$specifications).")";
If the values in the array are text values, you will need to add quotes
$query = "INSERT INto hardware (specifications) VALUES ("'.implode("','",$specifications)."')";
mysql_query($query);
Also, if you don't want duplicate values, switch the "INto" to "IGNORE" and only unique values will be inserted into the table.
I use Globalize so work with many date formats so use the following:
@Html.TextBoxFor(m => m.DateOfBirth, "{0:d}")
This will automatically adjust the date format to the browser's locale settings.
All of the above seem to work when spliced in, but gobyexample's signals page has a really clean and complete example of signal capturing. Worth adding to this list.
Here is java solution of the answer by Mehrdad Afshari.
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
public class Tree {
Iterator<Node> buildTreeAndGetRoots(List<MyObject> actualObjects) {
Map<Integer, Node> lookup = new HashMap<>();
actualObjects.forEach(x -> lookup.put(x.id, new Node(x)));
//foreach (var item in lookup.Values)
lookup.values().forEach(item ->
{
Node proposedParent;
if (lookup.containsKey(item.associatedObject.parentId)) {
proposedParent = lookup.get(item.associatedObject.parentId);
item.parent = proposedParent;
proposedParent.children.add(item);
}
}
);
//return lookup.values.Where(x =>x.Parent ==null);
return lookup.values().stream().filter(x -> x.parent == null).iterator();
}
}
class MyObject { // The actual object
public int parentId;
public int id;
}
class Node {
public List<Node> children = new ArrayList<Node>();
public Node parent;
public MyObject associatedObject;
public Node(MyObject associatedObject) {
this.associatedObject = associatedObject;
}
}
There is a good class that does what you want. It can be downloaded at: http://sourceforge.net/projects/snoopy/
This is the way to iterate on this array:
foreach($hotels as $row) {
foreach($row['rooms'] as $k) {
echo $k['boards']['board_id'];
echo $k['boards']['price'];
}
}
You want to iterate on the hotels and the rooms (the ones with numeric indexes), because those seem to be the "collections" in this case. The other arrays only hold and group properties.
No Root and no ADB tools required method. Install MyAppSharer app from the play store.
foreach ($all_address as $aa) {
$mail->AddAddress($aa);
}
STA (Single Threaded Apartment) is basically the concept that only one thread will interact with your code at a time. Calls into your apartment are marshaled via windows messages (using a non-visible) window. This allows calls to be queued and wait for operations to complete.
MTA (Multi Threaded Apartment) is where many threads can all operate at the same time and the onus is on you as the developer to handle the thread security.
There is a lot more to learn about threading models in COM, but if you are having trouble understanding what they are then I would say that understanding what the STA is and how it works would be the best starting place because most COM objects are STA’s.
Apartment Threads, if a thread lives in the same apartment as the object it is using then it is an apartment thread. I think this is only a COM concept because it is only a way of talking about the objects and threads they interact with…
Long Press on Power button, then you will have the option for the screenshot.
Value is not null, but DBNull.Value.
object value = cmd.ExecuteScalar();
if(value == DBNull.Value)
I have also tried that error , I got it right by just adding /hello/any name because it is path that there must be an hello/name
example : instead of just putting http://localhost/app_dev.php
put it like this way http://localhost/name_of_your_project/web/app_dev.php/hello/ai
it will display Hello Ai . I hope I answer your question.
I'm a little out of touch with the details of how MySQL deals with nulls, but here's two things to try:
SELECT * FROM match WHERE id NOT IN
( SELECT id FROM email WHERE id IS NOT NULL) ;
SELECT
m.*
FROM
match m
LEFT OUTER JOIN email e ON
m.id = e.id
AND e.id IS NOT NULL
WHERE
e.id IS NULL
The second query looks counter intuitive, but it does the join condition and then the where condition. This is the case where joins and where clauses are not equivalent.
mysqli_select_db()
should have 2 parameters, the connection link and the database name -
mysqli_select_db($con, 'phpcadet') or die(mysqli_error($con));
Using mysqli_error
in the die statement will tell you exactly what is wrong as opposed to a generic error message.
curl -iv https://your.domain.io
That will give you cert and header output if you do not wish to use openssl command.
This worked for me, no delayed expansion necessary:
@echo off
(
echo ^<html^>
echo ^<body^>
echo Hello
echo ^</body^>
echo ^</html^>
)
pause
It writes output like this:
<html>
<body>
Hello
</body>
</html>
Press any key to continue . . .
I'm using a simpler method:
The navigator global object has a property touchpoints, in Internet Exlorer 11 is called msMaxTouchPoints tho.
So if you look for:
navigator.msMaxTouchPoints !== void 0
You will find Internet Explorer 11.
$ git push origin develop:master
or, more generally
$ git push <remote> <local branch name>:<remote branch to push into>
As far as I know there is no “native” PowerShell way of getting this information. And perhaps it is rather the .NET limitation than PowerShell.
Here is the suggestion to add this functionality to the version next:
The WMI workaround is also there, just in case. I use this WMI solution for my tasks and it works.
Since Eclipse Neon which contains Eclipse Maven Integration (m2e) 1.7, the preferred way is one of the following ways:
.project
) as well as for non-Eclipse projects that only contain the file pom.xml
.The IEnumerable<T>
interface does not include an indexer, you're probably confusing it with IList<T>
If the object really is an IList<T>
(e.g. List<T>
or an array T[]
), try making the reference to it of type IList<T>
too.
Otherwise, you can use myEnumerable.ElementAt(index)
which uses the Enumerable.ElementAt extension method. This should work for all IEnumerable<T>
s .
Note that unless the (run-time) object implements IList<T>
, this will cause all of the first index + 1
items to be enumerated, with all but the last being discarded.
EDIT:
As an explanation, IEnumerable<T>
is simply an interface that represents "that which exposes an enumerator." A concrete implementation may well be some sort of in-memory list that does allow fast-access by index, or it may not. For instance, it could be a collection that cannot efficiently satisfy such a query, such as a linked-list (as mentioned by James Curran). It may even be no sort of in-memory data-structure at all, such as an iterator, where items are generated ('yielded') on demand, or by an enumerator that fetches the items from some remote data-source. Because IEnumerable<T>
must support all these cases, indexers are excluded from its definition.
Here is what worked for me (Dominic was just one line short).
$url = "";
$options = array(
'http'=>array(
'method'=>"GET",
'header'=>"Accept-language: en\r\n" .
"Cookie: foo=bar\r\n" . // check function.stream-context-create on php.net
"User-Agent: Mozilla/5.0 (iPad; U; CPU OS 3_2 like Mac OS X; en-us) AppleWebKit/531.21.10 (KHTML, like Gecko) Version/4.0.4 Mobile/7B334b Safari/531.21.102011-10-16 20:23:10\r\n" // i.e. An iPad
)
);
$context = stream_context_create($options);
$file = file_get_contents($url, false, $context);
What worked for me, was to add explicit name to celery task decorator. I changed my task declaration from @app.tasks
to @app.tasks(name='module.submodule.task')
Here is an example
# test_task.py
@celery.task
def test_task():
print("Celery Task !!!!")
# test_task.py
@celery.task(name='tasks.test.test_task')
def test_task():
print("Celery Task !!!!")
Below are the steps that worked for me
from google.colab import drive drive.mount('/content/drive')
import sys sys.path.insert(0,’/content/drive/My Drive/ColabNotebooks’)
%cd drive/MyDrive/ColabNotebooks %pwd
import my_module
If you get the following error 'Name Null is not defined' then do the following
5.1 Download my_module.ipynb from colab as my_module.py file (file->Download .py)
5.2 Upload the *.py file to drive/MyDrive/ColabNotebooks in Google drive
5.3 import my_module will work now
//sure run it i will also test it
//we make a class that extends with the fragment
public class Example_3_1 extends Fragment implements OnClickListener
{
View vi;
EditText t;
EditText t1;
Button bu;
// that are by defult function of fragment extend class
@Override
public View onCreateView(LayoutInflater inflater,ViewGroup container,BundlesavedInstanceState)
{
vi=inflater.inflate(R.layout.example_3_1, container, false);// load the xml file
bu=(Button) vi.findViewById(R.id.button1);// get button id from example_3_1 xml file
bu.setOnClickListener(this); //on button appay click listner
t=(EditText) vi.findViewById(R.id.editText1);// id get from example_3_1 xml file
t1=(EditText) vi.findViewById(R.id.editText2);
return vi; // return the view object,that set the xml file example_3_1 xml file
}
@Override
public void onClick(View v)//on button click that called
{
switch(v.getId())// on run time get id what button os click and get id
{
case R.id.button1: // it mean if button1 click then this work
t.setText("UMTien"); //set text
t1.setText("programming");
break;
}
} }
You can make use of cut
, sort
and uniq
commands as follows:
cat input_file | cut -f 1 | sort | uniq
gets unique values in field 1, replacing 1 by 2 will give you unique values in field 2.
Avoiding UUOC :)
cut -f 1 input_file | sort | uniq
EDIT:
To count the number of unique occurences you can make use of wc
command in the chain as:
cut -f 1 input_file | sort | uniq | wc -l
To answer your question:
.html()
will just call .innerHTML
after doing some checks for nodeTypes and stuff. It also uses a try/catch
block where it tries to use innerHTML
first and if that fails, it'll fallback gracefully to jQuery's .empty()
+ append()
A few comments:
analog=True
in the call to butter
, and you should use scipy.signal.freqz
(not freqs
) to generate the frequency response.Here's my modified version of your script, followed by the plot that it generates.
import numpy as np
from scipy.signal import butter, lfilter, freqz
import matplotlib.pyplot as plt
def butter_lowpass(cutoff, fs, order=5):
nyq = 0.5 * fs
normal_cutoff = cutoff / nyq
b, a = butter(order, normal_cutoff, btype='low', analog=False)
return b, a
def butter_lowpass_filter(data, cutoff, fs, order=5):
b, a = butter_lowpass(cutoff, fs, order=order)
y = lfilter(b, a, data)
return y
# Filter requirements.
order = 6
fs = 30.0 # sample rate, Hz
cutoff = 3.667 # desired cutoff frequency of the filter, Hz
# Get the filter coefficients so we can check its frequency response.
b, a = butter_lowpass(cutoff, fs, order)
# Plot the frequency response.
w, h = freqz(b, a, worN=8000)
plt.subplot(2, 1, 1)
plt.plot(0.5*fs*w/np.pi, np.abs(h), 'b')
plt.plot(cutoff, 0.5*np.sqrt(2), 'ko')
plt.axvline(cutoff, color='k')
plt.xlim(0, 0.5*fs)
plt.title("Lowpass Filter Frequency Response")
plt.xlabel('Frequency [Hz]')
plt.grid()
# Demonstrate the use of the filter.
# First make some data to be filtered.
T = 5.0 # seconds
n = int(T * fs) # total number of samples
t = np.linspace(0, T, n, endpoint=False)
# "Noisy" data. We want to recover the 1.2 Hz signal from this.
data = np.sin(1.2*2*np.pi*t) + 1.5*np.cos(9*2*np.pi*t) + 0.5*np.sin(12.0*2*np.pi*t)
# Filter the data, and plot both the original and filtered signals.
y = butter_lowpass_filter(data, cutoff, fs, order)
plt.subplot(2, 1, 2)
plt.plot(t, data, 'b-', label='data')
plt.plot(t, y, 'g-', linewidth=2, label='filtered data')
plt.xlabel('Time [sec]')
plt.grid()
plt.legend()
plt.subplots_adjust(hspace=0.35)
plt.show()
I wrote this to compare the results of a pretty nasty view I ported from Oracle to SQL Server. It creates a pair of temp tables, #DataVariances and #SchemaVariances, with differences in (you guessed it) the data in the tables and the schema of the tables themselves.
It requires both tables have a primary key, but you could drop it into tempdb with an identity column if the source tables don't have one.
declare @TableA_ThreePartName nvarchar(max) = ''
declare @TableB_ThreePartName nvarchar(max) = ''
declare @KeyName nvarchar(max) = ''
/***********************************************************************************************
Script to compare two tables and return differneces in schema and data.
Author: Devin Lamothe 2017-08-11
***********************************************************************************************/
set nocount on
-- Split three part name into database/schema/table
declare @Database_A nvarchar(max) = (
select left(@TableA_ThreePartName,charindex('.',@TableA_ThreePartName) - 1))
declare @Table_A nvarchar(max) = (
select right(@TableA_ThreePartName,len(@TableA_ThreePartName) - charindex('.',@TableA_ThreePartName,len(@Database_A) + 2)))
declare @Schema_A nvarchar(max) = (
select replace(replace(@TableA_ThreePartName,@Database_A + '.',''),'.' + @Table_A,''))
declare @Database_B nvarchar(max) = (
select left(@TableB_ThreePartName,charindex('.',@TableB_ThreePartName) - 1))
declare @Table_B nvarchar(max) = (
select right(@TableB_ThreePartName,len(@TableB_ThreePartName) - charindex('.',@TableB_ThreePartName,len(@Database_B) + 2)))
declare @Schema_B nvarchar(max) = (
select replace(replace(@TableB_ThreePartName,@Database_B + '.',''),'.' + @Table_B,''))
-- Get schema for both tables
declare @GetTableADetails nvarchar(max) = '
use [' + @Database_A +']
select COLUMN_NAME
, DATA_TYPE
from INFORMATION_SCHEMA.COLUMNS
where TABLE_NAME = ''' + @Table_A + '''
and TABLE_SCHEMA = ''' + @Schema_A + '''
'
create table #Table_A_Details (
ColumnName nvarchar(max)
, DataType nvarchar(max)
)
insert into #Table_A_Details
exec (@GetTableADetails)
declare @GetTableBDetails nvarchar(max) = '
use [' + @Database_B +']
select COLUMN_NAME
, DATA_TYPE
from INFORMATION_SCHEMA.COLUMNS
where TABLE_NAME = ''' + @Table_B + '''
and TABLE_SCHEMA = ''' + @Schema_B + '''
'
create table #Table_B_Details (
ColumnName nvarchar(max)
, DataType nvarchar(max)
)
insert into #Table_B_Details
exec (@GetTableBDetails)
-- Get differences in table schema
select ROW_NUMBER() over (order by
a.ColumnName
, b.ColumnName) as RowKey
, a.ColumnName as A_ColumnName
, a.DataType as A_DataType
, b.ColumnName as B_ColumnName
, b.DataType as B_DataType
into #FieldList
from #Table_A_Details a
full outer join #Table_B_Details b
on a.ColumnName = b.ColumnName
where a.ColumnName is null
or b.ColumnName is null
or a.DataType <> b.DataType
drop table #Table_A_Details
drop table #Table_B_Details
select coalesce(A_ColumnName,B_ColumnName) as ColumnName
, A_DataType
, B_DataType
into #SchemaVariances
from #FieldList
-- Get differences in table data
declare @LastColumn int = (select max(RowKey) from #FieldList)
declare @RowNumber int = 1
declare @ThisField nvarchar(max)
declare @TestSql nvarchar(max)
create table #DataVariances (
TableKey nvarchar(max)
, FieldName nvarchar(max)
, TableA_Value nvarchar(max)
, TableB_Value nvarchar(max)
)
delete from #FieldList where A_DataType in ('varbinary','image') or B_DataType in ('varbinary','image')
while @RowNumber <= @LastColumn begin
set @TestSql = '
select coalesce(a.[' + @KeyName + '],b.[' + @KeyName + ']) as TableKey
, ''' + @ThisField + ''' as FieldName
, a.[' + @ThisField + '] as [TableA_Value]
, b.[' + @ThisField + '] as [TableB_Value]
from [' + @Database_A + '].[' + @Schema_A + '].[' + @Table_A + '] a
inner join [' + @Database_B + '].[' + @Schema_B + '].[' + @Table_B + '] b
on a.[' + @KeyName + '] = b.[' + @KeyName + ']
where ltrim(rtrim(a.[' + @ThisField + '])) <> ltrim(rtrim(b.[' + @ThisField + ']))
or (a.[' + @ThisField + '] is null and b.[' + @ThisField + '] is not null)
or (a.[' + @ThisField + '] is not null and b.[' + @ThisField + '] is null)
'
insert into #DataVariances
exec (@TestSql)
set @RowNumber = @RowNumber + 1
set @ThisField = (select coalesce(A_ColumnName,B_ColumnName) from #FieldList a where RowKey = @RowNumber)
end
drop table #FieldList
print 'Query complete. Select from #DataVariances to verify data integrity or #SchemaVariances to verify schemas match. Data types varbinary and image are not checked.'
SO So So simple solution , go to c:/Users/user_name/.ssh/ and delete all pub / private key pairs , this way heroku will generate keys for you.
There's better support for this now through conda-env
. You can, for example, now do:
name: sample_env
channels:
dependencies:
- requests
- bokeh>=0.10.0
- pip:
- "--editable=git+https://github.com/pythonforfacebook/facebook-sdk.git@8c0d34291aaafec00e02eaa71cc2a242790a0fcc#egg=facebook_sdk-master"
It's still calling pip under the covers, but you can now unify your conda and pip package specifications in a single environment.yml
file.
If you wanted to update your root environment with this file, you would need to save this to a file (for example, environment.yml
), then run the command: conda env update -f environment.yml
.
It's more likely that you would want to create a new environment:
conda env create -f environment.yml
(changed as supposed in the comments)
If you want to force the issue, you can do:
git reset --hard c14809fafb08b9e96ff2879999ba8c807d10fb07
send you back to how your git clone looked like at the time of the checkin
A function is tail recursive if each recursive case consists only of a call to the function itself, possibly with different arguments. Or, tail recursion is recursion with no pending work. Note that this is a programming-language independent concept.
Consider the function defined as:
g(a, b, n) = a * b^n
A possible tail-recursive formulation is:
g(a, b, n) | n is zero = a
| n is odd = g(a*b, b, n-1)
| otherwise = g(a, b*b, n/2)
If you examine each RHS of g(...)
that involves a recursive case, you'll find that the whole body of the RHS is a call to g(...)
, and only that. This definition is tail recursive.
For comparison, a non-tail-recursive formulation might be:
g'(a, b, n) = a * f(b, n)
f(b, n) | n is zero = 1
| n is odd = f(b, n-1) * b
| otherwise = f(b, n/2) ^ 2
Each recursive case in f(...)
has some pending work that needs to happen after the recursive call.
Note that when we went from g'
to g
, we made essential use of associativity
(and commutativity) of multiplication. This is not an accident, and most cases where you will need to transform recursion to tail-recursion will make use of such properties: if we want to eagerly do some work rather than leave it pending, we have to use something like associativity to prove that the answer will be the same.
Tail recursive calls can be implemented with a backwards jump, as opposed to using a stack for normal recursive calls. Note that detecting a tail call, or emitting a backwards jump is usually straightforward. However, it is often hard to rearrange the arguments such that the backwards jump is possible. Since this optimization is not free, language implementations can choose not to implement this optimization, or require opt-in by marking recursive calls with a 'tailcall' instruction and/or choosing a higher optimization setting.
Some languages (e.g. Scheme) do, however, require all implementations to optimize tail-recursive functions, maybe even all calls in tail position.
Backwards jumps are usually abstracted as a (while) loop in most imperative languages, and tail-recursion, when optimized to a backwards jump, is isomorphic to looping.
Another thing that worked for me was to make the instance variable Long in place of long
I had my primary key variable long id;
changing it to Long id; worked
All the best
You need to use a <br>
because your Content-Type
is text/html
.
It works without the Content-Type
header because then your e-mail will be interpreted as plain text. If you really want to use \n
you should use Content-Type: text/plain
but then you'll lose any markup.
Also check out similar question here.
Use the DATEDIFF
function with a datepart of day
.
SELECT ...
FROM ...
WHERE DATEDIFF(day, date1, date2) >= 0
Note that if you want to test that date1
<= date2
then you need to test that DATEDIFF(day, date1, date2) >= 0
, or alternatively you could test DATEDIFF(day, date2, date1) <= 0
.
if your wanting to use jQuery for this, try the following code.
$('select option[value="1"]').attr("selected",true);
Updated:
Following a comment from Vivek, correctly pointed out steven spielberg wanted to select the option via its Text value.
Here below is the updated code.
$('select option:contains("it\'s me")').prop('selected',true);
You need to use the :contains(text)
selector to find via the containing text.
Also jQuery prop offeres better support for Internet Explorer when getting and setting attributes.
Simply forcefully kill the process ID, the hadoop job will also be killed automatically . Use this command:
kill -9 <process_id>
eg: process ID no: 4040 namenode
username@hostname:~$ kill -9 4040
This might sound stupid, but, in the first problem presented to you, you would have to see all the remaining numbers in the bag to actually add them up to find the missing number using that equation.
So, since you get to see all the numbers, just look for the number that's missing. The same goes for when two numbers are missing. Pretty simple I think. No point in using an equation when you get to see the numbers remaining in the bag.
There are many options how to write a regex pattern for that
^(?:(?!0)\d{1,2}|100)$
^(?:[1-9]\d?|100)$
^(?!0)(?=100$|..$|.$)\d+$
I tried almost all the answers proposed on this page and many other stuff. The best option I finally keeped on all my websites is the following architecture:
A single view
I display only one view in the browser. Here is my main view (/views/page.php):
<?php defined('BASEPATH') OR exit('No direct script access allowed'); ?>
<!DOCTYPE html>
<html lang="en">
<head>
<?= $header ?? '' ?>
</head>
<body>
<div style="width:1200px">
<?= $content ?? '' ?>
</div>
</body>
</html>
Controllers deal with multiple views
Of course, I had several views but they are concatenated to build the $header
and the $content
variables. Here is my controller:
$data['header'] = $this->load->view('templates/google-analytics', '', TRUE)
.$this->load->view('templates/javascript', '', TRUE)
.$this->load->view('templates/css', '', TRUE);
$data['content'] = $this->load->view('templates/navbar', '', TRUE)
.$this->load->view('templates/alert', $myData, TRUE)
.$this->load->view('home/index', $myData, TRUE)
.$this->load->view('home/footer', '', TRUE)
.$this->load->view('templates/modal-login', '', TRUE);
$this->load->view('templates/page', $data);
$javascript
variable at the end of the body)$this->load->view
with extra parameters dedicated to my application to keep my controllers clean.I'm so proud of this architecture...
use <br/>
tag
Example:
<string name="copyright"><b>@</b> 2014 <br/>
Corporation.<br/>
<i>All rights reserved.</i></string>
Steps:
Example
x=pd.DataFrame([1,2,3,4])
def add(i1, i2):
return i1+i2
x.apply(add,i2=9)
The outcome of this example is that each number in the dataframe will be added to the number 9.
0
0 10
1 11
2 12
3 13
Explanation:
The "add" function has two parameters: i1, i2. The first parameter is going to be the value in data frame and the second is whatever we pass to the "apply" function. In this case, we are passing "9" to the apply function using the keyword argument "i2".
There is also the Memory Measurer tool (formerly at Google Code, now on GitHub), which is simple and published under the commercial-friendly Apache 2.0 license, as discussed in a similar question.
It, too, requires a command-line argument to the java interpreter if you want to measure memory byte consumption, but otherwise seems to work just fine, at least in the scenarios I have used it.
Just came across this and the short code for transparency is simply #00000000.
I just do it like this:
CvCapture *capture = cvCreateFileCapture("rtsp://camera-address");
Also make sure this dll is available at runtime else cvCreateFileCapture will return NULL
opencv_ffmpeg200d.dll
The camera needs to allow unauthenticated access too, usually set via its web interface. MJPEG format worked via rtsp but MPEG4 didn't.
hth
Si
I got this working this way:
public void showHome() {
getHandler().post(new Runnable() {
@Override
public void run() {
final FragmentManager fm = getSupportFragmentManager();
while (fm.getBackStackEntryCount() > 0) {
fm.popBackStackImmediate();
}
}
});
}
When you do not provide mapDispatchToProps
as a second argument, like this:
export default connect(mapStateToProps)(Checkbox)
then you are automatically getting the dispatch to component's props, so you can just:
class SomeComp extends React.Component {
constructor(props, context) {
super(props, context);
}
componentDidMount() {
this.props.dispatch(ACTION GOES HERE);
}
....
without any mapDispatchToProps
Select into creates new table for you at the time and then insert records in it from the source table. The newly created table has the same structure as of the source table.If you try to use select into for a existing table it will produce a error, because it will try to create new table with the same name. Insert into requires the table to be exist in your database before you insert rows in it.
You are trying to use the wrong interface type. The type Function is not appropriate in this case because it receives a parameter and has a return value. Instead you should use Consumer (formerly known as Block)
The Function type is declared as
interface Function<T,R> {
R apply(T t);
}
However, the Consumer type is compatible with that you are looking for:
interface Consumer<T> {
void accept(T t);
}
As such, Consumer is compatible with methods that receive a T and return nothing (void). And this is what you want.
For instance, if I wanted to display all element in a list I could simply create a consumer for that with a lambda expression:
List<String> allJedi = asList("Luke","Obiwan","Quigon");
allJedi.forEach( jedi -> System.out.println(jedi) );
You can see above that in this case, the lambda expression receives a parameter and has no return value.
Now, if I wanted to use a method reference instead of a lambda expression to create a consume of this type, then I need a method that receives a String and returns void, right?.
I could use different types of method references, but in this case let's take advantage of an object method reference by using the println
method in the System.out
object, like this:
Consumer<String> block = System.out::println
Or I could simply do
allJedi.forEach(System.out::println);
The println
method is appropriate because it receives a value and has a return type void, just like the accept
method in Consumer.
So, in your code, you need to change your method signature to somewhat like:
public static void myForEach(List<Integer> list, Consumer<Integer> myBlock) {
list.forEach(myBlock);
}
And then you should be able to create a consumer, using a static method reference, in your case by doing:
myForEach(theList, Test::displayInt);
Ultimately, you could even get rid of your myForEach
method altogether and simply do:
theList.forEach(Test::displayInt);
About Functions as First Class Citizens
All been said, the truth is that Java 8 will not have functions as first-class citizens since a structural function type will not be added to the language. Java will simply offer an alternative way to create implementations of functional interfaces out of lambda expressions and method references. Ultimately lambda expressions and method references will be bound to object references, therefore all we have is objects as first-class citizens. The important thing is the functionality is there since we can pass objects as parameters, bound them to variable references and return them as values from other methods, then they pretty much serve a similar purpose.
In my opinion, the most elegant and idiomatic way of prepending an element or list to another list, in Python, is using the expansion operator * (also called unpacking operator),
# Initial list
l = [4, 5, 6]
# Modification
l = [1, 2, 3, *l]
Where the resulting list after the modification is [1, 2, 3, 4, 5, 6]
I also like simply combining two lists with the operator +, as shown,
# Prepends [1, 2, 3] to l
l = [1, 2, 3] + l
# Prepends element 42 to l
l = [42] + l
I don't like the other common approach, l.insert(0, value)
, as it requires a magic number. Moreover, insert()
only allows prepending a single element, however the approach above has the same syntax for prepending a single element or multiple elements.
The accepted solution have following drawbacks:
If your keys do not require to type password, I suggest following solution. Add the following to your .bash_profile
very end (edit key list to your needs):
exec ssh-agent $BASH -s 10<&0 << EOF
ssh-add ~/.ssh/your_key1.rsa \
~/.ssh/your_key2.rsa &> /dev/null
exec $BASH <&10-
EOF
It have following advantages:
It have possible disadvantages:
ssh-add
command will influence only one session, which is in fact an issue only in very untypical circumstances;Note that several ssh-agent
processes is not a disadvantage, because they don't take more memory or CPU time.
Trying to give a very simplified explanation
Virtual Memory is divided into kernel space and the user space. Kernel space is that area of virtual memory where kernel processes will run and user space is that area of virtual memory where user processes will be running.
This division is required for memory access protections.
Whenever a bootloader starts a kernel after loading it to a location in RAM, (on an ARM based controller typically)it needs to make sure that the controller is in supervisor mode with FIQ's and IRQ's disabled.