CentOS 7: I had the libcurl and gnutls development packages installed already, but still got the "cannot load git2r.so" error when installing devtools in R. I had to "reinstall" them for it to work:
sudo yum reinstall gnutls-devel.x86_64
Here is the code I use in my C++ app.
Positive points :
Negative points :
// Inspired from http://stackoverflow.com/a/15281070/1529139
// and http://stackoverflow.com/q/40059902/1529139
bool signalCtrl(DWORD dwProcessId, DWORD dwCtrlEvent)
{
bool success = false;
DWORD thisConsoleId = GetCurrentProcessId();
// Leave current console if it exists
// (otherwise AttachConsole will return ERROR_ACCESS_DENIED)
bool consoleDetached = (FreeConsole() != FALSE);
if (AttachConsole(dwProcessId) != FALSE)
{
// Add a fake Ctrl-C handler for avoid instant kill is this console
// WARNING: do not revert it or current program will be also killed
SetConsoleCtrlHandler(nullptr, true);
success = (GenerateConsoleCtrlEvent(dwCtrlEvent, 0) != FALSE);
FreeConsole();
}
if (consoleDetached)
{
// Create a new console if previous was deleted by OS
if (AttachConsole(thisConsoleId) == FALSE)
{
int errorCode = GetLastError();
if (errorCode == 31) // 31=ERROR_GEN_FAILURE
{
AllocConsole();
}
}
}
return success;
}
Usage example :
DWORD dwProcessId = ...;
if (signalCtrl(dwProcessId, CTRL_C_EVENT))
{
cout << "Signal sent" << endl;
}
From Perl HowTo, the most common ways to execute external commands from Perl are:
my $files = `ls -la`
— captures the output of the command in $files
system "touch ~/foo"
— if you don't want to capture the command's outputexec "vim ~/foo"
— if you don't want to return to the script after executing the commandopen(my $file, '|-', "grep foo"); print $file "foo\nbar"
— if you want to pipe input into the commandThe operator == casts between two different types if they are different, while the === operator performs a 'typesafe comparison'. That means that it will only return true if both operands have the same type and the same value.
Examples:
1 === 1: true
1 == 1: true
1 === "1": false // 1 is an integer, "1" is a string
1 == "1": true // "1" gets casted to an integer, which is 1
"foo" === "foo": true // both operands are strings and have the same value
Warning: two instances of the same class with equivalent members do NOT match the ===
operator. Example:
$a = new stdClass();
$a->foo = "bar";
$b = clone $a;
var_dump($a === $b); // bool(false)
install pip install pypiwin32
from win32com.client import Dispatch
speak = Dispatch("SAPI.SpVoice").Speak
speak("Ciao")
After you installed the gtts module in cmd: pip install gtts
from gtts import gTTS
import os
tts = gTTS(text="This is the pc speaking", lang='en')
tts.save("pcvoice.mp3")
# to start the file from python
os.system("start pcvoice.mp3")
For anyone that is using MariaDB instead of MySQL, the solution is to install the libmariadbclient-dev
package and create a symbolic link to the config file with the correct name.
For example this worked for me:
ln -s /usr/bin/mariadb_config /usr/bin/mysql_config
Another way using JOIN and CURSOR:
USE My_Database;
-- Store results in a local temp table so that. I'm using a
-- local temp table so that I can access it in SP_EXECUTESQL.
create table #tmp (
tbl nvarchar(max),
col nvarchar(max),
val nvarchar(max)
);
declare @tbl nvarchar(max);
declare @col nvarchar(max);
declare @q nvarchar(max);
declare @search nvarchar(max) = 'my search key';
-- Create a cursor on all columns in the database
declare c cursor for
SELECT tbls.TABLE_NAME, cols.COLUMN_NAME FROM INFORMATION_SCHEMA.TABLES AS tbls
JOIN INFORMATION_SCHEMA.COLUMNS AS cols
ON tbls.TABLE_NAME = cols.TABLE_NAME
-- For each table and column pair, see if the search value exists.
open c
fetch next from c into @tbl, @col
while @@FETCH_STATUS = 0
begin
-- Look for the search key in current table column and if found add it to the results.
SET @q = 'INSERT INTO #tmp SELECT ''' + @tbl + ''', ''' + @col + ''', ' + @col + ' FROM ' + @tbl + ' WHERE ' + @col + ' LIKE ''%' + @search + '%'''
EXEC SP_EXECUTESQL @q
fetch next from c into @tbl, @col
end
close c
deallocate c
-- Get results
select * from #tmp
-- Remove local temp table.
drop table #tmp
Which app server are you using? Each one puts its logging config in a different place, though most nowadays use Commons-Logging as a wrapper around either Log4J or java.util.logging.
Using Tomcat as an example, this document explains your options for configuring logging using either option. In either case you need to find or create a config file that defines the log level for each package and each place the logging system will output log info (typically console, file, or db).
In the case of log4j this would be the log4j.properties file, and if you follow the directions in the link above your file will start out looking like:
log4j.rootLogger=DEBUG, R
log4j.appender.R=org.apache.log4j.RollingFileAppender
log4j.appender.R.File=${catalina.home}/logs/tomcat.log
log4j.appender.R.MaxFileSize=10MB
log4j.appender.R.MaxBackupIndex=10
log4j.appender.R.layout=org.apache.log4j.PatternLayout
log4j.appender.R.layout.ConversionPattern=%p %t %c - %m%n
Simplest would be to change the line:
log4j.rootLogger=DEBUG, R
To something like:
log4j.rootLogger=WARN, R
But if you still want your own DEBUG level output from your own classes add a line that says:
log4j.category.com.mypackage=DEBUG
Reading up a bit on Log4J and Commons-Logging will help you understand all this.
To install android component do following steps
Fetching https://dl-ssl.google.com/android/repository/addons_list-2.xml
Fetched Add-ons List successfully
Fetching URL: https://dl-ssl.google.com/android/repository/repository-7.xml
Validate XML: https://dl-ssl.google.com/android/repository/repository-7.xml
Parse XML: https://dl-ssl.google.com/android/repository/repository-7.xml
https://dl-ssl.google.com/android/repository/addons_list-2.xml is main xml file where all other package list is available.
lets say you want to download platform api-9 and it is available on repository-7 then you have to do following steps
note the repository address and go to any other machine which has internet connection and type following link in any browser
https://dl-ssl.google.com/android/repository/repository-7.xml
Search for <sdk:url>**android-2.3.1_r02-linux.zip**</sdk:url>
under the api version which you want to download. This is the file name which you have to download. to download this file you have to type following URI in any downloader or browser and it will start download the file.
http://dl-ssl.google.com/android/repository/android-2.3.3_r02-linux.zip
General rule for any file replace android-2.3.3_r02-linux.zip with your package name
Once the download is complete,paste downloaded ZIP(or other format for other os) file in your flash/pen drive and paste the zip file at <android sdk dir>/temp
(ex:- c:\android-sdk\temp
) folder/directory in your offline machine.
Now start the SDK manager and select the package which you have paste in temp and click Install package button. Your package has been installed.
Restart your eclipse and AVD manager to get new packages.
Note:- if you are downloading sdk-tools or sdk platform-tools then choose the package for OS which is on offline machine(windows/Linux/Mac).
When you run into a problem where it cats all.txt into all.txt, You can try check all.txt is existing or not, if exists, remove
Like this:
[ -e $"all.txt" ] && rm $"all.txt"
Suppose you bound your combobox to a List<Person>
List<Person> pp = new List<Person>();
pp.Add(new Person() {id = 1, name="Steve"});
pp.Add(new Person() {id = 2, name="Mark"});
pp.Add(new Person() {id = 3, name="Charles"});
cbo1.DisplayMember = "name";
cbo1.ValueMember = "id";
cbo1.DataSource = pp;
At this point you cannot set the Text property as you like, but instead you need to add an item to your list before setting the datasource
pp.Insert(0, new Person() {id=-1, name="--SELECT--"});
cbo1.DisplayMember = "name";
cbo1.ValueMember = "id";
cbo1.DataSource = pp;
cbo1.SelectedIndex = 0;
Of course this means that you need to add a checking code when you try to use the info from the combobox
if(cbo1.SelectedValue != null && Convert.ToInt32(cbo1.SelectedValue) == -1)
MessageBox.Show("Please select a person name");
else
......
The code is the same if you use a DataTable instead of a list. You need to add a fake row at the first position of the Rows collection of the datatable and set the initial index of the combobox to make things clear. The only thing you need to look at are the name of the datatable columns and which columns should contain a non null value before adding the row to the collection
In a table with three columns like ID, FirstName, LastName with ID,FirstName and LastName required you need to
DataRow row = datatable.NewRow();
row["ID"] = -1;
row["FirstName"] = "--Select--";
row["LastName"] = "FakeAddress";
dataTable.Rows.InsertAt(row, 0);
Sometimes when I get stuck on this I hard code a path to project in the wsgi file like:
import os
import sys
sys.path.append("/var/www/html/myproject")
from django.core.wsgi import get_wsgi_application
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "myproject.settings")
application = get_wsgi_application()
I faced the same issue because I didn't have permission to query the database I was trying to.
In the case you don't have permission to query the table/database, besides the Return Code 2 from org.apache.hadoop.hive.ql.exec.MapRedTask
error, you will see that in Cloudera Manager is not even registering your query.
Similar to @Lithium answer but does not throw a "List may not contain type null" error:
list.removeAll(Collections.<T>singleton(null));
In my case below command worked for windows. It will install latest required version between 3.1.1 and 3.2.0. Depending on OS use either double or single quotes
npm install typescript@">=3.1.1 <3.2.0"
Create a Java archive (.jar) file using NetBeans as follows:
Clean and Build will first delete build artifacts (such as .class
files), whereas Build will retain any existing .class
files, creating new versions necessary. To elucidate, imagine a project with two classes, A and B.
When built the first time, the IDE creates A.class
and B.class
. Now you delete B.java
but don't clear out B.class
. Executing Build should leave B.class
in the build directory, and bundle it into the JAR. Selecting Clean and Build will delete B.class
. Since B.java
was deleted, no longer will B.class
be bundled.
The JAR file is built. To view it inside NetBeans:
Ensure files aren't being excluded when building the JAR file.
I've created this class:
public class Streams {
/**
* Converts Iterable to stream
*/
public static <T> Stream<T> streamOf(final Iterable<T> iterable) {
return toStream(iterable, false);
}
/**
* Converts Iterable to parallel stream
*/
public static <T> Stream<T> parallelStreamOf(final Iterable<T> iterable) {
return toStream(iterable, true);
}
private static <T> Stream<T> toStream(final Iterable<T> iterable, final boolean isParallel) {
return StreamSupport.stream(iterable.spliterator(), isParallel);
}
}
I think it's perfectly readable because you don't have to think about spliterators and booleans (isParallel).
if you just want diff the specified file, you can :
git diff master 766eceb -- connections/ > 000-mysql-connector.patch
Well, to give some perspective, let me compare node.js with apache.
Apache is a multi-threaded HTTP server, for each and every request that the server receives, it creates a separate thread which handles that request.
Node.js on the other hand is event driven, handling all requests asynchronously from single thread.
When A and B are received on apache, two threads are created which handle requests. Each handling the query separately, each waiting for the query results before serving the page. The page is only served until the query is finished. The query fetch is blocking because the server cannot execute the rest of thread until it receives the result.
In node, c.query is handled asynchronously, which means while c.query fetches the results for A, it jumps to handle c.query for B, and when the results arrive for A arrive it sends back the results to callback which sends the response. Node.js knows to execute callback when fetch finishes.
In my opinion, because it's a single thread model, there is no way to switch from one request to another.
Actually the node server does exactly that for you all the time. To make switches, (the asynchronous behavior) most functions that you would use will have callbacks.
The SQL query is taken from mysql library. It implements callback style as well as event emitter to queue SQL requests. It does not execute them asynchronously, that is done by the internal libuv threads that provide the abstraction of non-blocking I/O. The following steps happen for making a query :
The incoming requests to http server are handled in the similar fashion. The internal thread architecture is something like this:
The C++ threads are the libuv ones which do the asynchronous I/O (disk or network). The main event loop continues to execute after the dispatching the request to thread pool. It can accept more requests as it does not wait or sleep. SQL queries/HTTP requests/file system reads all happen this way.
Yes. First, construct a File
representing the image path:
File file = new File(a);
If you're starting from a relative path:
file = new File(file.getAbsolutePath());
Then, get the parent:
String dir = file.getParent();
Or, if you want the directory as a File
object,
File dirAsFile = file.getParentFile();
Following command work for me:
sudo npm i -g node-pre-gyp
fprintf
This is related with streams where as printf
is a statement similar to fprintf
but not related to streams, that is fprintf
is file related
The accepted answer works like a charm unless you're applying it to a vector. Since a vector is non-recursive, you'll get an error like this
$ operator is invalid for atomic vectors
You can use [
in that case
foo[order(foo["V1"]),]
Use mysql-connector-python. I prefer to install it with pip from PyPI:
pip install --allow-external mysql-connector-python mysql-connector-python
Have a look at its documentation and examples.
If you are going to use pooling make sure your database has enough connections available as the default settings may not be enough.
I'm not sure what your goal is, but might it be better to use addClass instead? I mean an objects ID in my opinion should be static and specific to that object. If you are just trying to change it from showing on the page or something like that I would put those details in a class and then add it to the object rather then trying to change it's ID. Again, I'm saying that without understand your underlining goal.
function saveProfile(){
$firstname = $this->input->post('firstname');
$lastname = $this->input->post('lastname');
$post_data = array('firstname'=> $firstname,'lastname'=>$lastname);
$this->db->insert('posts',$post_data);
return $this->db->insert_id();
}
Enhancement on the accepted answer by @afonsoduarte.
in case you are using bootstrap
Providing width:100%
on the style.
This is helpful if you are using bootstrap and want the image to stretch all the available width.
Specifying the height
property is optional, You can remove/keep it as you need
.cover {
object-fit: cover;
width: 100%;
/*height: 300px; optional, you can remove it, but in my case it was good */
}
By the way, there is NO need to provide the height
and width
attributes on the image
element because they will be overridden by the style.
so it is enough to write something like this.
<img class="cover" src="url to img ..." />
new_data <- data %>% filter_all(any_vars(is.na(.)))
This should create a new data frame (new_data
) with only the missing values in it.
Works best to keep a track of values that you might later drop because they had some columns with missing observations (NA).
<RelativeLayout android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:layout_marginTop="30dp">
<com.facebook.login.widget.LoginButton
xmlns:facebook="http://schemas.android.com/apk/res-auto"
android:id="@+id/login_button"
android:layout_width="300dp"
android:layout_height="100dp"
android:paddingTop="15dp"
android:paddingBottom="15dp" />
<LinearLayout
android:id="@+id/llfbSignup"
android:layout_width="300dp"
android:layout_height="50dp"
android:background="@drawable/facebook"
android:layout_gravity="center_horizontal"
android:orientation="horizontal">
<ImageView
android:layout_width="30dp"
android:layout_height="30dp"
android:src="@drawable/facbk"
android:layout_gravity="center_vertical"
android:layout_marginLeft="10dp" />
<View
android:layout_width="1dp"
android:layout_height="match_parent"
android:background="@color/fullGray"
android:layout_marginLeft="10dp"/>
<com.yadav.bookedup.fonts.GoutamBold
android:layout_width="240dp"
android:layout_height="50dp"
android:text="Sign Up via Facebook"
android:gravity="center"
android:textColor="@color/white"
android:textSize="18dp"
android:layout_gravity="center_vertical"
android:layout_marginLeft="10dp"/>
</LinearLayout>
</RelativeLayout>
Backticks are to be used for table and column identifiers, but are only necessary when the identifier is a MySQL reserved keyword, or when the identifier contains whitespace characters or characters beyond a limited set (see below) It is often recommended to avoid using reserved keywords as column or table identifiers when possible, avoiding the quoting issue.
Single quotes should be used for string values like in the VALUES()
list. Double quotes are supported by MySQL for string values as well, but single quotes are more widely accepted by other RDBMS, so it is a good habit to use single quotes instead of double.
MySQL also expects DATE
and DATETIME
literal values to be single-quoted as strings like '2001-01-01 00:00:00'
. Consult the Date and Time Literals documentation for more details, in particular alternatives to using the hyphen -
as a segment delimiter in date strings.
So using your example, I would double-quote the PHP string and use single quotes on the values 'val1', 'val2'
. NULL
is a MySQL keyword, and a special (non)-value, and is therefore unquoted.
None of these table or column identifiers are reserved words or make use of characters requiring quoting, but I've quoted them anyway with backticks (more on this later...).
Functions native to the RDBMS (for example, NOW()
in MySQL) should not be quoted, although their arguments are subject to the same string or identifier quoting rules already mentioned.
Backtick (`) table & column ------------------------------------------------------+ ? ? ? ? ? ? ? ? ? ? ? ? $query = "INSERT INTO `table` (`id`, `col1`, `col2`, `date`, `updated`) VALUES (NULL, 'val1', 'val2', '2001-01-01', NOW())"; ???? ? ? ? ? ? ? ????? Unquoted keyword --------+ ¦ ¦ ¦ ¦ ¦ ¦ ¦¦¦¦¦ Single-quoted (') strings ------------------------+ ¦ ¦ ¦¦¦¦¦ Single-quoted (') DATE --------------------------------------+ ¦¦¦¦¦ Unquoted function ---------------------------------------------+
The quoting patterns for variables do not change, although if you intend to interpolate the variables directly in a string, it must be double-quoted in PHP. Just make sure that you have properly escaped the variables for use in SQL. (It is recommended to use an API supporting prepared statements instead, as protection against SQL injection).
// Same thing with some variable replacements // Here, a variable table name $table is backtick-quoted, and variables // in the VALUES list are single-quoted $query = "INSERT INTO `$table` (`id`, `col1`, `col2`, `date`) VALUES (NULL, '$val1', '$val2', '$date')";
When working with prepared statements, consult the documentation to determine whether or not the statement's placeholders must be quoted. The most popular APIs available in PHP, PDO and MySQLi, expect unquoted placeholders, as do most prepared statement APIs in other languages:
// PDO example with named parameters, unquoted
$query = "INSERT INTO `table` (`id`, `col1`, `col2`, `date`) VALUES (:id, :col1, :col2, :date)";
// MySQLi example with ? parameters, unquoted
$query = "INSERT INTO `table` (`id`, `col1`, `col2`, `date`) VALUES (?, ?, ?, ?)";
According to MySQL documentation, you do not need to quote (backtick) identifiers using the following character set:
ASCII:
[0-9,a-z,A-Z$_]
(basic Latin letters, digits 0-9, dollar, underscore)
You can use characters beyond that set as table or column identifiers, including whitespace for example, but then you must quote (backtick) them.
Also, although numbers are valid characters for identifiers, identifiers cannot consist solely of numbers. If they do they must be wrapped in backticks.
Use the pip application. On windows you find it in Python3/Scripts/pip.exe
and On Ubuntu you can install with apt-get install python3-pip
.
and so, use the command line:
pip3 install --upgrade pip
pip3 install opencv-python
On Windows use only pip.exe instead pip3
Super easy answer for those that only have this on one webpage. Edit your actionlink and a + "/" on the end of it.
@Html.ActionLink("Edit", "Edit", new { id = item.name + "/" }) |
To give the simplest answer I can think of:
Suppose we have a problem that takes a certain number of inputs, and has various potential solutions, which may or may not solve the problem for given inputs. A logic puzzle in a puzzle magazine would be a good example: the inputs are the conditions ("George doesn't live in the blue or green house"), and the potential solution is a list of statements ("George lives in the yellow house, grows peas, and owns the dog"). A famous example is the Traveling Salesman problem: given a list of cities, and the times to get from any city to any other, and a time limit, a potential solution would be a list of cities in the order the salesman visits them, and it would work if the sum of the travel times was less than the time limit.
Such a problem is in NP if we can efficiently check a potential solution to see if it works. For example, given a list of cities for the salesman to visit in order, we can add up the times for each trip between cities, and easily see if it's under the time limit. A problem is in P if we can efficiently find a solution if one exists.
(Efficiently, here, has a precise mathematical meaning. Practically, it means that large problems aren't unreasonably difficult to solve. When searching for a possible solution, an inefficient way would be to list all possible potential solutions, or something close to that, while an efficient way would require searching a much more limited set.)
Therefore, the P=NP problem can be expressed this way: If you can verify a solution for a problem of the sort described above efficiently, can you find a solution (or prove there is none) efficiently? The obvious answer is "Why should you be able to?", and that's pretty much where the matter stands today. Nobody has been able to prove it one way or another, and that bothers a lot of mathematicians and computer scientists. That's why anybody who can prove the solution is up for a million dollars from the Claypool Foundation.
We generally assume that P does not equal NP, that there is no general way to find solutions. If it turned out that P=NP, a lot of things would change. For example, cryptography would become impossible, and with it any sort of privacy or verifiability on the Internet. After all, we can efficiently take the encrypted text and the key and produce the original text, so if P=NP we could efficiently find the key without knowing it beforehand. Password cracking would become trivial. On the other hand, there's whole classes of planning problems and resource allocation problems that we could solve effectively.
You may have heard the description NP-complete. An NP-complete problem is one that is NP (of course), and has this interesting property: if it is in P, every NP problem is, and so P=NP. If you could find a way to efficiently solve the Traveling Salesman problem, or logic puzzles from puzzle magazines, you could efficiently solve anything in NP. An NP-complete problem is, in a way, the hardest sort of NP problem.
So, if you can find an efficient general solution technique for any NP-complete problem, or prove that no such exists, fame and fortune are yours.
You need to use parentheses: myList.insert([1, 2, 3])
. When you leave out the parentheses, python thinks you are trying to access myList.insert
at position 1, 2, 3
, because that's what brackets are used for when they are right next to a variable.
No, not directly in the std::list
template itself. You can however use std::find
algorithm like that:
std::list<int> my_list;
//...
int some_value = 12;
std::list<int>::iterator iter = std::find (my_list.begin(), my_list.end(), some_value);
// now variable iter either represents valid iterator pointing to the found element,
// or it will be equal to my_list.end()
To quote Wikipedia:
ACID (atomicity, consistency, isolation, durability) is a set of properties that guarantee database transactions are processed reliably.
A DBMS that supports transactions will strive to support all of these properties - any commercial DBMS (as well as several open-source DBMSs) provide full ACID 'support' - although it's often possible (for example, with varying isolation levels in MSSQL) to lessen the ACIDness - thus losing the guarantee of fully transactional behaviour.
Make sure you pass a proxy attribute in your command forexample - pip install --proxy=http://proxyhost:proxyport pixiedust
Use a proxy port which has direct connection (with / without password). Speak with your corporate IT administrator. Quick way is find out network settings used in eclipse which will have direct connection.
You will encouter this issue often if you work behind a corporate firewall. You will have to check your internet explorer - InternetOptions -LAN Connection - Settings
Uncheck - Use automatic configuration script Check - Use a proxy server for your LAN. Ensure you have given the right address and port.
Click Ok Come back to anaconda terminal and you can try install commands
Here's an example using apache commons-fileupload:
// apache commons-fileupload to handle file upload
DiskFileItemFactory factory = new DiskFileItemFactory();
factory.setRepository(new File(DataSources.TORRENTS_DIR()));
ServletFileUpload fileUpload = new ServletFileUpload(factory);
List<FileItem> items = fileUpload.parseRequest(req.raw());
FileItem item = items.stream()
.filter(e ->
"the_upload_name".equals(e.getFieldName()))
.findFirst().get();
String fileName = item.getName();
item.write(new File(dir, fileName));
log.info(fileName);
Pay close attention to the first part of the error: "variable is not declared"
Ignore the second part: "it may be inaccessible due to its protection level". It's a red herring.
Some questions... (the answers might be in that image you posted, but I can't seem to make it larger and my eyes don't read that small of print... Any chance you can post the code in a way these older eyes can read it? Makes it hard to know the total picture. In particular I am suspicious of your Page directives.)
We know that 1stReasonTypes is a listbox, but for some reason it seems like we don't know WHICH listbox. This is why I want to see your page directives.
But also, how are you calling the private method FormRefresh()? It's not an event handler, which makes me wonder if you are trying to reference a listbox in a form that is not handled properly in this code behind.
You may need to find the control 1stReasonTypes. Try maybe putting your listbox inside something like
<div id="MyFormDiv" runat="server">.....</div>
then in FormRefresh(), do a...
Dim 1stReasonTypesNew As listbox = MyFormDiv.FindControl("1stReasonTypes")
Or use an existing control, object, or page instead of a div. More info on FindControl: http://msdn.microsoft.com/en-us/library/486wc64h(v=vs.110).aspx
But no matter how you slice it, there is something funky going here such that 1stReasonTypes doesn't know which exact listbox it's supposed to be.
You will have to use something like below
#menu ul{_x000D_
list-style: none;_x000D_
}_x000D_
#menu li{_x000D_
display: inline;_x000D_
}_x000D_
_x000D_
<div id="menu">_x000D_
<ul>_x000D_
<li>First menu item</li>_x000D_
<li>Second menu item</li>_x000D_
<li>Third menu item</li>_x000D_
</ul>_x000D_
</div>
_x000D_
The answer is not to add a newline after writing your string. That may solve a different problem. What you are asking is how to add a newline before you start appending your string. If you want to add a newline, but only if one does not already exist, you need to find out first, by reading the file.
For example,
with open('hst.txt') as fobj:
text = fobj.read()
name = 'Bob'
with open('hst.txt', 'a') as fobj:
if not text.endswith('\n'):
fobj.write('\n')
fobj.write(name)
You might want to add the newline after name, or you may not, but in any case, it isn't the answer to your question.
Below is answering the original first question:
Should I use
dict
orOrderedDict
in Python 3.6?
I think this sentence from the documentation is actually enough to answer your question
The order-preserving aspect of this new implementation is considered an implementation detail and should not be relied upon
dict
is not explicitly meant to be an ordered collection, so if you want to stay consistent and not rely on a side effect of the new implementation you should stick with OrderedDict
.
Make your code future proof :)
There's a debate about that here.
EDIT: Python 3.7 will keep this as a feature see
Button won't submit form on its own.It is a simple button which is used to perform some operation by using javascript whereas Submit is a kind of button which by default submit the form whenever user clicks on submit button.
To test if the string paragraph
contains the string word
(thanks @QuarterMeister)
culture.CompareInfo.IndexOf(paragraph, word, CompareOptions.IgnoreCase) >= 0
Where culture
is the instance of CultureInfo
describing the language that the text is written in.
This solution is transparent about the definition of case-insensitivity, which is language dependent. For example, the English language uses the characters I
and i
for the upper and lower case versions of the ninth letter, whereas the Turkish language uses these characters for the eleventh and twelfth letters of its 29 letter-long alphabet. The Turkish upper case version of 'i' is the unfamiliar character 'I'.
Thus the strings tin
and TIN
are the same word in English, but different words in Turkish. As I understand, one means 'spirit' and the other is an onomatopoeia word. (Turks, please correct me if I'm wrong, or suggest a better example)
To summarise, you can only answer the question 'are these two strings the same but in different cases' if you know what language the text is in. If you don't know, you'll have to take a punt. Given English's hegemony in software, you should probably resort to CultureInfo.InvariantCulture
, because it'll be wrong in familiar ways.
txt_name.value
txt_name.onkeyup = e=> alert(txt_name.value);
_x000D_
<input type="text" id="txt_name" />
_x000D_
you can simply use onBackPressed();
or if you are using fragment you can use getActivity().onBackPressed()
NSString* expectedString = nil;
if([givenString hasPrefix:@"*"])
{
expectedString = [givenString substringFromIndex:1];
}
Here is exp.
$date_search_strtotime = strtotime(date("Y-m-d"));
echo 'Now strtotime date : '.$date_search_strtotime;
echo '<br>';
echo 'Now date from strtotime : '.date('Y-m-d',$date_search_strtotime);
In Swift 3.01 using WKWebView:
let localURL = URL.init(fileURLWithPath: Bundle.main.path(forResource: "index", ofType: "html", inDirectory: "CWP")!)
myWebView.load(NSURLRequest.init(url: localURL) as URLRequest)
This adjusts for some of the finer syntax changes in 3.01 and keeps the directory structure in place so you can embed related HTML files.
C++ doesn't allow non-constant values for the size of an array. That's just the way it was designed.
C99 allows the size of an array to be a variable, but I'm not sure it is allowed for two dimensions. Some C++ compilers (gcc) will allow this as an extension, but you may need to turn on a compiler option to allow it.
And I almost missed it - you need to declare a variable name, not just the array dimensions.
Put that file in assets.
For project created in Android Studio project you need to create assets folder under the main folder.
Read that file as:
public String loadJSONFromAsset(Context context) {
String json = null;
try {
InputStream is = context.getAssets().open("file_name.json");
int size = is.available();
byte[] buffer = new byte[size];
is.read(buffer);
is.close();
json = new String(buffer, "UTF-8");
} catch (IOException ex) {
ex.printStackTrace();
return null;
}
return json;
}
and then you can simply read this string
return by this function as
JSONObject obj = new JSONObject(json_return_by_the_function);
For further details regarding JSON see http://www.vogella.com/articles/AndroidJSON/article.html
Hope you will get what you want.
@foreach (var m in Model)
{
<img src="~/Images/@m.Url" style="overflow: hidden; position: relative; width:200px; height:200px;" />
}
To set the PATH
variable, within the Makefile only, use something like:
PATH := $(PATH):/my/dir
test:
@echo my new PATH = $(PATH)
If your host time is correct, you can set the following .vmx configuration file option to enable periodic synchronization:
tools.syncTime = true
By default, this synchronizes the time every minute. To change the periodic rate, set the following option to the desired synch time in seconds:
tools.syncTime.period = 60
For this to work you need to have VMWare tools installed in your guest OS.
See http://www.vmware.com/pdf/vmware_timekeeping.pdf for more information
Add bottom:100%
to your #menu:hover ul li:hover ul
rule
#menu:hover ul li:hover ul {
position: absolute;
margin-top: 1px;
font: 10px;
bottom: 100%; /* added this attribute */
}
Or better yet to prevent the submenus from having the same effect, just add this rule
#menu>ul>li:hover>ul {
bottom:100%;
}
source: http://jsfiddle.net/W5FWW/4/
And to get back the border you can add the following attribute
#menu>ul>li:hover>ul {
bottom:100%;
border-bottom: 1px solid transparent
}
I find out the way how to set the image path just remove the "/"
before the destination folder as "images/66.jpg"
not "/images/66.jpg"
And its working fine for me.
EDIT: In summary, back in 2010 when this question was asked the most common way to solve this problem was to save a reference to the context where the setTimeout
function call is made, because setTimeout
executes the function with this
pointing to the global object:
var that = this;
if (this.options.destroyOnHide) {
setTimeout(function(){ that.tip.destroy() }, 1000);
}
In the ES5 spec, just released a year before that time, it introduced the bind
method, this wasn't suggested in the original answer because it wasn't yet widely supported and you needed polyfills to use it but now it's everywhere:
if (this.options.destroyOnHide) {
setTimeout(function(){ this.tip.destroy() }.bind(this), 1000);
}
The bind
function creates a new function with the this
value pre-filled.
Now in modern JS, this is exactly the problem arrow functions solve in ES6:
if (this.options.destroyOnHide) {
setTimeout(() => { this.tip.destroy() }, 1000);
}
Arrow functions do not have a this
value of its own, when you access it, you are accessing the this
value of the enclosing lexical scope.
HTML5 also standardized timers back in 2011, and you can pass now arguments to the callback function:
if (this.options.destroyOnHide) {
setTimeout(function(that){ that.tip.destroy() }, 1000, this);
}
See also:
Numbers inherit from the Number
constructor which doesn't have the .toLowerCase
method. You can look it up as a matter of fact:
"toLowerCase" in Number.prototype; // false
Instead of "w"
use "a"
(append) mode with open
function:
with open("games.txt", "a") as text_file:
I think you are using the latest version of TypeScript. Please see the section "Strict Class Initialization" in the link
.
There are two ways to fix this:
A. If you are using VSCode you need to change the TS version that the editor use.
B. Just initialize the array when you declare it inside the constructor,
makes: any[] = [];
constructor(private makeService: MakeService) {
// Initialization inside the constructor
this.makes = [];
}
I am trying to write a sample program to do AES encryption using Openssl.
This answer is kind of popular, so I'm going to offer something more up-to-date since OpenSSL added some modes of operation that will probably help you.
First, don't use AES_encrypt
and AES_decrypt
. They are low level and harder to use. Additionally, it's a software-only routine, and it will never use hardware acceleration, like AES-NI. Finally, its subject to endianess issues on some obscure platforms.
Instead, use the EVP_*
interfaces. The EVP_*
functions use hardware acceleration, like AES-NI, if available. And it does not suffer endianess issues on obscure platforms.
Second, you can use a mode like CBC, but the ciphertext will lack integrity and authenticity assurances. So you usually want a mode like EAX, CCM, or GCM. (Or you manually have to apply a HMAC after the encryption under a separate key.)
Third, OpenSSL has a wiki page that will probably interest you: EVP Authenticated Encryption and Decryption. It uses GCM mode.
Finally, here's the program to encrypt using AES/GCM. The OpenSSL wiki example is based on it.
#include <openssl/evp.h>
#include <openssl/aes.h>
#include <openssl/err.h>
#include <string.h>
int main(int arc, char *argv[])
{
OpenSSL_add_all_algorithms();
ERR_load_crypto_strings();
/* Set up the key and iv. Do I need to say to not hard code these in a real application? :-) */
/* A 256 bit key */
static const unsigned char key[] = "01234567890123456789012345678901";
/* A 128 bit IV */
static const unsigned char iv[] = "0123456789012345";
/* Message to be encrypted */
unsigned char plaintext[] = "The quick brown fox jumps over the lazy dog";
/* Some additional data to be authenticated */
static const unsigned char aad[] = "Some AAD data";
/* Buffer for ciphertext. Ensure the buffer is long enough for the
* ciphertext which may be longer than the plaintext, dependant on the
* algorithm and mode
*/
unsigned char ciphertext[128];
/* Buffer for the decrypted text */
unsigned char decryptedtext[128];
/* Buffer for the tag */
unsigned char tag[16];
int decryptedtext_len = 0, ciphertext_len = 0;
/* Encrypt the plaintext */
ciphertext_len = encrypt(plaintext, strlen(plaintext), aad, strlen(aad), key, iv, ciphertext, tag);
/* Do something useful with the ciphertext here */
printf("Ciphertext is:\n");
BIO_dump_fp(stdout, ciphertext, ciphertext_len);
printf("Tag is:\n");
BIO_dump_fp(stdout, tag, 14);
/* Mess with stuff */
/* ciphertext[0] ^= 1; */
/* tag[0] ^= 1; */
/* Decrypt the ciphertext */
decryptedtext_len = decrypt(ciphertext, ciphertext_len, aad, strlen(aad), tag, key, iv, decryptedtext);
if(decryptedtext_len < 0)
{
/* Verify error */
printf("Decrypted text failed to verify\n");
}
else
{
/* Add a NULL terminator. We are expecting printable text */
decryptedtext[decryptedtext_len] = '\0';
/* Show the decrypted text */
printf("Decrypted text is:\n");
printf("%s\n", decryptedtext);
}
/* Remove error strings */
ERR_free_strings();
return 0;
}
void handleErrors(void)
{
unsigned long errCode;
printf("An error occurred\n");
while(errCode = ERR_get_error())
{
char *err = ERR_error_string(errCode, NULL);
printf("%s\n", err);
}
abort();
}
int encrypt(unsigned char *plaintext, int plaintext_len, unsigned char *aad,
int aad_len, unsigned char *key, unsigned char *iv,
unsigned char *ciphertext, unsigned char *tag)
{
EVP_CIPHER_CTX *ctx = NULL;
int len = 0, ciphertext_len = 0;
/* Create and initialise the context */
if(!(ctx = EVP_CIPHER_CTX_new())) handleErrors();
/* Initialise the encryption operation. */
if(1 != EVP_EncryptInit_ex(ctx, EVP_aes_256_gcm(), NULL, NULL, NULL))
handleErrors();
/* Set IV length if default 12 bytes (96 bits) is not appropriate */
if(1 != EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_GCM_SET_IVLEN, 16, NULL))
handleErrors();
/* Initialise key and IV */
if(1 != EVP_EncryptInit_ex(ctx, NULL, NULL, key, iv)) handleErrors();
/* Provide any AAD data. This can be called zero or more times as
* required
*/
if(aad && aad_len > 0)
{
if(1 != EVP_EncryptUpdate(ctx, NULL, &len, aad, aad_len))
handleErrors();
}
/* Provide the message to be encrypted, and obtain the encrypted output.
* EVP_EncryptUpdate can be called multiple times if necessary
*/
if(plaintext)
{
if(1 != EVP_EncryptUpdate(ctx, ciphertext, &len, plaintext, plaintext_len))
handleErrors();
ciphertext_len = len;
}
/* Finalise the encryption. Normally ciphertext bytes may be written at
* this stage, but this does not occur in GCM mode
*/
if(1 != EVP_EncryptFinal_ex(ctx, ciphertext + len, &len)) handleErrors();
ciphertext_len += len;
/* Get the tag */
if(1 != EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_GCM_GET_TAG, 16, tag))
handleErrors();
/* Clean up */
EVP_CIPHER_CTX_free(ctx);
return ciphertext_len;
}
int decrypt(unsigned char *ciphertext, int ciphertext_len, unsigned char *aad,
int aad_len, unsigned char *tag, unsigned char *key, unsigned char *iv,
unsigned char *plaintext)
{
EVP_CIPHER_CTX *ctx = NULL;
int len = 0, plaintext_len = 0, ret;
/* Create and initialise the context */
if(!(ctx = EVP_CIPHER_CTX_new())) handleErrors();
/* Initialise the decryption operation. */
if(!EVP_DecryptInit_ex(ctx, EVP_aes_256_gcm(), NULL, NULL, NULL))
handleErrors();
/* Set IV length. Not necessary if this is 12 bytes (96 bits) */
if(!EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_GCM_SET_IVLEN, 16, NULL))
handleErrors();
/* Initialise key and IV */
if(!EVP_DecryptInit_ex(ctx, NULL, NULL, key, iv)) handleErrors();
/* Provide any AAD data. This can be called zero or more times as
* required
*/
if(aad && aad_len > 0)
{
if(!EVP_DecryptUpdate(ctx, NULL, &len, aad, aad_len))
handleErrors();
}
/* Provide the message to be decrypted, and obtain the plaintext output.
* EVP_DecryptUpdate can be called multiple times if necessary
*/
if(ciphertext)
{
if(!EVP_DecryptUpdate(ctx, plaintext, &len, ciphertext, ciphertext_len))
handleErrors();
plaintext_len = len;
}
/* Set expected tag value. Works in OpenSSL 1.0.1d and later */
if(!EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_GCM_SET_TAG, 16, tag))
handleErrors();
/* Finalise the decryption. A positive return value indicates success,
* anything else is a failure - the plaintext is not trustworthy.
*/
ret = EVP_DecryptFinal_ex(ctx, plaintext + len, &len);
/* Clean up */
EVP_CIPHER_CTX_free(ctx);
if(ret > 0)
{
/* Success */
plaintext_len += len;
return plaintext_len;
}
else
{
/* Verify failed */
return -1;
}
}
They most often come from forgetting to include the header file that contains the function declaration, for example, this program will give an 'undeclared identifier' error:
int main() {
std::cout << "Hello world!" << std::endl;
return 0;
}
To fix it, we must include the header:
#include <iostream>
int main() {
std::cout << "Hello world!" << std::endl;
return 0;
}
If you wrote the header and included it correctly, the header may contain the wrong include guard.
To read more, see http://msdn.microsoft.com/en-us/library/aa229215(v=vs.60).aspx.
Another common source of beginner's error occur when you misspelled a variable:
int main() {
int aComplicatedName;
AComplicatedName = 1; /* mind the uppercase A */
return 0;
}
For example, this code would give an error, because you need to use std::string
:
#include <string>
int main() {
std::string s1 = "Hello"; // Correct.
string s2 = "world"; // WRONG - would give error.
}
void f() { g(); }
void g() { }
g
has not been declared before its first use. To fix it, either move the definition of g
before f
:
void g() { }
void f() { g(); }
Or add a declaration of g
before f
:
void g(); // declaration
void f() { g(); }
void g() { } // definition
This is Visual Studio-specific. In VS, you need to add #include "stdafx.h"
before any code. Code before it is ignored by the compiler, so if you have this:
#include <iostream>
#include "stdafx.h"
The #include <iostream>
would be ignored. You need to move it below:
#include "stdafx.h"
#include <iostream>
Feel free to edit this answer.
If you have access to a database, you can create and use a sequence in the file name.
select mySequence.nextval from dual;
It will be guaranteed to be unique and shouldn't get too large (unless you are pumping out a ton of files).
I just experienced this issue while using the Windows Subsystem for Linux (WSL2), so I will also share this solution.
My objective was to render the output from webpack both at wsl:3000
and localhost:3000
, thereby creating an alternate local endpoint.
As you might expect, this initially caused the "Invalid Host header" error to arise. Nothing seemed to help until I added the devServer config option shown below.
module.exports = {
//...
devServer: {
proxy: [
{
context: ['http://wsl:3000'],
target: 'http://localhost:3000',
},
],
},
}
This fixed the "bug" without introducing any security risks.
Reference: webpack DevServer docs
The source release is the raw, uncompiled code. You could read it yourself. To use it, it must be compiled on your machine. Binary means the code was compiled into a machine language format that the computer can read, then execute. No human can understand the binary file unless its been dissected, or opened with some program that let's you read the executable as code.
The main reason for primary and foreign keys is to enforce data consistency.
A primary key enforces the consistency of uniqueness of values over one or more columns. If an ID column has a primary key then it is impossible to have two rows with the same ID value. Without that primary key, many rows could have the same ID value and you wouldn't be able to distinguish between them based on the ID value alone.
A foreign key enforces the consistency of data that points elsewhere. It ensures that the data which is pointed to actually exists. In a typical parent-child relationship, a foreign key ensures that every child always points at a parent and that the parent actually exists. Without the foreign key you could have "orphaned" children that point at a parent that doesn't exist.
Margin is usually used to create a space between the element itself and its surround.
for example I use it when I'm building a navbar to make it sticks to the edges of the screen and for no white gap.
I usually use when I've an element inside a border, <div>
or something similar, and I want to decrease its size but at the time I want to keep the distance or the margin between the other elements around it.
So briefly, it's situational; it depends on what you are trying to do.
Here's the GNU version of printf
... you can see it passing in stdout
to vfprintf
:
__printf (const char *format, ...)
{
va_list arg;
int done;
va_start (arg, format);
done = vfprintf (stdout, format, arg);
va_end (arg);
return done;
}
Here's a link to vfprintf
... all the formatting 'magic' happens here.
The only thing that's truly 'different' about these functions is that they use varargs to get at arguments in a variable length argument list. Other than that, they're just traditional C. (This is in contrast to Pascal's printf
equivalent, which is implemented with specific support in the compiler... at least it was back in the day.)
If you dont want to query for it just create an entity, and then delete it.
Customer customer = new Customer() { Id = 1 } ;
context.AttachTo("Customers", customer);
context.DeleteObject(customer);
context.Savechanges();
You can create the required headers in a filter too.
@WebFilter(urlPatterns="/rest/*")
public class AllowAccessFilter implements Filter {
@Override
public void doFilter(ServletRequest sRequest, ServletResponse sResponse, FilterChain chain) throws IOException, ServletException {
System.out.println("in AllowAccessFilter.doFilter");
HttpServletRequest request = (HttpServletRequest)sRequest;
HttpServletResponse response = (HttpServletResponse)sResponse;
response.setHeader("Access-Control-Allow-Origin", "*");
response.setHeader("Access-Control-Allow-Methods", "GET, POST, PUT");
response.setHeader("Access-Control-Allow-Headers", "Content-Type");
chain.doFilter(request, response);
}
...
}
Ideone supports Python 2.6 and Python 3
You can use the 'describe pod' syntax
For OpenShift use:
oc describe pod <pod-id>
For vanilla Kubernetes:
kubectl describe pod <pod-id>
Examine the events of the output. In my case it shows Back-off pulling image coredns/coredns:latest
In this case the image coredns/coredns:latest can not be pulled from the Internet.
Events:
FirstSeen LastSeen Count From SubObjectPath Type Reason Message
--------- -------- ----- ---- ------------- -------- ------ -------
5m 5m 1 {default-scheduler } Normal Scheduled Successfully assigned coredns-4224169331-9nhxj to 192.168.122.190
5m 1m 4 {kubelet 192.168.122.190} spec.containers{coredns} Normal Pulling pulling image "coredns/coredns:latest"
4m 26s 4 {kubelet 192.168.122.190} spec.containers{coredns} Warning Failed Failed to pull image "coredns/coredns:latest": Network timed out while trying to connect to https://index.docker.io/v1/repositories/coredns/coredns/images. You may want to check your internet connection or if you are behind a proxy.
4m 26s 4 {kubelet 192.168.122.190} Warning FailedSync Error syncing pod, skipping: failed to "StartContainer" for "coredns" with ErrImagePull: "Network timed out while trying to connect to https://index.docker.io/v1/repositories/coredns/coredns/images. You may want to check your Internet connection or if you are behind a proxy."
4m 2s 7 {kubelet 192.168.122.190} spec.containers{coredns} Normal BackOff Back-off pulling image "coredns/coredns:latest"
4m 2s 7 {kubelet 192.168.122.190} Warning FailedSync Error syncing pod, skipping: failed to "StartContainer" for "coredns" with ImagePullBackOff: "Back-off pulling image \"coredns/coredns:latest\""
Additional debuging steps
$xml = $( $.parseXML( xml ) );
$xml.find("<<your_xml_tag_name>>").each(function(index,elem){
// elem = found XML element
});
The simplest way I have found is to just set the container name in the docker-compose.yml
See container_name documentation. It is applicable to docker-compose v1+. It works for container to container, not from the host machine to container.
services:
dns:
image: phensley/docker-dns
container_name: affy
Now you should be able to access affy
from other containers using the container name. I had to do this for multiple redis servers in a development environment.
NOTE The solution works so long as you don't need to scale. Such as consistant individual developer environments.
Java is a compiled programming language, but rather than compile straight to executable machine code, it compiles to an intermediate binary form called JVM byte code. The byte code is then compiled and/or interpreted to run the program.
These answers are right, but old and works for Depoloyement Package Model
.
What I Actually needed is to change the server name, database name of a connection manager and i found this very helpful:
https://www.youtube.com/watch?v=_yLAwTHH_GA
Better for people using SQL Server 2012-2014-2016 ... with Deployment Project Model
I think this is a simple way:
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int number = input.nextInt();
long a = 0;
long b = 1;
for(int i = 1; i<number;i++){
long c = a +b;
a=b;
b=c;
System.out.println(c);
}
}
}
For those arriving here after updating phpunit to version 6 or greater released on 2017-02-03 (e.g. with composer), you may be getting this error because phpunit code is now namespaced (check changelog).
You will need to refactor things like \PHPUnit_Framework_TestCase
to \PHPUnit\Framework\TestCase
After trying to solve this issue for some time, I managed to come with a working solution that is also valid:
var event = new MouseEvent('mousedown');
element.dispatchEvent(event);
I've tried to implement this in Jquery as well, using trigger
and mousedown
or only mousedown
but with no success.
Before you run make oldconfig
, you need to copy a kernel configuration file from an older kernel into the root directory of the new kernel.
You can find a copy of the old kernel configuration file on a running system at /boot/config-3.11.0
. Alternatively, kernel source code has configs in linux-3.11.0/arch/x86/configs/{i386_defconfig / x86_64_defconfig}
If your kernel source is located at /usr/src/linux
:
cd /usr/src/linux
cp /boot/config-3.9.6-gentoo .config
make oldconfig
Should it be LIBRARY_PATH
instead of LD_LIBRARY_PATH
.
gcc checks for LIBRARY_PATH
which can be seen with -v
option
When migrating from one machine to another-
Check the gpg version and supported algorithms between the two systems.
gpg --version
Check the presence of keys on both systems.
gpg --list-keys
pub 4096R/62999779 2020-08-04 sub 4096R/0F799997 2020-08-04
gpg --list-secret-keys
sec 4096R/62999779 2020-08-04 ssb 4096R/0F799997 2020-08-04
Check for the presence of same pair of key ids on the other machine. For decrypting, only secret key(sec) and secret sub key(ssb) will be needed.
If the key is not present on the other machine, export the keys in a file from the machine on which keys are present, scp the file and import the keys on the machine where it is missing.
Do not recreate the keys on the new machine with the same passphrase, name, user details as the newly generated key will have new unique id and "No secret key" error will still appear if source is using previously generated public key for encryption. So, export and import, this will ensure that same key id is used for decryption and encryption.
gpg --output gpg_pub_key --export <Email address>
gpg --output gpg_sec_key --export-secret-keys <Email address>
gpg --output gpg_sec_sub_key --export-secret-subkeys <Email address>
gpg --import gpg_pub_key
gpg --import gpg_sec_key
gpg --import gpg_sec_sub_key
This is my solution for my scenario:
<div class="btn-group btn-group-justified">
<a class="btn btn-default" ng-class="{'btn-success': hover.left, 'btn-danger': hover.right}" ng-click="setMatch(-1)" role="button" ng-mouseenter="hover.left = true;" ng-mouseleave="hover.left = false;">
<i class="fa fa-thumbs-o-up fa-5x pull-left" ng-class="{'fa-rotate-90': !hover.left && !hover.right, 'fa-flip-vertical': hover.right}"></i>
{{ song.name }}
</a>
<a class="btn btn-default" ng-class="{'btn-success': hover.right, 'btn-danger': hover.left}" ng-click="setMatch(1)" role="button" ng-mouseenter="hover.right = true;" ng-mouseleave="hover.right = false;">
<i class="fa fa-thumbs-o-up fa-5x pull-right" ng-class="{'fa-rotate-270': !hover.left && !hover.right, 'fa-flip-vertical': hover.left}"></i>
{{ match.name }}
</a>
</div>
default state:
on hover:
Russian.
Month
.MAY
.getDisplayName(
TextStyle.FULL_STANDALONE ,
new Locale( "ru" , "RU" )
)
???
English in the United States.
Month
.MAY
.getDisplayName(
TextStyle.FULL_STANDALONE ,
Locale.US
)
May
See this code run live at IdeOne.com.
Here’s the modern answer. When this question was asked in 2011, Calendar
and GregorianCalendar
were commonly used for dates and times even though they were always poorly designed. That’s 8 years ago now, and those classes are long outdated. Assuming you are not yet on API level 26, my suggestion is to use the ThreeTenABP library, which contains an Android adapted backport of java.time, the modern Java date and time API. java.time is so much nicer to work with.
Depending on your exact needs and situation there are two options:
Month
and its getDisplayName
method.DateTimeFormatter
. Locale desiredLanguage = Locale.ENGLISH;
Month m = Month.MAY;
String monthName = m.getDisplayName(TextStyle.FULL, desiredLanguage);
System.out.println(monthName);
Output from this snippet is:
May
In a few languages it will make a difference whether you use TextStyle.FULL
or TextStyle.FULL_STANDALONE
. You will have to see, maybe check with your users, which of the two fits into your context.
If you’ve got a date with or without time of day, I find a DateTimeFormatter
more practical. For example:
DateTimeFormatter monthFormatter = DateTimeFormatter.ofPattern("MMMM", desiredLanguage);
ZonedDateTime dateTime = ZonedDateTime.of(2019, 5, 31, 23, 49, 51, 0, ZoneId.of("America/Araguaina"));
String monthName = dateTime.format(monthFormatter);
I am showing the use of a ZonedDateTime
, the closest replacement for the old Calendar
class. The above code will work for a LocalDate
, a LocalDateTime
, MonthDay
, OffsetDateTime
and a YearMonth
too.
What if you got a Calendar
from a legacy API not yet upgraded to java.time? Convert to a ZonedDateTime
and proceed as above:
Calendar c = getCalendarFromLegacyApi();
ZonedDateTime dateTime = DateTimeUtils.toZonedDateTime(c);
The rest is the same as before.
java.time works nicely on both older and newer Android devices. It just requires at least Java 6.
org.threeten.bp
with subpackages.java.time
was first described.java.time
to Java 6 and 7 (ThreeTen for JSR-310).Selenium does it for you. Or at least it tries its best. Sometimes it falls short, and you must help it a little bit. The usual solution is Implicit Wait
which solves most of the problems.
If you really know what you're doing, and why you're doing it, you could try to write a generic method which would check whether the page is completely loaded. However, it can't be done for every web and for every situation.
Related question: Selenium WebDriver : Wait for complex page with JavaScript(JS) to load, see my answer there.
Shorter version: You'll never be sure.
The "normal" load is easy - document.readyState
. This one is implemented by Selenium, of course. The problematic thing are asynchronous requests, AJAX, because you can never tell whether it's done for good or not. Most of today's webpages have scripts that run forever and poll the server all the time.
The various things you could do are under the link above. Or, like 95% of other people, use Implicit Wait
implicity and Explicit Wait
+ ExpectedConditions
where needed.
E.g. after a click, some element on the page should become visible and you need to wait for it:
WebDriverWait wait = new WebDriverWait(driver, 10); // you can reuse this one
WebElement elem = driver.findElement(By.id("myInvisibleElement"));
elem.click();
wait.until(ExpectedConditions.visibilityOf(elem));
Now with new JavaScript version (ECMAScript 6 http://es6-features.org/#ClassDefinition) there is a better way to submit requests using nodejs and Promise request (http://www.wintellect.com/devcenter/nstieglitz/5-great-features-in-es6-harmony)
Using library: https://github.com/request/request-promise
npm install --save request
npm install --save request-promise
client:
//Sequential execution for node.js using ES6 ECMAScript
var rp = require('request-promise');
rp({
method: 'POST',
uri: 'http://localhost:3000/',
body: {
val1 : 1,
val2 : 2
},
json: true // Automatically stringifies the body to JSON
}).then(function (parsedBody) {
console.log(parsedBody);
// POST succeeded...
})
.catch(function (err) {
console.log(parsedBody);
// POST failed...
});
server:
var express = require('express')
, bodyParser = require('body-parser');
var app = express();
app.use(bodyParser.json());
app.post('/', function(request, response){
console.log(request.body); // your JSON
var jsonRequest = request.body;
var jsonResponse = {};
jsonResponse.result = jsonRequest.val1 + jsonRequest.val2;
response.send(jsonResponse);
});
app.listen(3000);
It checks whether the page has been called through POST (as opposed to GET, HEAD, etc). When you type a URL in the menu bar, the page is called through GET. However, when you submit a form with method="post" the action page is called with POST.
import java.util.ArrayList;
public class numbers {
private int number1 = 50;
private int number2 = 100;
private List<Integer> list;
public numbers() {
list = new ArrayList<Integer>();
list.add(number1);
list.add(number2);
}
public List<Integer> getList() {
return list;
}
}
And the test class:
import java.util.ArrayList;
public class test {
private numbers number;
//example
public test() {
number = new numbers();
List<Integer> list = number.getList();
//hurray !
}
}
class GlobaleVariableDemo extends Application {
private String myGlobalState;
public String getGlobalState(){
return myGlobalState;
}
public void setGlobalState(String s){
myGlobalState = s;
}
}
class Demo extends Activity {
@Override
public void onCreate(Bundle b){
...
GlobaleVariableDemo appState = ((GlobaleVariableDemo)getApplicationContext());
String state = appState.getGlobalState();
...
}
}
Session.Abandon()
http://msdn.microsoft.com/en-us/library/ms524310.aspx
Here is a little more detail on the HttpSessionState
object:
http://msdn.microsoft.com/en-us/library/system.web.sessionstate.httpsessionstate_members.aspx
In python, A dynamic array is an 'array' from the array module. E.g.
from array import array
x = array('d') #'d' denotes an array of type double
x.append(1.1)
x.append(2.2)
x.pop() # returns 2.2
This datatype is essentially a cross between the built-in 'list' type and the numpy 'ndarray' type. Like an ndarray, elements in arrays are C types, specified at initialization. They are not pointers to python objects; this may help avoid some misuse and semantic errors, and modestly improves performance.
However, this datatype has essentially the same methods as a python list, barring a few string & file conversion methods. It lacks all the extra numerical functionality of an ndarray.
See https://docs.python.org/2/library/array.html for details.
Use this for windows Server 2008 r2 and Windows Server 2012 R2
Click Start, click Run, type dcomcnfg and then click OK to open Component Services.
In the console tree, click to expand Component Services, click to expand Computers, click to expand My Computer, click to expand Distributed Transaction Coordinator and then click Local DTC.
Right click Local DTC and click Properties to display the Local DTC Properties dialog box.
Click the Security tab.
Check mark "Network DTC Access" checkbox.
Finally check mark "Allow Inbound" and "Allow Outbound" checkboxes.
Click Apply, OK.
A message will pop up about restarting the service.
Click OK and That's all.
Reference : https://msdn.microsoft.com/en-us/library/dd327979.aspx
Note: Sometimes the network firewall on the Local Computer or the Server could interrupt your connection so make sure you create rules to "Allow Inbound" and "Allow Outbound" connection for C:\Windows\System32\msdtc.exe
Combine two answers above, I finally make it work. Just be careful that the first single quote for each string is a backtick (`) in file sendmail.mc.
#Change to your mail config directory:
cd /etc/mail
#Make a auth subdirectory
mkdir auth
chmod 700 auth #maybe not, because I cannot apply cmd "cd auth" if I do so.
#Create a file with your auth information to the smtp server
cd auth
touch client-info
#In the file, put the following, matching up to your smtp server:
AuthInfo:your.isp.net "U:root" "I:user" "P:password"
#Generate the Authentication database, make both files readable only by root
makemap hash client-info < client-info
chmod 600 client-info
cd ..
#Add the following lines to sendmail.mc. Make sure you update your smtp server
#The first single quote for each string should be changed to a backtick (`) like this:
define(`SMART_HOST',`your.isp.net')dnl
define(`confAUTH_MECHANISMS', `EXTERNAL GSSAPI DIGEST-MD5 CRAM-MD5 LOGIN PLAIN')dnl
FEATURE(`authinfo',`hash /etc/mail/auth/client-info')dnl
#run
sudo sendmailconfig
I recommend you to use ArgueJS.
You can just type your function this way:
function getData(){
arguments = __({id: String, parameters: [Object], callback: [Function]})
// and now access your arguments by arguments.id,
// arguments.parameters and arguments.callback
}
I considered by your examples that you want your id
parameter to be a string, right?
Now, getData
is requiring a String id
and is accepting the optionals Object parameters
and Function callback
. All the use cases you posted will work as expected.
A solid approach to implement this would be to pass the values from the frontend using a query string. Let's say we want to get page #2 and also limit the output to 25 results.
The query string would look like this: ?page=2&limit=25 // this would be added onto your URL: http:localhost:5000?page=2&limit=25
Let's see the code:
// We would receive the values with req.query.<<valueName>> => e.g. req.query.page
// Since it would be a String we need to convert it to a Number in order to do our
// necessary calculations. Let's do it using the parseInt() method and let's also provide some default values:
const page = parseInt(req.query.page, 10) || 1; // getting the 'page' value
const limit = parseInt(req.query.limit, 10) || 25; // getting the 'limit' value
const startIndex = (page - 1) * limit; // this is how we would calculate the start index aka the SKIP value
const endIndex = page * limit; // this is how we would calculate the end index
// We also need the 'total' and we can get it easily using the Mongoose built-in **countDocuments** method
const total = await <<modelName>>.countDocuments();
// skip() will return a certain number of results after a certain number of documents.
// limit() is used to specify the maximum number of results to be returned.
// Let's assume that both are set (if that's not the case, the default value will be used for)
query = query.skip(startIndex).limit(limit);
// Executing the query
const results = await query;
// Pagination result
// Let's now prepare an object for the frontend
const pagination = {};
// If the endIndex is smaller than the total number of documents, we have a next page
if (endIndex < total) {
pagination.next = {
page: page + 1,
limit
};
}
// If the startIndex is greater than 0, we have a previous page
if (startIndex > 0) {
pagination.prev = {
page: page - 1,
limit
};
}
// Implementing some final touches and making a successful response (Express.js)
const advancedResults = {
success: true,
count: results.length,
pagination,
data: results
}
// That's it. All we have to do now is send the `results` to the frontend.
res.status(200).json(advancedResults);
I would suggest implementing this logic into middleware so you can be able to use it for various routes/ controllers.
I noticed this post was old but it appears top on google and this kind of solution was never offered so I decided to post it anyway.
You can just disable cursor-events and enable them again later via css. It is supported on all major browsers and may prove useful in some situations.
$("#button_id").click(function() {
$("#button_id").css("pointer-events", "none");
//do something
$("#button_id").css("pointer-events", "auto");
}
I am researching module usage in python just now and thought I would answer the question Markus asks in the comments above ("How to import variables when they are embedded in modules?") from two perspectives:
Here is how I would rewrite the main program f1.py to demonstrate variable reuse for Markus:
import f2
myStorage = f2.useMyVars(0) # initialze class and properties
for i in range(0,10):
print "Hello, "
f2.print_world()
myStorage.setMyVar(i)
f2.inc_gMyVar()
print "Display class property myVar:", myStorage.getMyVar()
print "Display global variable gMyVar:", f2.get_gMyVar()
Here is how I would rewrite the reusable module f2.py:
# Module: f2.py
# Example 1: functions to store and retrieve global variables
gMyVar = 0
def print_world():
print "World!"
def get_gMyVar():
return gMyVar # no need for global statement
def inc_gMyVar():
global gMyVar
gMyVar += 1
# Example 2: class methods to store and retrieve properties
class useMyVars(object):
def __init__(self, myVar):
self.myVar = myVar
def getMyVar(self):
return self.myVar
def setMyVar(self, myVar):
self.myVar = myVar
def print_helloWorld(self):
print "Hello, World!"
When f1.py is executed here is what the output would look like:
%run "f1.py"
Hello,
World!
Hello,
World!
Hello,
World!
Hello,
World!
Hello,
World!
Hello,
World!
Hello,
World!
Hello,
World!
Hello,
World!
Hello,
World!
Display class property myVar: 9
Display global variable gMyVar: 10
I think the point to Markus would be:
Just to complete the answer (using the KeyEvent is the way to go) but up arrow is 38 and down arrow is 40 so:
else if (e.getKeyCode()==38)
{
//Up arrow key code
}
else if (e.getKeyCode()==40)
{
//down arrow key code
}
Your code looks correct but sometimes google blocks an IP when you try to send a email from an unusual location. You can try to unblock it by visiting https://accounts.google.com/DisplayUnlockCaptcha from the IP and following the prompts.
Reference: https://support.google.com/accounts/answer/6009563
$ git init
$ git add .
$ git commit -m "First commit"
$ git remote add origin remote repository URL
$ git push origin master
Look at this example, and try to do your own:
import java.io.*;
public class ReadFile {
public static void main(String[] args){
String string = "";
String file = "textFile.txt";
// Reading
try{
InputStream ips = new FileInputStream(file);
InputStreamReader ipsr = new InputStreamReader(ips);
BufferedReader br = new BufferedReader(ipsr);
String line;
while ((line = br.readLine()) != null){
System.out.println(line);
string += line + "\n";
}
br.close();
}
catch (Exception e){
System.out.println(e.toString());
}
// Writing
try {
FileWriter fw = new FileWriter (file);
BufferedWriter bw = new BufferedWriter (fw);
PrintWriter fileOut = new PrintWriter (bw);
fileOut.println (string+"\n test of read and write !!");
fileOut.close();
System.out.println("the file " + file + " is created!");
}
catch (Exception e){
System.out.println(e.toString());
}
}
}
Here's a method which receives boundaries and returns a random integer. It is slightly more advanced (completely universal): boundaries can be both positive and negative, and minimum/maximum boundaries can come in any order.
int myRand(int i_from, int i_to) {
return (int)(Math.random() * (Math.abs(i_from - i_to) + 1)) + Math.min(i_from, i_to);
}
In general, it finds the absolute distance between the borders, gets relevant random value, and then shifts the answer based on the bottom border.
I had this problem and it was due to an upgrade of my git executable. I rolled back to Git-2.21.0.rc1.windows.1-64-bit and added this to my environment path and it fixed my issue.
It's not the best answer, but its also an option: since you can concatenate multiple expressions, but just the last one is rendered, you can finish your expression with ""
and your variable will be hidden.
So, you could define the variable with:
{{f = forecast[day.iso]; ""}}
I had the same problem with bringing a JFrame
to the front under Ubuntu (Java 1.6.0_10). And the only way I could resolve it is by providing a WindowListener
. Specifically, I had to set my JFrame
to always stay on top whenever toFront()
is invoked, and provide windowDeactivated
event handler to setAlwaysOnTop(false)
.
So, here is the code that could be placed into a base JFrame
, which is used to derive all application frames.
@Override
public void setVisible(final boolean visible) {
// make sure that frame is marked as not disposed if it is asked to be visible
if (visible) {
setDisposed(false);
}
// let's handle visibility...
if (!visible || !isVisible()) { // have to check this condition simply because super.setVisible(true) invokes toFront if frame was already visible
super.setVisible(visible);
}
// ...and bring frame to the front.. in a strange and weird way
if (visible) {
toFront();
}
}
@Override
public void toFront() {
super.setVisible(true);
int state = super.getExtendedState();
state &= ~JFrame.ICONIFIED;
super.setExtendedState(state);
super.setAlwaysOnTop(true);
super.toFront();
super.requestFocus();
super.setAlwaysOnTop(false);
}
Whenever your frame should be displayed or brought to front call frame.setVisible(true)
.
Since I moved to Ubuntu 9.04 there seems to be no need in having a WindowListener
for invoking super.setAlwaysOnTop(false)
-- as can be observed; this code was moved to the methods toFront()
and setVisible()
.
Please note that method setVisible()
should always be invoked on EDT.
For 1.8.1 based on @ManuelSchneid3r 's answer I had to do:
wget github.com/google/googletar xf release-1.8.1.tar.gz
tar xf release-1.8.1.tar.gz
cd googletest-release-1.8.1/
cmake -DBUILD_SHARED_LIBS=ON .
make
I then did make install
which seemed to work for 1.8.1, but
following @ManuelSchneid3r it would mean:
sudo cp -a googletest/include/gtest /usr/include
sudo cp -a googlemock/include/gmock /usr/include
sudo cp `find .|grep .so$` /usr/lib/
You can use mplayer.
mencoder -nocache -rtsp-stream-over-tcp rtsp://192.168.XXX.XXX/test.sdp -oac copy -ovc copy -o test.avi
The "copy" codec is just a dumb copy of the stream. Mencoder adds a header and stuff you probably want.
In the mplayer source file "stream/stream_rtsp.c" is a prebuffer_size setting of 640k and no option to change the size other then recompile. The result is that writing the stream is always delayed, which can be annoying for things like cameras, but besides this, you get an output file, and can play it back most places without a problem.
As second says, most of the "design" decisions made for TeX documents are backed up by well researched usability studies, so changing them should be undertaken with care. It is, however, relatively common to replace Computer Modern with Times (also a serif face).
Try \usepackage{times}
.
You shouldn't design your application based on specific lifetimes of access tokens. Just assume they are (very) short lived.
However, after a successful completion of the OAuth2 installed application flow, you will get back a refresh token. This refresh token never expires, and you can use it to exchange it for an access token as needed. Save the refresh tokens, and use them to get access tokens on-demand (which should then immediately be used to get access to user data).
EDIT: My comments above notwithstanding, there are two easy ways to get the access token expiration time:
expires_in
)when you exchange your refresh token (using /o/oauth2/token endpoint). More details.There is also an API that returns the remaining lifetime of the access_token:
https://www.googleapis.com/oauth2/v1/tokeninfo?access_token={accessToken}
This will return a json array that will contain an expires_in
parameter, which is the number of seconds left in the lifetime of the token.
All This Work :)
Model
public partial class ClientMessage
{
public int IdCon { get; set; }
public string Name { get; set; }
public string Email { get; set; }
}
Controller
public class TestAjaxBeginFormController : Controller{
projectNameEntities db = new projectNameEntities();
public ActionResult Index(){
return View();
}
[HttpPost]
public ActionResult GetClientMessages(ClientMessage Vm) {
var model = db.ClientMessages.Where(x => x.Name.Contains(Vm.Name));
return PartialView("_PartialView", model);
}
}
View index.cshtml
@model projectName.Models.ClientMessage
@{
Layout = null;
}
<script src="~/Scripts/jquery-1.9.1.js"></script>
<script src="~/Scripts/jquery.unobtrusive-ajax.js"></script>
<script>
//\\\\\\\ JS retrun message SucccessPost or FailPost
function SuccessMessage() {
alert("Succcess Post");
}
function FailMessage() {
alert("Fail Post");
}
</script>
<h1>Page Index</h1>
@using (Ajax.BeginForm("GetClientMessages", "TestAjaxBeginForm", null , new AjaxOptions
{
HttpMethod = "POST",
OnSuccess = "SuccessMessage",
OnFailure = "FailMessage" ,
UpdateTargetId = "resultTarget"
}, new { id = "MyNewNameId" })) // set new Id name for Form
{
@Html.AntiForgeryToken()
@Html.EditorFor(x => x.Name)
<input type="submit" value="Search" />
}
<div id="resultTarget"> </div>
View _PartialView.cshtml
@model IEnumerable<projectName.Models.ClientMessage >
<table>
@foreach (var item in Model) {
<tr>
<td>@Html.DisplayFor(modelItem => item.IdCon)</td>
<td>@Html.DisplayFor(modelItem => item.Name)</td>
<td>@Html.DisplayFor(modelItem => item.Email)</td>
</tr>
}
</table>
Hi it is also possible for Strings with XML-Table
SELECT trim(COLUMN_VALUE) str FROM xmltable(('"'||REPLACE('a1, b2, a2, c1', ',', '","')||'"'));
Add "cd your_repos_path" to your Git profile, which is under the %
.
AH = 09 DS:DX = pointer to string ending in "$"
returns nothing
- outputs character string to STDOUT up to "$"
- backspace is treated as non-destructive
- if Ctrl-Break is detected, INT 23 is executed
ref: http://stanislavs.org/helppc/int_21-9.html
.data
string db 2 dup(' ')
.code
mov ax,@data
mov ds,ax
mov al,10
add al,15
mov si,offset string+1
mov bl,10
div bl
add ah,48
mov [si],ah
dec si
div bl
add ah,48
mov [si],ah
mov ah,9
mov dx,string
int 21h
It depends on the jQuery selector that you use. Since id
should be unique within the DOM, the first one would be simple:
$('#Comanda').hide();
The second one might require something more, depending on the other elements and how to uniquely identify it. If the name
of that particular input
is unique, then this would work:
$('input[name="Vizualizeaza"]').hide();
static class Program
{
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Login();
}
private static bool logOut;
private static void Login()
{
LoginForm login = new LoginForm();
MainForm main = new MainForm();
main.FormClosed += new FormClosedEventHandler(main_FormClosed);
if (login.ShowDialog(main) == DialogResult.OK)
{
Application.Run(main);
if (logOut)
Login();
}
else
Application.Exit();
}
static void main_FormClosed(object sender, FormClosedEventArgs e)
{
logOut= (sender as MainForm).logOut;
}
}
public partial class MainForm : Form
{
private void btnLogout_ItemClick(object sender, ItemClickEventArgs e)
{
//timer1.Stop();
this.logOut= true;
this.Close();
}
}
I use LogParser to generate graphs and look for elements in IIS logs.
I have used a span with in line styling. I have had to do this as I as processing a string of plain text and need to replace the \t with 4 spaces (appx). I couldn't use
as further on in the process they were being interpreted so that the final mark up had non-content spaces.
HTML:
<span style="padding: 0 40px"> </span>
I used it in a php function like this:
$message = preg_replace('/\t/', '<span style="padding: 0 40px"> </span>', $message);
Had the same problem Make sure whatever classes you have defined in models.py, you must have to inherit models.Model class.
class Product(models.Model):
title = models.TextField()
description = models.TextField()
price = models.TextField()
You can get good Time Series graphs in Excel, the way you want, but you have to work with a few quirks.
Be sure to select "Scatter Graph" (with a line option). This is needed if you have non-uniform time stamps, and will scale the X-axis accordingly.
In your data, you need to add a column with the mid-point. Here's what I did with your sample data. (This trick ensures that the data gets plotted at the mid-point, like you desire.)
You can format the x-axis options with this menu. (Chart->Design->Layout)
Select "Axes" and go to Primary Horizontal Axis, and then select "More Primary Horizontal Axis Options"
Set up the options you wish. (Fix the starting and ending points.)
And you will get a graph such as the one below.
You can then tweak many of the options, label the axes better etc, but this should get you started.
Hope this helps you move forward.
Elements are added to list using append()
:
>>> data = {'list': [{'a':'1'}]}
>>> data['list'].append({'b':'2'})
>>> data
{'list': [{'a': '1'}, {'b': '2'}]}
If you want to add element to a specific place in a list (i.e. to the beginning), use insert()
instead:
>>> data['list'].insert(0, {'b':'2'})
>>> data
{'list': [{'b': '2'}, {'a': '1'}]}
After doing that, you can assemble JSON again from dictionary you modified:
>>> json.dumps(data)
'{"list": [{"b": "2"}, {"a": "1"}]}'
You can do like this,this is the quickest process
Var result = MsgList.Except(MsgList.Where(o => SentList.Select(s => s.MsgID).ToList().Contains(o.MsgID))).ToList();
This will give you expected output.
Use exec sp_execsql @Sql
Example
DECLARE @sql as nvarchar(100)
DECLARE @paraDOB datetime
SET @paraDOB = '1/1/1981'
SET @sql=N'SELECT * FROM EmpMast WHERE DOB >= @paraDOB'
exec sp_executesql @sql,N'@paraDOB datetime',@paraDOB
When the normType
is NORM_MINMAX
, cv::normalize
normalizes _src
in such a way that the min value of dst
is alpha
and max value of dst
is beta
. cv::normalize
does its magic using only scales and shifts (i.e. adding constants and multiplying by constants).
CV_8UC1
says how many channels dst
has.
The documentation here is pretty clear: http://docs.opencv.org/modules/core/doc/operations_on_arrays.html#normalize
The existing answers explain the problem well but if including your script files using or before requireJS is not an easy option due to legacy code a slightly hacky workaround is to remove require from the window scope before your script tag and then reinstate it afterwords. In our project this is wrapped behind a server-side function call but effectively the browser sees the following:
<script>
window.__define = window.define;
window.__require = window.require;
window.define = undefined;
window.require = undefined;
</script>
<script src="your-script-file.js"></script>
<script>
window.define = window.__define;
window.require = window.__require;
window.__define = undefined;
window.__require = undefined;
</script>
Not the neatest but seems to work and has saved a lot of refractoring.
You could use css3 flexible box, it would go like this:
First your wrapper is wrapping a lot of things so you need a wrapper just for the 2 horizontal floated boxes:
<div id="hor-box">
<div id="left">
left
</div>
<div id="content">
content
</div>
</div>
And your css3 should be:
#hor-box{
display: -webkit-box;
display: -moz-box;
display: box;
-moz-box-orient: horizontal;
box-orient: horizontal;
-webkit-box-orient: horizontal;
}
#left {
width:200px;
background-color:antiquewhite;
margin-left:10px;
-webkit-box-flex: 0;
-moz-box-flex: 0;
box-flex: 0;
}
#content {
min-width:700px;
margin-left:10px;
background-color:AppWorkspace;
-webkit-box-flex: 1;
-moz-box-flex: 1;
box-flex: 1;
}
Try this
@Configuration
@ComponentScan
@EnableAutoConfiguration
public class Application {
public static void main(String[] args) {
SpringApplication.run(ScheduledTasks.class, args);
}
}
Wrap in a self executing function and return
(function(){
for(i=0;i<5;i++){
for (j=0;j<3;j++){
//console.log(i+' '+j);
if (j == 2) return;
}
}
})()
You can lowercase the value and the passed parameter :
SELECT * FROM `table` WHERE LOWER(`Value`) = LOWER("IAreSavage")
Another (better) way would be to use the COLLATE
operator as said in the documentation
Parent: Car
Child: Figo
Car c1 = new Figo();
=====
Upcasting:-
Method: Object c1 will refer to Methods of Class (Figo - Method must be overridden) because class "Figo" is specified with "new".
Instance Variable: Object c1 will refer to instance variable of Declaration Class ("Car").
When Declaration class is parent and object is created of child then implicit casting happens which is "Upcasting".
======
Downcasting:-
Figo f1 = (Figo) c1; //
Method: Object f1 will refer to Method of Class (figo) as initial object c1 is created with class "Figo". but once down casting is done, methods which are only present in class "Figo" can also be referred by variable f1.
Instance Variable: Object f1 will not refer to instance variable of Declaration class of object c1 (declaration class for c1 is CAR) but with down casting it will refer to instance variables of class Figo.
======
Use: When Object is of Child Class and declaration class is Parent and Child class wants to access Instance variable of it's own class and not of parent class then it can be done with "Downcasting".
Try username = root and password is blank.
So I was using Qt with Windows XP and MinGW compiler and this thing was driving me crazy.
Basically the moc_xxx.cpp was generated empty even when I was added
Q_OBJECT
Deleting everything making functions virtual, explicit and whatever you guess doesn't worked. Finally I started removing line by line and it turned out that I had
#ifdef something
Around the file. Even when the #ifdef was true moc file was not generated.
So removing all #ifdefs fixed the problem.
This thing was not happening with Windows and VS 2013.
You can use something like this:
$('#your-button').text('New Value');
You can also add extra properties like this:
$(this).text('New Value').attr('disabled', true).addClass('bt-hud').unbind('click');
For the sake of completeness: the previous answers tell how to set the upstream branch, but not how to see it.
There are a few ways to do this:
git branch -vv
shows that info for all branches. (formatted in blue in most terminals)
cat .git/config
shows this also.
For reference:
Here is a small example how to add a matplotlib grid in Gtk3 with Python 2 (not working in Python 3):
#!/usr/bin/env python
#-*- coding: utf-8 -*-
import gi
gi.require_version('Gtk', '3.0')
from gi.repository import Gtk
from matplotlib.figure import Figure
from matplotlib.backends.backend_gtk3agg import FigureCanvasGTK3Agg as FigureCanvas
win = Gtk.Window()
win.connect("delete-event", Gtk.main_quit)
win.set_title("Embedding in GTK3")
f = Figure(figsize=(1, 1), dpi=100)
ax = f.add_subplot(111)
ax.grid()
canvas = FigureCanvas(f)
canvas.set_size_request(400, 400)
win.add(canvas)
win.show_all()
Gtk.main()
The literal answer is:
return (value == 1 ? Periods.VariablePeriods : Periods.FixedPeriods);
Note that the inline if statement, just like an if statement, only checks for true or false. If (value == 1) evaluates to false, it might not necessarily mean that value == 2. Therefore it would be safer like this:
return (value == 1
? Periods.VariablePeriods
: (value == 2
? Periods.FixedPeriods
: Periods.Unknown));
If you add more values an inline if will become unreadable and a switch would be preferred:
switch (value)
{
case 1:
return Periods.VariablePeriods;
case 2:
return Periods.FixedPeriods;
}
The good thing about enums is that they have a value, so you can use the values for the mapping, as user854301 suggested. This way you can prevent unnecessary branches thus making the code more readable and extensible.
From the official GitFaq:
Git has a rename command
git mv
, but that is just a convenience. The effect is indistinguishable from removing the file and adding another with different name and the same content
You use the ajaxStop to execute code when the ajax are completed:
$(document).ajaxStop(function(){
setTimeout("window.location = 'otherpage.html'",100);
});
For those arriving around summer 2013, I believe some of this thread is outdated.
I followed this howto which recommends Vundle over Pathogen. After one days use I found installing plugins trivial.
The klen/python-mode plugin deserves special mention. It provides pyflakes and pylint amongst other features.
I have just started using Valloric/YouCompleteMe and I love it. It has C-lang auto-complete and python also works great thanks to jedi integration. It may well replace jedi-vim as per this discussion /davidhalter/jedi-vim/issues/119
Finally browsing the /carlhuda/janus plugins supplied is a good guide to useful scripts you might not know you are looking for such as NerdTree, vim-fugitive, syntastic, powerline, ack.vim, snipmate...
All the above '{}/{}' are found on github you can find them easily with Google.
You can also do it as part of the declaration:
int[] a = new int[] {0, 0, 0, 0};
Sometimes, when a function name and a variable name to which the return of the function is stored are same, the error is shown. Just happened to me.
To support full urls with param/values you'd need:
?next={{ request.get_full_path|urlencode }}
instead of just:
?next={{ request.path }}
To add the Tomcat 9.0 (Tomcat build from the trunk) as a server in Eclipse.
Update the ServerInfo.properties file properties as below.
server.info=Apache Tomcat/@VERSION@
server.number=@VERSION_NUMBER@
server.built=@VERSION_BUILT@
server.info=Apache Tomcat/7.0.57
server.number=7.0.57.0
server.built=Nov 3 2014 08:39:16 UTC
Build the tomcat server from trunk and add the server as tomcat7 instance in Eclipse.
ServerInfo.properties file location : \tomcat\java\org\apache\catalina\util\ServerInfo.properties
Replace everything with the remote branch; but, only from the same commit your local branch is on:
git reset --hard origin/some-branch
OR, get the latest from the remote branch and replace everything:
git fetch origin some-branch
git reset --hard FETCH_HEAD
As an aside, if needed, you can wipe out untracked files & directories that you haven't committed yet:
git clean -fd
Simply outputting something is PowerShell is a thing of beauty - and one its greatest strengths. For example, the common Hello, World! application is reduced to a single line:
"Hello, World!"
It creates a string object, assigns the aforementioned value, and being the last item on the command pipeline it calls the .toString()
method and outputs the result to STDOUT
(by default). A thing of beauty.
The other Write-*
commands are specific to outputting the text to their associated streams, and have their place as such.
If you are using SQL Server 2008 or later
select convert(date, getdate())
Otherwise
select convert(varchar(10), getdate(),120)
You can simply use multiprocessing.Pool
:
from multiprocessing import Pool
def process_image(name):
sci=fits.open('{}.fits'.format(name))
<process>
if __name__ == '__main__':
pool = Pool() # Create a multiprocessing Pool
pool.map(process_image, data_inputs) # process data_inputs iterable with pool
Swift 3 compatible
// MARK: - UIDevice Extension -
private let DeviceList = [
/* iPod 5 */ "iPod5,1": "iPod Touch 5",
/* iPhone 4 */ "iPhone3,1": "iPhone 4", "iPhone3,2": "iPhone 4", "iPhone3,3": "iPhone 4",
/* iPhone 4S */ "iPhone4,1": "iPhone 4S",
/* iPhone 5 */ "iPhone5,1": "iPhone 5", "iPhone5,2": "iPhone 5",
/* iPhone 5C */ "iPhone5,3": "iPhone 5C", "iPhone5,4": "iPhone 5C",
/* iPhone 5S */ "iPhone6,1": "iPhone 5S", "iPhone6,2": "iPhone 5S",
/* iPhone 6 */ "iPhone7,2": "iPhone 6",
/* iPhone 6 Plus */ "iPhone7,1": "iPhone 6 Plus",
/* iPhone 6S */ "iPhone8,1": "iPhone 6S",
/* iPhone 6S Plus */ "iPhone8,2": "iPhone 6S Plus",
/* iPhone SE */ "iPhone8,4": "iPhone SE",
/* iPhone 7 */ "iPhone9,1": "iPhone 7",
/* iPhone 7 */ "iPhone9,3": "iPhone 7",
/* iPhone 7 Plus */ "iPhone9,2": "iPhone 7 Plus",
/* iPhone 7 Plus */ "iPhone9,4": "iPhone 7 Plus",
/* iPad 2 */ "iPad2,1": "iPad 2", "iPad2,2": "iPad 2", "iPad2,3": "iPad 2", "iPad2,4": "iPad 2",
/* iPad 3 */ "iPad3,1": "iPad 3", "iPad3,2": "iPad 3", "iPad3,3": "iPad 3",
/* iPad 4 */ "iPad3,4": "iPad 4", "iPad3,5": "iPad 4", "iPad3,6": "iPad 4",
/* iPad Air */ "iPad4,1": "iPad Air", "iPad4,2": "iPad Air", "iPad4,3": "iPad Air",
/* iPad Air 2 */ "iPad5,1": "iPad Air 2", "iPad5,3": "iPad Air 2", "iPad5,4": "iPad Air 2",
/* iPad Mini */ "iPad2,5": "iPad Mini 1", "iPad2,6": "iPad Mini 1", "iPad2,7": "iPad Mini 1",
/* iPad Mini 2 */ "iPad4,4": "iPad Mini 2", "iPad4,5": "iPad Mini 2", "iPad4,6": "iPad Mini 2",
/* iPad Mini 3 */ "iPad4,7": "iPad Mini 3", "iPad4,8": "iPad Mini 3", "iPad4,9": "iPad Mini 3",
/* iPad Pro 12.9 */ "iPad6,7": "iPad Pro 12.9", "iPad6,8": "iPad Pro 12.9",
/* iPad Pro 9.7 */ "iPad6,3": "iPad Pro 9.7", "iPad6,4": "iPad Pro 9.7",
/* Simulator */ "x86_64": "Simulator", "i386": "Simulator"
]
extension UIDevice {
static var modelName: String {
var systemInfo = utsname()
uname(&systemInfo)
let machine = systemInfo.machine
let mirror = Mirror(reflecting: machine)
var identifier = ""
for child in mirror.children {
if let value = child.value as? Int8, value != 0 {
identifier += String(UnicodeScalar(UInt8(value)))
}
}
return DeviceList[identifier] ?? identifier
}
static var isIphone4: Bool {
return modelName == "iPhone 5" || modelName == "iPhone 5C" || modelName == "iPhone 5S" || UIDevice.isSimulatorIPhone4
}
static var isIphone5: Bool {
return modelName == "iPhone 4S" || modelName == "iPhone 4" || UIDevice.isSimulatorIPhone5
}
static var isIphone6: Bool {
return modelName == "iPhone 6" || UIDevice.isSimulatorIPhone6
}
static var isIphone6Plus: Bool {
return modelName == "iPhone 6 Plus" || UIDevice.isSimulatorIPhone6Plus
}
static var isIpad: Bool {
if UIDevice.current.model.contains("iPad") {
return true
}
return false
}
static var isIphone: Bool {
return !self.isIpad
}
/// Check if current device is iPhone4S (and earlier) relying on screen heigth
static var isSimulatorIPhone4: Bool {
return UIDevice.isSimulatorWithScreenHeigth(480)
}
/// Check if current device is iPhone5 relying on screen heigth
static var isSimulatorIPhone5: Bool {
return UIDevice.isSimulatorWithScreenHeigth(568)
}
/// Check if current device is iPhone6 relying on screen heigth
static var isSimulatorIPhone6: Bool {
return UIDevice.isSimulatorWithScreenHeigth(667)
}
/// Check if current device is iPhone6 Plus relying on screen heigth
static var isSimulatorIPhone6Plus: Bool {
return UIDevice.isSimulatorWithScreenHeigth(736)
}
private static func isSimulatorWithScreenHeigth(_ heigth: CGFloat) -> Bool {
let screenSize: CGRect = UIScreen.main.bounds
return modelName == "Simulator" && screenSize.height == heigth
}
}
Generally, you cannot send a POST request using sendRedirect() method. You can use RequestDispatcher to forward() requests with parameters within the same web application, same context.
RequestDispatcher dispatcher = servletContext().getRequestDispatcher("test.jsp");
dispatcher.forward(request, response);
The HTTP spec states that all redirects must be in the form of a GET (or HEAD). You can consider encrypting your query string parameters if security is an issue. Another way is you can POST to the target by having a hidden form with method POST and submitting it with javascript when the page is loaded.
Just a shot in the dark(since you did not share the compiler
initialization code with us): the way you retrieve the compiler
causes the issue. Point your JRE to be inside the JDK as unlike jdk, jre does not provide any tools hence, results in NPE
.
If you are using HTML Form element instead Laravel Form Builder, you must place method_field
between your
form opening tag and closing end. By doing this you may explicitly define form method type.
<form>
{{ method_field('PUT') }}
</form>
The geocoder has quota and rate limits. From experience, you can geocode ~10 locations without hitting the query limit (the actual number probably depends on server loading). The best solution is to delay when you get OVER_QUERY_LIMIT errors, then retry. See these similar posts:
CDATA stands for Character Data. You can use this to escape some characters which otherwise will be treated as regular XML. The data inside this will not be parsed.
For example, if you want to pass a URL that contains &
in it, you can use CDATA to do it. Otherwise, you will get an error as it will be parsed as regular XML.
As Davide Gualano has been told. This one
$("#myDiv").load("myScript.php?var=x&var2=y&var3=z")
use GET method for sending the request, and this one
$("#myDiv").load("myScript.php", {var:x, var2:y, var3:z})
use POST method for sending the request. But any limitation that is applied to each method (post/get) is applied to the alternative usages that has been mentioned in the question.
For example: url length limits the amount of sending data in GET method.
In my case the /usr/local/Frameworks didn't even exist, so I did:
sudo mkdir /usr/local/Frameworks
sudo chown -R $(whoami) /usr/local/Frameworks
And then everything worked as expected.
I use the command pkill
for this:
NAME
pgrep, pkill - look up or signal processes based on name and
other attributes
SYNOPSIS
pgrep [options] pattern
pkill [options] pattern
DESCRIPTION
pgrep looks through the currently running processes and lists
the process IDs which match the selection criteria to stdout.
All the criteria have to match. For example,
$ pgrep -u root sshd
will only list the processes called sshd AND owned by root.
On the other hand,
$ pgrep -u root,daemon
will list the processes owned by root OR daemon.
pkill will send the specified signal (by default SIGTERM)
to each process instead of listing them on stdout.
If your code runs via interpreter (java, python, ...) then the name of the process is the name of the interpreter. You need to user the argument --full. This matches against the command name and the arguments.
Create the data/db directory in your main (windows) partition:
C:\> mkdir \data
C:\> mkdir \data\db
and then go to your mongo_directory/bin and run mongod.exe:
C:\> cd \my_mongo_dir\bin
C:\my_mongo_dir\bin> mongod
DON't CLOSE THIS WINDOW
Now in a different command prompt window run Mongo:
C:\> cd \my_mongo_dir\bin
C:\my_mongo_dir\bin> mongo
(REMEMBER YOU HAVE TO KEEP THAT OTHER WINDOW OPEN)
This solved the problem for me.
If you want to make exceptions, you can apply the following "hack". It requires a user with DELETE
and INSERT
privilege for mysql.plugin
system table.
uninstall plugin validate_password;
SET PASSWORD FOR 'app' = PASSWORD('abcd');
INSTALL PLUGIN validate_password SONAME 'validate_password.so';
Bland security disclaimer: Consider, why you are making your password shorter or easier and perhaps consider replacing it with one that is more complex. However, I understand the "it's 3AM and just needs to work" moments, just make sure you don't build a system of hacks, lest you yourself be hacked
This solution lists all the columns of your object my_dataframe:
print(list(my_dataframe))
Click on "Tables" in "Connections" window, choose "Import data ...", follow the wizard and you will be asked for name for new table.
If you want window handles for ALL of your application's Window
s for some reason, you can use the Application.Windows
property to get at all the Windows and then use WindowInteropHandler
to get at their handles as you have already demonstrated.
You need to be able to read code written by people who have different style and best practices opinions than you.
If you're only using cout
, nobody gets confused. But when you have lots of namespaces flying around and you see this class and you aren't exactly sure what it does, having the namespace explicit acts as a comment of sorts. You can see at first glance, "oh, this is a filesystem operation" or "that's doing network stuff".
The os.makedirs
function does this. Try the following:
import os
import errno
filename = "/foo/bar/baz.txt"
if not os.path.exists(os.path.dirname(filename)):
try:
os.makedirs(os.path.dirname(filename))
except OSError as exc: # Guard against race condition
if exc.errno != errno.EEXIST:
raise
with open(filename, "w") as f:
f.write("FOOBAR")
The reason to add the try-except
block is to handle the case when the directory was created between the os.path.exists
and the os.makedirs
calls, so that to protect us from race conditions.
In Python 3.2+, there is a more elegant way that avoids the race condition above:
import os
filename = "/foo/bar/baz.txt"
os.makedirs(os.path.dirname(filename), exist_ok=True)
with open(filename, "w") as f:
f.write("FOOBAR")
At first I thought you could use regular expressions, but as I've been reading the MYSQL docs it seems you can't. If I were you I would use another language (such as PHP) to generate a list of columns you want to get, store it as a string and then use that to generate the SQL.
Use a list instead and replace your foreach
loop with a for
loop:
@model IList<BlockedIPViewModel>
@using (Html.BeginForm())
{
@Html.AntiForgeryToken()
@for (var i = 0; i < Model.Count; i++)
{
<tr>
<td>
@Html.HiddenFor(x => x[i].IP)
@Html.CheckBoxFor(x => x[i].Checked)
</td>
<td>
@Html.DisplayFor(x => x[i].IP)
</td>
</tr>
}
<div>
<input type="submit" value="Unblock IPs" />
</div>
}
Alternatively you could use an editor template:
@model IEnumerable<BlockedIPViewModel>
@using (Html.BeginForm())
{
@Html.AntiForgeryToken()
@Html.EditorForModel()
<div>
<input type="submit" value="Unblock IPs" />
</div>
}
and then define the template ~/Views/Shared/EditorTemplates/BlockedIPViewModel.cshtml
which will automatically be rendered for each element of the collection:
@model BlockedIPViewModel
<tr>
<td>
@Html.HiddenFor(x => x.IP)
@Html.CheckBoxFor(x => x.Checked)
</td>
<td>
@Html.DisplayFor(x => x.IP)
</td>
</tr>
The reason you were getting null in your controller is because you didn't respect the naming convention for your input fields that the default model binder expects to successfully bind to a list. I invite you to read the following article
.
Once you have read it, look at the generated HTML (and more specifically the names of the input fields) with my example and yours. Then compare and you will understand why yours doesn't work.
Just wanted to add one more problem that some people might find on top of all the other answers. Sending JSON object using RAW data and setting the type to application/json
is what is to be done as has been mentioned above.
Even though I had done so, I got error in the POSTMAN request, it was because I accidentally forgot to create a default constructor for both child class.
Say if I had to send a JSON of format:
{
"firstname" : "John",
"lastname" : "Doe",
"book":{
"name":"Some Book",
"price":12.2
}
}
Then just make sure you create a default constructor for Book class.
I know this is a simple and uncommon error, but did certainly help me.
Here is an alternative from one of my tests:
__block BOOL success;
NSCondition *completed = NSCondition.new;
[completed lock];
STAssertNoThrow([self.client asyncSomethingWithCompletionHandler:^(id value) {
success = value != nil;
[completed lock];
[completed signal];
[completed unlock];
}], nil);
[completed waitUntilDate:[NSDate dateWithTimeIntervalSinceNow:2]];
[completed unlock];
STAssertTrue(success, nil);
I also see that the page loading (performance) takes a long time on using h:commandLink than h:link. h:link is faster compared to h:commandLink
For multivalue map you can do like below (using java 8 stream api's)
Url encoding has been taken cared in this.
MultiValueMap<String, String> params = new LinkedMultiValueMap<>();
String urlQueryString = params.entrySet()
.stream()
.flatMap(stringListEntry -> stringListEntry.getValue()
.stream()
.map(s -> UriUtils.encode(stringListEntry.getKey(), StandardCharsets.UTF_8.toString()) + "=" +
UriUtils.encode(s, StandardCharsets.UTF_8.toString())))
.collect(Collectors.joining("&"));
I'm a total noob but I reinstalled over the codeblocks giving me these "Can't find file executable in your configured search path for gnc gcc compiler" errors by downloading:
codeblocks-20.03mingw-setup.exe
(IMPORTANT: make sure it has the "mingw" in the file download name, that has the compiler build that is required to compile the code which doesn't automatically comes with the main codeblocks editor software download because codeblocks already assumes you already have another compiler installed on your computer {visual studio 2019 or such}).
Then when I created a new project (console application) and used the defaults to quickly test it out.
It gave me errors.
So I went to Settings > Compiler > Selected Compiler set to: GNU GCC Compiler > Click on the "Tooolchain executables" tab > Click on Auto-Detect > Should say "C:\Progam Files\CodeBlocks\MinGW" > Click OK.
Build and run a simple hello world code.
Should work! If not, look for the "MingGW" in the C:\Program Files\CodeBlocks and select it.
You can wrap it in a TreeSet like this:
Set mySet = new HashSet();
mySet.add(4);
mySet.add(5);
mySet.add(3);
mySet.add(1);
System.out.println("mySet items "+ mySet);
TreeSet treeSet = new TreeSet(mySet);
System.out.println("treeSet items "+ treeSet);
output :
mySet items [1, 3, 4, 5]
treeSet items [1, 3, 4, 5]
Set mySet = new HashSet();
mySet.add("five");
mySet.add("elf");
mySet.add("four");
mySet.add("six");
mySet.add("two");
System.out.println("mySet items "+ mySet);
TreeSet treeSet = new TreeSet(mySet);
System.out.println("treeSet items "+ treeSet);
output:
mySet items [six, four, five, two, elf]
treeSet items [elf, five, four, six, two]
requirement for this method is that the objects of the set/list should be comparable (implement the Comparable interface)
<input onkeyup="this.setAttribute('value', this.value);" />
and
input[value=""]
will work :-)
Reason for the error:
Column
expands to the maximum size in main axis direction (vertical axis), and so does the ListView
.
Solutions
So, you need to constrain the height of the ListView
. There are many ways of doing it, you can choose that best suits your need.
If you want to allow ListView
to take up all remaining space inside Column
use Expanded
.
Column(
children: <Widget>[
Expanded(
child: ListView(...),
)
],
)
If you want to limit your ListView
to certain height
, you can use SizedBox
.
Column(
children: <Widget>[
SizedBox(
height: 200, // constrain height
child: ListView(),
)
],
)
If your ListView
is small, you may try shrinkWrap
property on it.
Column(
children: <Widget>[
ListView(
shrinkWrap: true, // use it
)
],
)
Of course you can. In Nodejs you can connect server side JavaScript with MySQL using MySQL driver. Nodejs-MySQL
For folks who are stumbling across Victor Stoddard's answer above in 2019, and become hopeful and doe eyed, note that:
a) Support for X-Content-Duration was removed in Firefox 41: https://developer.mozilla.org/en-US/docs/Mozilla/Firefox/Releases/41#HTTP
b) I think it was only supported in Firefox for .ogg audio and .ogv video, not for any other types.
c) I can't see that it was ever supported at all in Chrome, but that may just be a lack of research on my part. But its presence or absence seems to have no effect one way or another for webm or ogv videos as of today in Chrome 71.
d) I can't find anywhere where 'Content-Duration' replaced 'X-Content-Duration' for anything, I don't think 'X-Content-Duration' lived long enough for there to be a successor header name.
I think this means that, as of today if you want to serve webm or ogv containers that contain streams that don't know their duration (e.g. the output of an ffpeg pipe) to Chrome or FF, and you want them to be scrubbable in an HTML 5 video element, you are probably out of luck. Firefox 64.0 makes a half hearted attempt to make these scrubbable whether or not you serve via range requests, but it gets confused and throws up a spinning wheel until the stream is completely downloaded if you seek a few times more than it thinks is appropriate. Chrome doesn't even try, it just nopes out and won't let you scrub at all until the entire stream is finished playing.
On windows:
Add an environmental variable (in both system and user's variables, I have some weird problem, that it gets the var from various places, so I add them in both of them).
Name it MAVEN_OPTS.
Value will be: -Xms1024m -Xmx3000m -XX:MaxPermSize=1024m -XX:+CMSClassUnloadingEnabled
The numbers can be different, make them relative to your mem size.
I had that problem and this fixed it, nothing else!
There are good options given in How To Reset MySQL Autoincrement Column
Note that ALTER TABLE tablename AUTO_INCREMENT = value;
does not work for InnoDB
select InitialPayment * MonthlyRate as MultiplyingCalculation, InitialPayment - MonthlyRate as SubtractingCalculation from Payment
Sencha acquired Raphael and now their charts are pure javascript as of version 4. Emprise and HighCharts mentioned above are my two favorites.
And my 15 cent. A one liner for the mac terminal etc just set the MIN= to whatever and a message
MIN=15 && for i in $(seq $(($MIN*60)) -1 1); do echo "$i, "; sleep 1; done; echo -e "\n\nMac Finder should show a popup" afplay /System/Library/Sounds/Funk.aiff; osascript -e 'tell app "Finder" to display dialog "Look away. Rest your eyes"'
A bonus example for inspiration to combine more commands; this will put a mac put to standby sleep upon the message too :) the sudo login is needed then, a multiplication as the 60*2 for two hours goes aswell
sudo su
clear; echo "\n\nPreparing for a sleep when timers done \n"; MIN=60*2 && for i in $(seq $(($MIN*60)) -1 1); do printf "\r%02d:%02d:%02d" $((i/3600)) $(( (i/60)%60)) $((i%60)); sleep 1; done; echo "\n\n Time to sleep zzZZ"; afplay /System/Library/Sounds/Funk.aiff; osascript -e 'tell app "Finder" to display dialog "Time to sleep zzZZ"'; shutdown -h +1 -s
Use MySQL's STR_TO_DATE()
function to parse the string that you're attempting to insert:
INSERT INTO tblInquiry (fldInquiryReceivedDateTime) VALUES
(STR_TO_DATE('5/15/2012 8:06:26 AM', '%c/%e/%Y %r'))
This is extremely easy to do in Sass! Don't delve into JavaScript for this. The & selector in sass does exactly this.
http://thesassway.com/intermediate/referencing-parent-selectors-using-ampersand
See ?boxplot
for all the help you need.
outline: if ‘outline’ is not true, the outliers are not drawn (as
points whereas S+ uses lines).
boxplot(x,horizontal=TRUE,axes=FALSE,outline=FALSE)
And for extending the range of the whiskers and suppressing the outliers inside this range:
range: this determines how far the plot whiskers extend out from the
box. If ‘range’ is positive, the whiskers extend to the most
extreme data point which is no more than ‘range’ times the
interquartile range from the box. A value of zero causes the
whiskers to extend to the data extremes.
# change the value of range to change the whisker length
boxplot(x,horizontal=TRUE,axes=FALSE,range=2)
Password boxes are also textboxes, so if you need them too:
$("input[type='text'], textarea, input[type='password']").css({width: "90%"});
and while file-input is a bit different, you may want to include them too (eg. for visual consistency):
$("input[type='text'], textarea, input[type='password'], input[type='file']").css({width: "90%"});
The best javascript solution I've found is this
elm.options[0].selected="selected";
if($('selector').hasClass('active')){ }
i think this will check if the selector hasClass active ...
Add this into your header
<script>
//tooltip
$(function() {
var tooltips = $( "[title]" ).tooltip();
$(document)(function() {
tooltips.tooltip( "open" );
});
});
</script>
Then just add the attribute title="your tooltip"
to any element
to install uuid
npm install --save uuid
uuid is updated and the old import
const uuid= require('uuid/v4');
is not working and we should now use this import
const {v4:uuid} = require('uuid');
and for using it use as a funciton like this
const createdPlace = {
id: uuid(),
title,
description,
location:coordinates,
address,
creator
};
The basic intrinsic types (e.g. byte
, int
, string
, and arrays) will be serialized automatically by WCF. Custom classes, like your UploadedFile, won't be.
So, a silly question (but I have to ask it...): is UploadedFile marked as a [DataContract]
? If not, you'll need to make sure that it is, and that each of the members in the class that you want to send are marked with [DataMember].
Unlike remoting, where marking a class with [XmlSerializable] allowed you to serialize the whole class without bothering to mark the members that you wanted serialized, WCF needs you to mark up each member. (I believe this is changing in .NET 3.5 SP1...)
A tremendous resource for WCF development is what we know in our shop as "the fish book": Programming WCF Services by Juval Lowy. Unlike some of the other WCF books around, which are a bit dry and academic, this one takes a practical approach to building WCF services and is actually useful. Thoroughly recommended.
I use the following macro to help me out with NSRect:
#define LogRect(RECT) NSLog(@"%s: (%0.0f, %0.0f) %0.0f x %0.0f",
#RECT, RECT.origin.x, RECT.origin.y, RECT.size.width, RECT.size.height)
You could do something similar for CGPoint:
@define LogCGPoint(POINT) NSLog(@"%s: (%0.0f, %0.0f)",
#POINT POINT.x, POINT.y);
Using it as follows:
LogCGPoint(cgPoint);
Would produce the following:
cgPoint: (100, 200)
Try this:
SELECT *
FROM (SELECT * FROM (
SELECT
id,
client_id,
create_time,
ROW_NUMBER() OVER(PARTITION BY client_id ORDER BY create_time DESC) rn
FROM order
)
WHERE rn=1
ORDER BY create_time desc) alias_name
WHERE rownum <= 100
ORDER BY rownum;
Or TOP:
SELECT TOP 2 * FROM Customers; //But not supported in Oracle
NOTE: I suppose that your internal query is fine. Please share your output of this.
Look at the filter
function.
If you just need a 1-pole low-pass filter, it's
xfilt = filter(a, [1 a-1], x);
where a = T/τ, T = the time between samples, and τ (tau) is the filter time constant.
Here's the corresponding high-pass filter:
xfilt = filter([1-a a-1],[1 a-1], x);
If you need to design a filter, and have a license for the Signal Processing Toolbox, there's a bunch of functions, look at fvtool and fdatool.
Copying the code from this page - works in mail()
He starts off my making a function mail_attachment that can be called later. Which he does later with his attachment code.
<?php
function mail_attachment($filename, $path, $mailto, $from_mail, $from_name, $replyto, $subject, $message) {
$file = $path.$filename;
$file_size = filesize($file);
$handle = fopen($file, "r");
$content = fread($handle, $file_size);
fclose($handle);
$content = chunk_split(base64_encode($content));
$uid = md5(uniqid(time()));
$header = "From: ".$from_name." <".$from_mail.">\r\n";
$header .= "Reply-To: ".$replyto."\r\n";
$header .= "MIME-Version: 1.0\r\n";
$header .= "Content-Type: multipart/mixed; boundary=\"".$uid."\"\r\n\r\n";
$header .= "This is a multi-part message in MIME format.\r\n";
$header .= "--".$uid."\r\n";
$header .= "Content-type:text/plain; charset=iso-8859-1\r\n";
$header .= "Content-Transfer-Encoding: 7bit\r\n\r\n";
$header .= $message."\r\n\r\n";
$header .= "--".$uid."\r\n";
$header .= "Content-Type: application/octet-stream; name=\"".$filename."\"\r\n"; // use different content types here
$header .= "Content-Transfer-Encoding: base64\r\n";
$header .= "Content-Disposition: attachment; filename=\"".$filename."\"\r\n\r\n";
$header .= $content."\r\n\r\n";
$header .= "--".$uid."--";
if (mail($mailto, $subject, "", $header)) {
echo "mail send ... OK"; // or use booleans here
} else {
echo "mail send ... ERROR!";
}
}
//start editing and inputting attachment details here
$my_file = "somefile.zip";
$my_path = "/your_path/to_the_attachment/";
$my_name = "Olaf Lederer";
$my_mail = "[email protected]";
$my_replyto = "[email protected]";
$my_subject = "This is a mail with attachment.";
$my_message = "Hallo,\r\ndo you like this script? I hope it will help.\r\n\r\ngr. Olaf";
mail_attachment($my_file, $my_path, "[email protected]", $my_mail, $my_name, $my_replyto, $my_subject, $my_message);
?>
He has more details on his page and answers some problems in the comments section.
In PHP, a variable or array element which has never been set is different from one whose value is null
; attempting to access such an unset value is a runtime error.
That's what you're running into: the array $_POST
does not have any element at the key "username"
, so the interpreter aborts your program before it ever gets to the nullity test.
Fortunately, you can test for the existence of a variable or array element without actually trying to access it; that's what the special operator isset
does:
if (isset($_POST["username"]))
{
$user = $_POST["username"];
echo $user;
echo " is your username";
}
else
{
$user = null;
echo "no username supplied";
}
This looks like it will blow up in exactly the same way as your code, when PHP tries to get the value of $_POST["username"]
to pass as an argument to the function isset()
. However, isset()
is not really a function at all, but special syntax recognized before the evaluation stage, so the PHP interpreter checks for the existence of the value without actually trying to retrieve it.
It's also worth mentioning that as runtime errors go, a missing array element is considered a minor one (assigned the E_NOTICE
level). If you change the error_reporting
level so that notices are ignored, your original code will actually work as written, with the attempted array access returning null
. But that's considered bad practice, especially for production code.
Side note: PHP does string interpolation, so the echo
statements in the if
block can be combined into one:
echo "$user is your username";
When you're working with strings in PHP you'll need to pay special attention to the formation, using "
or '
$string = 'Hello, world!';
$string = "Hello, world!";
Both of these are valid, the following is not:
$string = "Hello, world';
You must also note that '
inside of a literal started with "
will not end the string, and vice versa. So when you have a string which contains '
, it is generally best practice to use double quotation marks.
$string = "It's ok here";
Escaping the string is also an option
$string = 'It\'s ok here too';
More information on this can be found within the documentation
In my case I'm using C# OracleCommand
with OracleParameter
, and I set all the the parameters Size
property to max length of each column, then the error solved.
OracleParameter parm1 = new OracleParameter();
param1.OracleDbType = OracleDbType.Varchar2;
param1.Value = "test1";
param1.Size = 8;
OracleParameter parm2 = new OracleParameter();
param2.OracleDbType = OracleDbType.Varchar2;
param2.Value = "test1";
param2.Size = 12;
Here column name must be decimal.
select CAST(columnname AS decimal(38,0)) from table
Official npm page suggest a structured method to update angular version for both global and local scenarios.
1.First of all, you need to uninstall the current angular from your system.
npm uninstall -g angular-cli
npm uninstall --save-dev angular-cli
npm uninstall -g @angular/cli
2.Clean up the cache
npm cache clean
EDIT
As pointed out by @candidj
npm cache clean
is renamed as npm cache verify
from npm 5 onwards
3.Install angular globally
npm install -g @angular/cli@latest
4.Local project setup if you have one
rm -rf node_modules
npm install --save-dev @angular/cli@latest
npm install
Please check the same down on the link below:
https://www.npmjs.com/package/@angular/cli#updating-angular-cli
This will solve the problem.