To get the lines that contain the texts 8768
, 9875
or 2353
, use:
^.*(8768|9875|2353).*$
What it means:
^ from the beginning of the line
.* get any character except \n (0 or more times)
(8768|9875|2353) if the line contains the string '8768' OR '9875' OR '2353'
.* and get any character except \n (0 or more times)
$ until the end of the line
If you do want the literal *
char, you'd have to escape it:
^.*(\*8768|\*9875|\*2353).*$
I use gitosis for managing this kind of stuff. Gitosis has a single user (usually called "git") that owns all the repositories, and it uses public-key-based access control to each repo. It might not suit your setup but is probably worth checking out (no pun intended).
SSH itself provides a means of communication, it does not know anything about directories. Since you can specify which remote command to execute (this is - by default - your shell), I'd start there.
How about this:
text=" <tag>bmnmn</tag> "
if [[ "$text" =~ "<tag>" ]]; then
echo "matched"
else
echo "not matched"
fi
Here is an easy way to fetch data from a MySQL database using PDO.
define("DB_HOST", "localhost"); // Using Constants
define("DB_USER", "YourUsername");
define("DB_PASS", "YourPassword");
define("DB_NAME", "Yourdbname");
$dbc = new PDO("mysql:host=".DB_HOST.";dbname=".DB_NAME.";charset-utf8mb4", DB_USER, DB_PASS);
$print = ""; // assign an empty string
$stmt = $dbc->query("SELECT * FROM tableName"); // fetch data
$stmt->setFetchMode(PDO::FETCH_OBJ);
$print .= '<table border="1px">';
$print .= '<tr><th>First name</th>';
$print .= '<th>Last name</th></tr>';
while ($names = $stmt->fetch()) { // loop and display data
$print .= '<tr>';
$print .= "<td>{$names->firstname}</td>";
$print .= "<td>{$names->lastname}</td>";
$print .= '</tr>';
}
$print .= "</table>";
echo $print;
Your best bet is to change that column to a timestamp. MySQL will automatically use the first timestamp in a row as a 'last modified' value and update it for you. This is configurable if you just want to save creation time.
See doc http://dev.mysql.com/doc/refman/5.7/en/timestamp-initialization.html
your validation should be occur before your event suppose you are going to submit your form.
anyway if you want this on onchange, so here is code.
function valid(id)
{
var textVal=document.getElementById(id).value;
if (!textVal.match(/\S/))
{
alert("Field is blank");
return false;
}
else
{
return true;
}
}
For simple document, I sometimes use verbatim, but listing is nice for big chunk of code.
<script type="text/javascript" src="jquery-1.9.1.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$(".click-header").click(function(){
$(this).next(".hidden-content").slideToggle("slow");
$(this).toggleClass("expanded-header");
});
});
</script>
.demo-container {
margin:0 auto;
width: 600px;
text-align:center;
}
.click-header {
padding: 5px 10px 5px 60px;
background: url(images/arrow-down.png) no-repeat 50% 50%;
}
.expanded-header {
padding: 5px 10px 5px 60px;
background: url(images/arrow-up.png) no-repeat 50% 50%;
}
.hidden-content {
display:none;
border: 1px solid #d7dbd8;
padding: 20px;
text-align: center;
}
<div class="demo-container">
<div class="click-header"> </div>
<div class="hidden-content">Lorem Ipsum.</div>
</div>
SQL tables have no implicit ordering, the order has to come from the data. Perhaps you should add a field to your table (e.g. an int counter) and re-import the data.
However that will only give the order of the import and not the data. If your data has no ordering you have to find out how to add it.
EDIT: you say
...to make sure it imported everything.
What's wrong with using row count?
%3A
and %2F
are URL encoded characters. Use this java code to convert them back into :
and /
String decoded = java.net.URLDecoder.decode(url, "UTF-8");
I prefer to use:
string result = "myFile_" + DateTime.Now.ToFileTime() + ".txt";
What does ToFileTime() do?
Converts the value of the current DateTime object to a Windows file time.
public long ToFileTime()
A Windows file time is a 64-bit value that represents the number of 100-nanosecond intervals that have elapsed since 12:00 midnight, January 1, 1601 A.D. (C.E.) Coordinated Universal Time (UTC). Windows uses a file time to record when an application creates, accesses, or writes to a file.
The problem was, in the URL i wrote http://my_domain instead of https://my_domain
For mysqli you can use :
$db = ADONewConnection('mysqli');
... ...
$db->execute("set names 'utf8'");
Many UNIX programs respect the http_proxy
environment variable, curl included. The format curl accepts is [protocol://]<host>[:port]
.
In your shell configuration:
export http_proxy http://proxy.server.com:3128
For proxying HTTPS requests, set https_proxy
as well.
Curl also allows you to set this in your .curlrc
file (_curlrc
on Windows), which you might consider more permanent:
http_proxy=http://proxy.server.com:3128
Just a note that the constant
keyword use for safe-area margins has been updated to env
for 11.2 beta+
https://webkit.org/blog/7929/designing-websites-for-iphone-x/
Better solution is to introduce another interface for async operations. New interface must inherit from original interface.
Example:
interface IIO
{
void DoOperation();
}
interface IIOAsync : IIO
{
Task DoOperationAsync();
}
class ClsAsync : IIOAsync
{
public void DoOperation()
{
DoOperationAsync().GetAwaiter().GetResult();
}
public async Task DoOperationAsync()
{
//just an async code demo
await Task.Delay(1000);
}
}
class Program
{
static void Main(string[] args)
{
IIOAsync asAsync = new ClsAsync();
IIO asSync = asAsync;
Console.WriteLine(DateTime.Now.Second);
asAsync.DoOperation();
Console.WriteLine("After call to sync func using Async iface: {0}",
DateTime.Now.Second);
asAsync.DoOperationAsync().GetAwaiter().GetResult();
Console.WriteLine("After call to async func using Async iface: {0}",
DateTime.Now.Second);
asSync.DoOperation();
Console.WriteLine("After call to sync func using Sync iface: {0}",
DateTime.Now.Second);
Console.ReadKey(true);
}
}
P.S. Redesign your async operations so they return Task instead of void, unless you really must return void.
Static makes the clock member a class member instead of an instance member. Without the static keyword you would need to create an instance of the Hello class (which has a clock member variable) - e.g.
Hello hello = new Hello();
hello.clock.sayTime();
Your problem is that you are relying on the browser to resize your images. Browsers have notoriously poor image scaling algorithms, which will cause the ugly pixelization.
You should resize your images in a graphics program first before you use them on the webpage.
Also, you have a spelling mistake: it should say moz-crisp-edges; however, that won't help you in your case (because that resizing algorithm won't give you a high quality resize: https://developer.mozilla.org/En/CSS/Image-rendering)
In my case I don't have issues with ~/.composer
.
So being inside Laravel app root folder, I did sudo chown -R $USER composer.lock
and it was helpful.
Another useful resource:
http://psoug.org/reference/roles.html
public static final String URL = "jdbc:sqlserver://localhost:1433;databaseName=dbName";
public static final String USERNAME = "xxxx";
public static final String PASSWORD = "xxxx";
/**
* This method
@param args command line argument
*/
public static void main(String[] args)
{
try
{
Connection connection;
DriverManager.registerDriver(new com.microsoft.sqlserver.jdbc.SQLServerDriver());
connection = DriverManager.getConnection(MainDriver.URL,MainDriver.USERNAME,
MainDriver.PASSWORD);
String query ="select * from employee";
Statement statement = connection.createStatement();
ResultSet resultSet = statement.executeQuery(query);
while(resultSet.next())
{
System.out.print("First Name: " + resultSet.getString("first_name"));
System.out.println(" Last Name: " + resultSet.getString("last_name"));
}
}catch(Exception ex)
{
ex.printStackTrace();
}
}
I edited the select2.min.js
file to set the select-2__search
input field that's generated to readonly="true"
.
You are correct, but note that you can do it the other way around - use Android Wifi tethering that sets up the phone as a base station and connect to said base station from the laptop.
Css classes are here
<style type="text/css">
.mymenu
{
background-color: blue;
color: white;
}
.newmenu
{
background-color: red;
color: white;
}
</style>
Make your HTML like this, Set url as id
<div class="my_menu" id="index-url"><a href="index-url">Index</a></div>
<div class="my_menu" id="contact-url"><a href="contact-url">Contac</a></div>
Here write javascript, put this javascript after the HTML code.
function menuHighlight() {
var url = window.location.href;
$('#'+tabst).addClass('new_current');
}
menuHighlight();
A one-liner is:-
fruitdict = dict(zip(('apple','banana','carrot'), (1,'f', '3'))
scanf
needs to know the size of the data being pointed at by &d
to fill it properly, whereas variadic functions promote floats to doubles (not entirely sure why), so printf
is always getting a double
.
$(document).ready(function() {
$('#Button').click(function() {
$(this).addClass('active');
});
});
should do the trick. unless you're loading the button with ajax. In which case you could do:
$('#Button').live('click', function() {...
Also remember not to use the same id more than once in your html code.
You can try this:
HTML
<div class="social">
<div class="socialIcon"><img src="images/facebook.png" alt="Facebook" /></div>
<div class="socialText">Find me on Facebook</div>
</div>
CSS CODE
.social {
width:330px;
height:75px;
float:right;
text-align:left;
padding:10px 0;
border-bottom:dotted 1px #6d6d6d;
}
.social .socialIcon{
padding-top:0;
}
.social .socialText{
border:0;
}
To add multiple class in the same element you can use the following format:
<div class="class1 class2 class3"></div>
Every Set has an iterator(). A normal HashSet's iterator is quite random, a TreeSet does it by sort order, a LinkedHashSet iterator iterates by insert order.
You can't replace an element in a LinkedHashSet, however. You can remove one and add another, but the new element will not be in the place of the original. In a LinkedHashMap, you can replace a value for an existing key, and then the values will still be in the original order.
Also, you can't insert at a certain position.
Maybe you'd better use an ArrayList with an explicit check to avoid inserting duplicates.
There is probably another table with a foreign key referencing the primary key you are trying to change.
To find out which table caused the error you can run SHOW ENGINE INNODB STATUS
and then look at the LATEST FOREIGN KEY ERROR
section.
Did you restart the server after you changed the config file?
Can you telnet to the server from a different machine?
Can you telnet to the server from the server itself?
telnet <ip address> 80
telnet localhost 80
Try {{model?.person.name}}
this should wait for model to not be undefined
and then render.
Angular 2 refers to this ?.
syntax as the Elvis operator. Reference to it in the documentation is hard to find so here is a copy of it in case they change/move it:
The Elvis Operator ( ?. ) and null property paths
The Angular “Elvis” operator ( ?. ) is a fluent and convenient way to guard against null and undefined values in property paths. Here it is, protecting against a view render failure if the currentHero is null.
The current hero's name is {{currentHero?.firstName}}
Let’s elaborate on the problem and this particular solution.
What happens when the following data bound title property is null?
The title is {{ title }}
The view still renders but the displayed value is blank; we see only "The title is" with nothing after it. That is reasonable behavior. At least the app doesn't crash.
Suppose the template expression involves a property path as in this next example where we’re displaying the firstName of a null hero.
The null hero's name is {{nullHero.firstName}}
JavaScript throws a null reference error and so does Angular:
TypeError: Cannot read property 'firstName' of null in [null]
Worse, the entire view disappears.
We could claim that this is reasonable behavior if we believed that the hero property must never be null. If it must never be null and yet it is null, we've made a programming error that should be caught and fixed. Throwing an exception is the right thing to do.
On the other hand, null values in the property path may be OK from time to time, especially when we know the data will arrive eventually.
While we wait for data, the view should render without complaint and the null property path should display as blank just as the title property does.
Unfortunately, our app crashes when the currentHero is null.
We could code around that problem with NgIf
<!--No hero, div not displayed, no error -->
<div *ngIf="nullHero">The null hero's name is {{nullHero.firstName}}</div>
Or we could try to chain parts of the property path with &&, knowing that the expression bails out when it encounters the first null.
The null hero's name is {{nullHero && nullHero.firstName}}
These approaches have merit but they can be cumbersome, especially if the property path is long. Imagine guarding against a null somewhere in a long property path such as a.b.c.d.
The Angular “Elvis” operator ( ?. ) is a more fluent and convenient way to guard against nulls in property paths. The expression bails out when it hits the first null value. The display is blank but the app keeps rolling and there are no errors.
<!-- No hero, no problem! -->
The null hero's name is {{nullHero?.firstName}}
It works perfectly with long property paths too:
a?.b?.c?.d
The return statement only makes sense inside functions:
def foo():
while True:
return False
I was finally able to get this to work for my needs.
The old voted up code does not run on windows 10 system (at least not mine). The referenced MS library link below provides current examples on how to make this work. My example uses them with late bindings.
https://docs.microsoft.com/en-us/windows/win32/shell/folder-getdetailsof.
The attribute codes were different on my computer and like someone mentioned above most return blank values even if they are not. I used a for loop to cycle through all of them and found out that Title and Subject can still be accessed which is more then enough for my purposes.
Private Sub MySubNamek()
Dim objShell As Object 'Shell
Dim objFolder As Object 'Folder
Set objShell = CreateObject("Shell.Application")
Set objFolder = objShell.NameSpace("E:\MyFolder")
If (Not objFolder Is Nothing) Then
Dim objFolderItem As Object 'FolderItem
Set objFolderItem = objFolder.ParseName("Myfilename.txt")
For i = 0 To 288
szItem = objFolder.GetDetailsOf(objFolderItem, i)
Debug.Print i & " - " & szItem
Next
Set objFolderItem = Nothing
End If
Set objFolder = Nothing
Set objShell = Nothing
End Sub
If using Struts, we disable direct access to the JSP files by using this tag in web.xml
<security-constraint>
<web-resource-collection>
<web-resource-name>no_access</web-resource-name>
<url-pattern>*.jsp</url-pattern>
</web-resource-collection>
<auth-constraint/>
Some HTML elements have predefined margins (namely: body
, h1
to h6
, p
, fieldset
, form
, ul
, ol
, dl
, dir
, menu
, blockquote
and dd
).
In your case it's the h1
causing your problem. It has { margin: .67em }
by default. If you set it to 0 it will remove the space.
To solve problems like these generally, I recommend using your browser's dev tools. For most browsers: right-click on the element you want to know more about and select "Inspect Element". In the "Styles" tab, at the very bottom, you have a CSS box-model. This is a great tool for visualising borders, padding and margins and what elements are the root of your styling headaches.
Seems you need to use JToggleButton
:
JToggleButton tb = new JToggleButton("push me");
tb.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
JToggleButton btn = (JToggleButton) e.getSource();
btn.setText(btn.isSelected() ? "pushed" : "push me");
}
});
public class MyMap {
public static void main(String[] args) {
Map<String, String> map1 = new HashMap<String, String>();
map1.put("key1", "value1");
map1.put("key2", "value2");
map1.put("key3", "value3");
map1.put(null, null);
Map<String, String> map2 = new HashMap<String, String>();
map2.put("key4", "value4");
map2.put("key5", "value5");
map2.put("key6", "value6");
map2.put("key3", "replaced-value-of-key3-in-map2");
// used only if map1 can be changes/updates with the same keys present in map2.
map1.putAll(map2);
// use below if you are not supposed to modify the map1.
for (Map.Entry e : map2.entrySet())
if (!map1.containsKey(e.getKey()))
map1.put(e.getKey().toString(), e.getValue().toString());
System.out.println(map1);
}}
All this is about cultures. If you have any other culture than "US English" (and also as good manners of development), you should use something like this:
var d = Convert.ToDecimal("1.2345", new CultureInfo("en-US"));
// (or 1,2345 with your local culture, for instance)
(obviously, you should replace the "en-US" with the culture of your number local culture)
the same way, if you want to do ToString()
d.ToString(new CultureInfo("en-US"));
What does the DTD have to say?
If the XML file is for communicating with other existing software (e.g., SOAP), then check that software for what it expects.
If the XML file is for serialisation or communication with non-existing software (e.g., the one you're writing), you can define it. In which case, I'd suggest something that is both easy to parse in your language(s) of choice, and easy to read for humans. e.g., if your language (whether VB.NET or C#.NET or whatever) allows you to parse ISO dates (YYYY-MM-DD) easily, that's the one I'd suggest.
You should use the following:
<td><input id="priceInput-{{orderLine.id}}" type="number" [(ngModel)]="orderLine.price"></td>
You will need to add the FormsModule
to your app.module
in the inputs
section as follows:
import { FormsModule } from '@angular/forms';
@NgModule({
declarations: [
...
],
imports: [
BrowserModule,
FormsModule
],
..
The use of the brackets around the ngModel
are as follows:
The []
show that it is taking an input from your TS file. This input should be a public member variable. A one way binding from TS to HTML.
The ()
show that it is taking output from your HTML file to a variable in the TS file. A one way binding from HTML to TS.
The [()]
are both (e.g. a two way binding)
See here for more information: https://angular.io/guide/template-syntax
I would also suggest replacing id="priceInput-{{orderLine.id}}"
with something like this [id]="getElementId(orderLine)"
where getElementId(orderLine)
returns the element Id in the TS file and can be used anywere you need to reference the element (to avoid simple bugs like calling it priceInput1
in one place and priceInput-1
in another. (if you still need to access the input by it's Id somewhere else)
INSERT INTO DestTable
SELECT * FROM SourceTable
WHERE ...
works in SQL Server
There's a method that does this for you:
def show
@city = @user.city.present?
end
The present?
method tests for not-nil
plus has content. Empty strings, strings consisting of spaces or tabs, are considered not present.
Since this pattern is so common there's even a shortcut in ActiveRecord:
def show
@city = @user.city?
end
This is roughly equivalent.
As a note, testing vs nil
is almost always redundant. There are only two logically false values in Ruby: nil
and false
. Unless it's possible for a variable to be literal false
, this would be sufficient:
if (variable)
# ...
end
This is preferable to the usual if (!variable.nil?)
or if (variable != nil)
stuff that shows up occasionally. Ruby tends to wards a more reductionist type of expression.
One reason you'd want to compare vs. nil
is if you have a tri-state variable that can be true
, false
or nil
and you need to distinguish between the last two states.
Two generic ways to do the same thing... I'm not aware of any specific open solutions to do this, but it'd be rather trivial to do.
You could write a daily or weekly cron/jenkins job to scrape the previous time period's email from the archive looking for your keyworkds/combinations. Sending a batch digest with what it finds, if anything.
But personally, I'd Setup a specific email account to subscribe to the various security lists you're interested in. Add a simple automated script to parse the new emails for various keywords or combinations of keywords, when it finds a match forward that email on to you/your team. Just be sure to keep the keywords list updated with new products you're using.
You could even do this with a gmail account and custom rules, which is what I currently do, but I have setup an internal inbox in the past with a simple python script to forward emails that were of interest.
You didn't mention the version you're using, but if you're using rc5 or rc6, that "old" style of form has been deprecated. Take a look at this for guidance on the "new" forms techniques: https://angular.io/docs/ts/latest/guide/forms.html
Single Liner to Drop, Create and Seed from Package Manager Console:
update-database -TargetMigration:0 | update-database -force
Kaboom.
The simplest approach would be to edit the webserver, most likely an Apache2 installation, configuration and give phpmyadmin a different name.
A second approach would be to limit the IP addresses from where phpmyadmin may be accessed (e.g. only local lan or localhost).
Base64
Base64 is a generic term for a number of similar encoding schemes that encode binary data by treating it numerically and translating it into a base 64 representation. The Base64 term originates from a specific MIME content transfer encoding.
Base64 encoding schemes are commonly used when there is a need to encode binary data that needs be stored and transferred over media that are designed to deal with textual data. This is to ensure that the data remains intact without modification during transport. Base64 is used commonly in a number of applications including email via MIME, and storing complex data in XML.
You can also get strange messages about the need to upgrade your working copy when there are other working copies nested into yours. I had this issue with a Symphony project were some framework folders are working copy, that I suppose have not been cleaned up properly before they were published.
In this case, just make a file search for .svn
, and delete the .svn
folders that you don't want (don't delete yours at the root of course).
If you need to print the number you can use printf
System.out.printf("%02d", num);
You can use
String.format("%02d", num);
or
(num < 10 ? "0" : "") + num;
or
(""+(100+num)).substring(1);
My mistake was simply using the CSR file instead of the CERT file.
For Microsoft Access
UPDATE TableA A
INNER JOIN TableB B
ON A.ID = B.ID
SET A.Name = B.Name
simple
COPY README.md package.json gulpfile.js __BUILD_NUMBER ./
from the doc
If multiple resources are specified, either directly or due to the use of a wildcard, then must be a directory, and it must end with a slash /.
As aready proposed in this answer and this other answer Microsoft.VisualBasic.CompilerServices.Operators.LikeString
could be a good option for simple tasks, when a RegExp is overkill. Syntax is different from RegExp and SQL LIKE operator, but it's really simple to learn (mainly because it's also very limited).
Assembly Microsoft.VisualBasic
must be added as a reference to the project to use this method.
For more information see Operators.LikeString Method and for a description of the syntax see Like Operator (Visual Basic).
It can be used as an extension method to String class:
/// <summary>
/// Visual Basic like operator. Performs simple, case insensitive, string pattern matching.
/// </summary>
/// <param name="thisString"></param>
/// <param name="pattern"> ? = Any single character. * = Zero or more characters. # = Any single digit (0–9)</param>
/// <returns>true if the string matches the pattern</returns>
public static bool Like(this string thisString, string pattern)
=> Microsoft.VisualBasic.CompilerServices.Operators
.LikeString(thisString, pattern, Microsoft.VisualBasic.CompareMethod.Text);
Check service dependencies if they are disabled.
Set those dependencies to Automatic, Start them and it should work.
IntelliJ IDEA Plugins / GenerateSerialVersionUID https://plugins.jetbrains.com/plugin/?idea&id=185
very nice, very easy to install. you can install that from plugins menu, select install from disk, select the jar file you unpacked in the lib folder. restart, control + ins, and it pops up to generate serial UID from menu. love it. :-)
You missed the each=
argument to rep()
:
R> n <- 3
R> rep(1:5, each=n)
[1] 1 1 1 2 2 2 3 3 3 4 4 4 5 5 5
R>
so your example can be done with a simple
R> rep(1:8, each=20)
Windows 7, 64 bit, no modifications to the Registry key, the location is:
C:\Users[Current User when app crashed]\AppData\Local\Microsoft\Windows\WER\ReportArchive
You need to set JAVA_HOME to your jdk7 home directory, for example on Microsoft Windows:
or on OS X:
simple as this
myObj.name = value;
Open the file (if you are using multiple tab groups, make sure your file is selected).
Menu Window ? Split (alternately, there's this tiny nub just above the editor's vertical scroll bar - grab it and drag down)
This gives you two (horizontal) views of the same file. Beware that any edit-actions will reflect on both views.
Once you are done, grab the splitter and drag it up all the way (or menu Window ? Remove Split).
The following should work:
public static void main(String[] args)
{
final String title = "Test Window";
final int width = 1200;
final int height = width / 16 * 9;
//Creating the frame.
JFrame frame = new JFrame(title);
frame.setSize(width, height);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocationRelativeTo(null);
frame.setResizable(false);
frame.setVisible(true);
//Creating the canvas.
Canvas canvas = new Canvas();
canvas.setSize(width, height);
canvas.setBackground(Color.BLACK);
canvas.setVisible(true);
canvas.setFocusable(false);
//Putting it all together.
frame.add(canvas);
canvas.createBufferStrategy(3);
boolean running = true;
BufferStrategy bufferStrategy;
Graphics graphics;
while (running) {
bufferStrategy = canvas.getBufferStrategy();
graphics = bufferStrategy.getDrawGraphics();
graphics.clearRect(0, 0, width, height);
graphics.setColor(Color.GREEN);
graphics.drawString("This is some text placed in the top left corner.", 5, 15);
bufferStrategy.show();
graphics.dispose();
}
}
Personally, I found that, since we maintain a ngRoutes
collection (long story) i find the most enjoyment from:
GOTO(ri) {
this.router.navigate(this.ngRoutes[ri]);
}
I actually use it as part of one of our interview questions. This way, I can get a near-instant read at who's been developing forever by watching who twitches when they run into GOTO(1)
for Homepage redirection.
Role attribute mainly improve accessibility for people using screen readers. For several cases we use it such as accessibility, device adaptation,server-side processing, and complex data description. Know more click: https://www.w3.org/WAI/PF/HTML/wiki/RoleAttribute.
For anyone that is still stuck on this issue after trying the above. If you are right-clicking on the database and going to tasks->import, then here is the issue. Go to your start menu and under sql server, find the x64 bit import export wizard and try that. Worked like a charm for me, but it took me FAR too long to find it Microsoft!
Using HTML5 you can add the attribute 'download' to your links.
<a href="/path/to/image.png" download>
Compliant browsers will then prompt to download the image with the same file name (in this example image.png).
If you specify a value for this attribute, then that will become the new filename:
<a href="/path/to/image.png" download="AwesomeImage.png">
UPDATE: As of spring 2018 this is no longer possible for cross-origin href
s. So if you want to create <a href="https://i.imgur.com/IskAzqA.jpg" download>
on a domain other than imgur.com it will not work as intended. Chrome deprecations and removals announcement
If you want the transition work for whole application you can create a rootacivity
and inherit it in the activity you need. In Root Activity's onCreate call overridePendingTransition
with desired direction. And onStart
call overridePendingTransition
with other direction if activity is resumed. Here I am giving full running code below.Correct me if I am wrong.
create this xml file on your anim folder
anim_slide_in_left.xml
<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android" >
<translate
android:duration="600"
android:fromXDelta="100%"
android:toXDelta="0%" >
</translate>
</set>
anim_slide_in_right.xml
<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android" >
<translate
android:duration="600"
android:fromXDelta="-100%"
android:toXDelta="0%" >
</translate>
</set>
anim_slide_out_left.xml
<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android" >
<translate
android:duration="600"
android:fromXDelta="0%"
android:toXDelta="-100%" >
</translate>
</set>
anim_slide_out_right.xml
<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android" >
<translate
android:duration="600"
android:fromXDelta="0%"
android:toXDelta="100%" >
</translate>
</set>
RootActivity
import android.app.Activity;
import android.os.Bundle;
public class RootActivity extends Activity {
int onStartCount = 0;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
onStartCount = 1;
if (savedInstanceState == null) // 1st time
{
this.overridePendingTransition(R.anim.anim_slide_in_left,
R.anim.anim_slide_out_left);
} else // already created so reverse animation
{
onStartCount = 2;
}
}
@Override
protected void onStart() {
// TODO Auto-generated method stub
super.onStart();
if (onStartCount > 1) {
this.overridePendingTransition(R.anim.anim_slide_in_right,
R.anim.anim_slide_out_right);
} else if (onStartCount == 1) {
onStartCount++;
}
}
}
FirstActivity
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
public class FirstActivity extends RootActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
TextView tv = (TextView) findViewById(R.id.tvTitle);
tv.setText("First Activity");
Button bt = (Button) findViewById(R.id.buttonNext);
bt.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
Intent i = new Intent(FirstActivity.this, SecondActivity.class);
startActivity(i);
}
});
}
}
SecondActivity
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
public class SecondActivity extends RootActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
TextView tv = (TextView) findViewById(R.id.tvTitle);
tv.setText("Second Activity");
Button bt = (Button) findViewById(R.id.buttonNext);
bt.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
Intent i = new Intent(SecondActivity.this, ThirdActivity.class);
startActivity(i);
}
});
}
}
ThirdActivity
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
public class ThirdActivity extends RootActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
TextView tv = (TextView) findViewById(R.id.tvTitle);
tv.setText("Third Activity");
Button bt = (Button) findViewById(R.id.buttonNext);
bt.setText("previous");
bt.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
finish();
}
});
}
}
and finally Manifest
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.transitiontest"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="18" />
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name="com.example.transitiontest.FirstActivity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name="com.example.transitiontest.SecondActivity"
android:label="@string/app_name" >
</activity>
<activity
android:name="com.example.transitiontest.ThirdActivity"
android:label="@string/app_name" >
</activity>
</application>
</manifest>
You can probably just use the true
command:
if [ "$a" -ge 10 ]; then
true
elif [ "$a" -le 5 ]; then
echo "1"
else
echo "2"
fi
An alternative, in your example case (but not necessarily everywhere) is to re-order your if/else:
if [ "$a" -le 5 ]; then
echo "1"
elif [ "$a" -lt 10 ]; then
echo "2"
fi
Use jQuery
Look how easy it would be if you did.
Example:
$('#td1').html('hello world');
I guess this is essentially putting it in a string, but this avoids the rounding error:
import decimal
def display(x):
digits = 15
temp = str(decimal.Decimal(str(x) + '0' * digits))
return temp[:temp.find('.') + digits + 1]
Here's how you can do it with Java 8's Streams:
mySet.stream().sorted().collect(Collectors.toList());
or with a custom comparator:
mySet.stream().sorted(myComparator).collect(Collectors.toList());
If you want to apply rotation on the axes object, the easiest way is using tick_params
. For example.
ax.tick_params(axis='x', labelrotation=90)
Matplotlib documentation reference here.
This is useful when you have an array of axes as returned by plt.subplots
, and it is more convenient than using set_xticks
because in that case you need to also set the tick labels, and also more convenient that those that iterate over the ticks (for obvious reasons)
To improve upon the answer given by derobert,
You can determine what your OS connection limit is by catting nf_conntrack_max.
For example: cat /proc/sys/net/netfilter/nf_conntrack_max
You can use the following script to count the number of tcp connections to a given range of tcp ports. By default 1-65535.
This will confirm whether or not you are maxing out your OS connection limit.
Here's the script.
#!/bin/bash
OS=$(uname)
case "$OS" in
'SunOS')
AWK=/usr/bin/nawk
;;
'Linux')
AWK=/bin/awk
;;
'AIX')
AWK=/usr/bin/awk
;;
esac
netstat -an | $AWK -v start=1 -v end=65535 ' $NF ~ /TIME_WAIT|ESTABLISHED/ && $4 !~ /127\.0\.0\.1/ {
if ($1 ~ /\./)
{sip=$1}
else {sip=$4}
if ( sip ~ /:/ )
{d=2}
else {d=5}
split( sip, a, /:|\./ )
if ( a[d] >= start && a[d] <= end ) {
++connections;
}
}
END {print connections}'
Just download and install "Samsung Kies" from this link. and everything would work as required.
Before installing, uninstall the drivers you have installed for your device.
Update:
Two possible solutions:
You need to dig a bit deeper into the api to do this:
from matplotlib import pyplot as plt
plt.plot(range(5))
plt.xlim(-3, 3)
plt.ylim(-3, 3)
plt.gca().set_aspect('equal', adjustable='box')
plt.draw()
Try this:
if [ ${STATUS} -ne 100 -a "${STRING}" = "${VALUE}" ]
or
if [ ${STATUS} -ne 100 ] && [ "${STRING}" = "${VALUE}" ]
pip install python-dateutil
>>> a = "2019-06-27T02:14:49.443814497Z"
>>> dateutil.parser.parse(a)
datetime.datetime(2019, 6, 27, 2, 14, 49, 443814, tzinfo=tzutc())
Alternatively, in python 3.6+, you can generate Unicode superscript and copy paste that in your code:
ax1.set_ylabel('Rate (min?¹)')
Try cleaning the project:
1. shift + cmd + k
2. shift + cmd + Alt + k
Then try to run your project again. Hope this will fix the problem.
Isn't it better with a group by? Something like:
SELECT COUNT(*) FROM t1 GROUP BY keywork;
A tool to use here is awk:
cat file | awk 'BEGIN{ found=0} /TERMINATE/{found=1} {if (found) print }'
How does this work:
The other solutions might consume a lot of memory if you use them on very large files.
Here is the new dependency (August 2017)
<!-- https://mvnrepository.com/artifact/org.glassfish.jersey.core/jersey-common -->
<dependency>
<groupId>org.glassfish.jersey.core</groupId>
<artifactId>jersey-common</artifactId>
<version>2.0-m03</version>
</dependency>
You need to include the reference to the assembly System.Web.Mvc in you project.
you may not have the System.Web.Mvc in your C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework.NETFramework\v4.0
So you need to add it and then to include it as reference to your projrect
import * as utils from './utils.js';
If you do the above, you will be able to use functions in utils.js as
utils.someFunction()
Looking in the headers sent...
res.send uses content-type:text/html
res.json uses content-type:application/json
edit: send actually changes what is sent based on what it's given, so strings are sent as text/html, but it you pass it an object it emits application/json.
1: The arguments to the callback functions are reversed.
.each()
's, $.each()
's, and .map()
's callback function take the index first, and then the element
function (index, element)
$.map()
's callback has the same arguments, but reversed
function (element, index)
2: .each()
, $.each()
, and .map()
do something special with this
each()
calls the function in such a way that this
points to the current element. In most cases, you don't even need the two arguments in the callback function.
function shout() { alert(this + '!') }
result = $.each(['lions', 'tigers', 'bears'], shout)
// result == ['lions', 'tigers', 'bears']
For $.map()
the this
variable refers to the global window object.
3: map()
does something special with the callback's return value
map()
calls the function on each element, and stores the result in a new array, which it returns. You usually only need to use the first argument in the callback function.
function shout(el) { return el + '!' }
result = $.map(['lions', 'tigers', 'bears'], shout)
// result == ['lions!', 'tigers!', 'bears!']
Goto File -> Project Structure -> Modules -> app -> Dependencies Tab -> Click on +(button) -> Select File Dependency - > Select jar file in the lib folder
This steps will automatically add your dependency to gralde
Very Simple
I recently had to do this in R:
inversionNumber <- function(x){
mergeSort <- function(x){
if(length(x) == 1){
inv <- 0
} else {
n <- length(x)
n1 <- ceiling(n/2)
n2 <- n-n1
y1 <- mergeSort(x[1:n1])
y2 <- mergeSort(x[n1+1:n2])
inv <- y1$inversions + y2$inversions
x1 <- y1$sortedVector
x2 <- y2$sortedVector
i1 <- 1
i2 <- 1
while(i1+i2 <= n1+n2+1){
if(i2 > n2 || i1 <= n1 && x1[i1] <= x2[i2]){
x[i1+i2-1] <- x1[i1]
i1 <- i1 + 1
} else {
inv <- inv + n1 + 1 - i1
x[i1+i2-1] <- x2[i2]
i2 <- i2 + 1
}
}
}
return (list(inversions=inv,sortedVector=x))
}
r <- mergeSort(x)
return (r$inversions)
}
Broadly speaking, there are three groups of people out there.
Those who will not buy your software and resort to cracks, or if they don't find any, not use your software at all. Don't expect to make any money from this group. They rely either on their own skills or on crackers (who tend to prioritize their time depending on your useful and how big your audience is. The more useful, the sooner a crack will be available).
The group of legitimate users who will buy (pay for) your software, irrespective of what protection mechanism you use. Don't make life hard for your legitimate users by using an elaborate protection mechanism since they are going to pay for it in any case. A complex protection mechanism can easily spoil the user experience and you don't want this happening to this group. Personally, I'd vote against any hardware solution, which adds to the cost of your software.
A minority who will resort to "unethical" cracking and will only pay for your software because its features are protected by a licensing mechanism. You probably don't want to make it exceedingly easy for this group to circumvent your protection. However, all that effort you spend on protecting your software will pay back, depending on how big this group of people is. This entirely depends on the type of software you're building.
Given what you've said, if you think there is a large enough minority who can be pushed into buying your software, go ahead and implement some form of protection. Think about how much money you can make from this minority versus the time you spend working on the protection, or the amount you spend on a third party protection API/tool.
If you like to implement a solution of your own, using public-key cryptography is a good way (as opposed to symmetric algorithms) to prevent easy hacks. You could for instance digitally sign your license (serial no, or license file). The only way to get around this would then be to decompile, alter and recompile the code (which you could make harder using techniques such as those suggested in Simucal's answer).
The function () use () {}
is like closure for PHP.
Without use
, function cannot access parent scope variable
$s = "hello";
$f = function () {
echo $s;
};
$f(); // Notice: Undefined variable: s
$s = "hello";
$f = function () use ($s) {
echo $s;
};
$f(); // hello
The use
variable's value is from when the function is defined, not when called
$s = "hello";
$f = function () use ($s) {
echo $s;
};
$s = "how are you?";
$f(); // hello
use
variable by-reference with &
$s = "hello";
$f = function () use (&$s) {
echo $s;
};
$s = "how are you?";
$f(); // how are you?
Use driver.save_screenshot('/path/to/file')
or driver.get_screenshot_as_file('/path/to/file')
:
import selenium.webdriver as webdriver
import contextlib
@contextlib.contextmanager
def quitting(thing):
yield thing
thing.quit()
with quitting(webdriver.Firefox()) as driver:
driver.implicitly_wait(10)
driver.get('http://www.google.com')
driver.get_screenshot_as_file('/tmp/google.png')
# driver.save_screenshot('/tmp/google.png')
This will disable dragging for an image in all browsers, while preserving other events such as click and hover. Works as long as any of HTML5, JS, or CSS are available.
<img draggable="false" onmousedown="return false" style="user-drag: none" />
If you're confident the user will have JS, you only need to use the JS attribute, etc. For more flexibility, look into ondragstart, onselectstart, and some WebKit tap/touch CSS.
ES2015 onwards:
From ES6/ES2015, we have default parameters in the language specification. So we can just do something simple like,
function A(a, b = 4, c = 5) {
}
or combined with ES2015 destructuring,
function B({c} = {c: 2}, [d, e] = [3, 4]) {
}
For detailed explanation,
https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Functions/default_parameters
Default function parameters allow formal parameters to be initialized with default values if no value or undefined is passed.
Pre ES2015:
If you're going to handle values which are NOT Numbers, Strings, Boolean, NaN
, or null
you can simply use
(So, for Objects, Arrays and Functions that you plan never to send null
, you can use)
param || DEFAULT_VALUE
for example,
function X(a) {
a = a || function() {};
}
Though this looks simple and kinda works, this is restrictive and can be an anti-pattern because ||
operates on all falsy values (""
, null
, NaN
, false
, 0
) too - which makes this method impossible to assign a param the falsy value passed as the argument.
So, in order to handle only undefined
values explicitly, the preferred approach would be,
function C(a, b) {
a = typeof a === 'undefined' ? DEFAULT_VALUE_A : a;
b = typeof b === 'undefined' ? DEFAULT_VALUE_B : b;
}
To add to tacaswell's answer, the colorbar()
function has an optional cax
input you can use to pass an axis on which the colorbar should be drawn. If you are using that input, you can directly set a label using that axis.
import matplotlib.pyplot as plt
from mpl_toolkits.axes_grid1 import make_axes_locatable
fig, ax = plt.subplots()
heatmap = ax.imshow(data)
divider = make_axes_locatable(ax)
cax = divider.append_axes('bottom', size='10%', pad=0.6)
cb = fig.colorbar(heatmap, cax=cax, orientation='horizontal')
cax.set_xlabel('data label') # cax == cb.ax
There seems to be a really easy solution when dealing with data type issues.
Basically, at the end of Excel connection string, add ;IMEX=1;"
Provider=Microsoft.Jet.OLEDB.4.0;Data Source=\\YOURSERVER\shared\Client Projects\FOLDER\Data\FILE.xls;Extended Properties="EXCEL 8.0;HDR=YES;IMEX=1";
This will resolve data type issues such as columns where values are mixed with text and numbers.
To get to connection property, right click on Excel connection manager below control flow and hit properties. It'll be to the right under solution explorer. Hope that helps.
Gimp can be used to convert SVGs with primitives (e.g. rects, circles, etc.) into a single path which can be used within HTML5.
.svg
file with any tool of choice e.g. Illustrator. Don't worry if the SVG output is messy for now, Gimp will clean it upCheck both the Import Paths and Merge imported paths options
<path d="copy this text here" />
The Chromatable jquery plugin allows a fixed header (or top row) with widths that allow percentages--granted, only a percentage of 100%.
http://www.chromaloop.com/posts/chromatable-jquery-plugin
I can't think of how you could do this without javascript.
update: new link -> http://www.jquery-plugins.info/chromatable-00012248.htm
I had same issue with my Eclipse and as a solution, I created new project, copied all resources manually (using windows copy/paste) to new project, deleted old project and that's it.
Sometimes, this happens due to improper System shutdown and Eclipse workspace started facing similar issues.
Hope it will work.
// Create a DataTable and add two Columns to it
DataTable dt=new DataTable();
dt.Columns.Add("Name",typeof(string));
dt.Columns.Add("Age",typeof(int));
// Create a DataRow, add Name and Age data, and add to the DataTable
DataRow dr=dt.NewRow();
dr["Name"]="Mohammad"; // or dr[0]="Mohammad";
dr["Age"]=24; // or dr[1]=24;
dt.Rows.Add(dr);
// Create another DataRow, add Name and Age data, and add to the DataTable
dr=dt.NewRow();
dr["Name"]="Shahnawaz"; // or dr[0]="Shahnawaz";
dr["Age"]=24; // or dr[1]=24;
dt.Rows.Add(dr);
// DataBind to your UI control, if necessary (a GridView, in this example)
GridView1.DataSource=dt;
GridView1.DataBind();
Here is a working version using v3
of docker-compose.yml
. The key is the volumes directive:
mysql:
image: mysql:5.6
ports:
- "3306:3306"
environment:
MYSQL_ROOT_PASSWORD: root
MYSQL_USER: theusername
MYSQL_PASSWORD: thepw
MYSQL_DATABASE: mydb
volumes:
- ./data:/docker-entrypoint-initdb.d
In the directory that I have my docker-compose.yml
I have a data
dir that contains .sql
dump files. This is nice because you can have a .sql
dump file per table.
I simply run docker-compose up
and I'm good to go. Data automatically persists between stops. If you want remove the data and "suck in" new .sql
files run docker-compose down
then docker-compose up
.
If anyone knows how to get the mysql
docker to re-process files in /docker-entrypoint-initdb.d
without removing the volume, please leave a comment and I will update this answer.
for (Map.Entry<String, ArrayList<String>> entry : test1.entrySet()) {
String key = entry.getKey();
ArrayList<String> value = entry.getValue();
// now work with key and value...
}
By the way, you should really declare your variables as the interface type instead, such as Map<String, List<String>>
.
This is an initialization list. It'll initialize the members before the constructor body is run. Consider
class Foo {
public:
string str;
Foo(string &p)
{
str = p;
};
};
vs
class Foo {
public:
string str;
Foo(string &p): str(p) {};
};
In the first example, str will be initialized by its no-argument constructor
string();
before the body of the Foo constructor. Inside the foo constructor, the
string& operator=( const string& s );
will be called on 'str' as you do str = p;
Wheras in the second example, str will be initialized directly by calling its constructor
string( const string& s );
with 'p' as an argument.
Refer to Section 8.3 of this SAML core pdf of oasis SAML specification.
SP and IdP usually communicate each other about a subject. That subject should be identified through a NAME-IDentifier , which should be in some format so that It is easy for the other party to identify it based on the Format.
All these
1.urn:oasis:names:tc:SAML:1.1:nameid-format:unspecified [default]
2.urn:oasis:names:tc:SAML:1.1:nameid-format:emailAddress
3.urn:oasis:names:tc:SAML:2.0:nameid-format:persistent
4.urn:oasis:names:tc:SAML:2.0:nameid-format:transient
are format for the Name Identifiers.
Transient is for [section 8.3.8 of SAML Core]
Indicates that the content of the element is an identifier with transient semantics and SHOULD be treated as an opaque and temporary value by the relying party.
Unspecified can be used and it purely depends on the entities implementation on their own wish.
An SMS Push is a message to tell the terminal to initiate the session. This happens because you can't initiate an IP session simply because you don't know the IP Adress of the mobile terminal. Mostly used to send a few lines of data to end recipient, to the effect of sending information, or reminding of events.
WAP Push is an SMS within the header of which is included a link to a WAP address. On receiving a WAP Push, the compatible mobile handset automatically gives the user the option to access the WAP content on his handset. The WAP Push directs the end-user to a WAP address where content is stored ready for viewing or downloading onto the handset. This wap address may be a page or a WAP site.
The user may “take action” by using a developer-defined soft-key to immediately activate an application to accomplish a specific task, such as downloading a picture, making a purchase, or responding to a marketing offer.
public class MainActivity extends Activity {
private WebView webView1;
Button google;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
google = (Button) findViewById(R.id.google);
google.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
webView1 = (WebView) findViewById(R.id.webView);
webView1.getSettings().setJavaScriptEnabled(true);
webView1.loadUrl("http://www.google.co.in/");
}
});
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
As of right now, I do not know of any. It appears the code academy folks have set their sites on Ruby on Rails. They do not rule Java out of the picture however.
I'm quite late to the party, but one approach is to use a static inner class to unwrap values:
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
class Scratch {
private final String aString;
private final String bString;
private final String cString;
private final static String jsonString;
static {
jsonString = "{\n" +
" \"wrap\" : {\n" +
" \"A\": \"foo\",\n" +
" \"B\": \"bar\",\n" +
" \"C\": \"baz\"\n" +
" }\n" +
"}";
}
@JsonCreator
Scratch(@JsonProperty("A") String aString,
@JsonProperty("B") String bString,
@JsonProperty("C") String cString) {
this.aString = aString;
this.bString = bString;
this.cString = cString;
}
@Override
public String toString() {
return "Scratch{" +
"aString='" + aString + '\'' +
", bString='" + bString + '\'' +
", cString='" + cString + '\'' +
'}';
}
public static class JsonDeserializer {
private final Scratch scratch;
@JsonCreator
public JsonDeserializer(@JsonProperty("wrap") Scratch scratch) {
this.scratch = scratch;
}
public Scratch getScratch() {
return scratch;
}
}
public static void main(String[] args) throws JsonProcessingException {
ObjectMapper objectMapper = new ObjectMapper();
Scratch scratch = objectMapper.readValue(jsonString, Scratch.JsonDeserializer.class).getScratch();
System.out.println(scratch.toString());
}
}
However, it's probably easier to use objectMapper.configure(SerializationConfig.Feature.UNWRAP_ROOT_VALUE, true);
in conjunction with @JsonRootName("aName")
, as pointed out by pb2q
gridview itself has a method that checks if the datasource you are binding it to is empty, it lets you display something else.
You need to set the correct content type and stringify your object.
var arr = {City:'Moscow', Age:25};
$.ajax({
url: "Ajax.ashx",
type: "POST",
data: JSON.stringify(arr),
dataType: 'json',
async: false,
contentType: 'application/json; charset=utf-8',
success: function(msg) {
alert(msg);
}
});
If your ListView row item refers to a separate XML file, be sure to add android:longClickable="true"
to that layout file in addition to setting setOnItemLongClickListener()
to your ListView.
Since Spark 1.5 you can use a number of date processing functions:
pyspark.sql.functions.year
pyspark.sql.functions.month
pyspark.sql.functions.dayofmonth
pyspark.sql.functions.dayofweek()
pyspark.sql.functions.dayofyear
pyspark.sql.functions.weekofyear()
import datetime
from pyspark.sql.functions import year, month, dayofmonth
elevDF = sc.parallelize([
(datetime.datetime(1984, 1, 1, 0, 0), 1, 638.55),
(datetime.datetime(1984, 1, 1, 0, 0), 2, 638.55),
(datetime.datetime(1984, 1, 1, 0, 0), 3, 638.55),
(datetime.datetime(1984, 1, 1, 0, 0), 4, 638.55),
(datetime.datetime(1984, 1, 1, 0, 0), 5, 638.55)
]).toDF(["date", "hour", "value"])
elevDF.select(
year("date").alias('year'),
month("date").alias('month'),
dayofmonth("date").alias('day')
).show()
# +----+-----+---+
# |year|month|day|
# +----+-----+---+
# |1984| 1| 1|
# |1984| 1| 1|
# |1984| 1| 1|
# |1984| 1| 1|
# |1984| 1| 1|
# +----+-----+---+
You can use simple map
as with any other RDD:
elevDF = sqlContext.createDataFrame(sc.parallelize([
Row(date=datetime.datetime(1984, 1, 1, 0, 0), hour=1, value=638.55),
Row(date=datetime.datetime(1984, 1, 1, 0, 0), hour=2, value=638.55),
Row(date=datetime.datetime(1984, 1, 1, 0, 0), hour=3, value=638.55),
Row(date=datetime.datetime(1984, 1, 1, 0, 0), hour=4, value=638.55),
Row(date=datetime.datetime(1984, 1, 1, 0, 0), hour=5, value=638.55)]))
(elevDF
.map(lambda (date, hour, value): (date.year, date.month, date.day))
.collect())
and the result is:
[(1984, 1, 1), (1984, 1, 1), (1984, 1, 1), (1984, 1, 1), (1984, 1, 1)]
Btw: datetime.datetime
stores an hour anyway so keeping it separately seems to be a waste of memory.
I had the same issue. I am currently using Asp.net Core 2.2. I solved this problem with the following piece of code.
using Microsoft.AspNetCore.Identity;
var user = await _userManager.FindByEmailAsync(User.Identity.Name);
I hope this will be useful to someone.
testvar[1] is the value of that array index, which is the number 2. Numbers don't have a length property, and you're checking for 2.length which is undefined. If you want the length of the array just check testvar.length
Try using this. It is the fastest and best ffmpeg-way I have figure it out:
ffmpeg -ss 00:01:00 -i input.mp4 -to 00:02:00 -c copy output.mp4
This command trims your video in seconds!
Explanation of the command:
-i: This specifies the input file. In that case, it is (input.mp4).
-ss: Used with -i, this seeks in the input file (input.mp4) to position.
00:01:00: This is the time your trimmed video will start with.
-to: This specifies duration from start (00:01:40) to end (00:02:12).
00:02:00: This is the time your trimmed video will end with.
-c copy: This is an option to trim via stream copy. (NB: Very fast)
The timing format is: hh:mm:ss
Please note that the current highly upvoted answer is outdated and the trim would be extremely slow. For more information, look at this official ffmpeg article.
It's empty by default. You'll find a bunch of settings in /etc/apache2/apache2.conf
.
In there it does this:
# Include all the user configurations:
Include httpd.conf
Don't change any environment variables
It was the installer which caused the issue and did not install all the required file.
I just repaired the NODEJS setup on windows 7 and it works very well. May be you can reinstall, just incase something does not work.
DECLARE @tab AS TABLE (col1 VARCHAR(10), col2 varchar(10))
INSERT into @tab EXECUTE sp_executesql N'
SELECT 1 AS col1, 2 AS col2
UNION ALL
SELECT 1 AS col1, 2 AS col2
UNION ALL
SELECT 1 AS col1, 2 AS col2'
SELECT * FROM @tab
The answer is in the documentation:
Real partial mocks (Since 1.8.0)
Finally, after many internal debates & discussions on the mailing list, partial mock support was added to Mockito. Previously we considered partial mocks as code smells. However, we found a legitimate use case for partial mocks.
Before release 1.8 spy() was not producing real partial mocks and it was confusing for some users. Read more about spying: here or in javadoc for spy(Object) method.
callRealMethod()
was introduced after spy()
, but spy() was left there of course, to ensure backward compatibility.
Otherwise, you're right: all the methods of a spy are real unless stubbed. All the methods of a mock are stubbed unless callRealMethod()
is called. In general, I would prefer using callRealMethod()
, because it doesn't force me to use the doXxx().when()
idiom instead of the traditional when().thenXxx()
I also wanted similar functionality where I have a File Input Control with display:none
and a Button control where I wanted to trigger click event of File Input Control when I click on the button, below is the code to do so
<input type="button" (click)="fileInput.click()" class="btn btn-primary" value="Add From File">
<input type="file" style="display:none;" #fileInput/>
as simple as that and it's working flawlessly...
You could also use a URI template. If you structured your request into a restful URL Spring could parse the provided value from the url.
HTML
<li>
<a id="byParameter"
class="textLink" href="<c:url value="/mapping/parameter/bar />">By path, method,and
presence of parameter</a>
</li>
Controller
@RequestMapping(value="/mapping/parameter/{foo}", method=RequestMethod.GET)
public @ResponseBody String byParameter(@PathVariable String foo) {
//Perform logic with foo
return "Mapped by path + method + presence of query parameter! (MappingController)";
}
The Cause
Running your app in the Simulator before the previously running app has completely stopped.
The Fix
Wait until you see the Stop button become active again before running again.
(I'm using Xcode 4.2.1. This problem happened very frequently when I upgraded to OS X Lion).
var employee = (from res in _db.EMPLOYEEs
where (res.EMAIL == givenInfo || res.USER_NAME == givenInfo)
select new {res.EMAIL, res.USERNAME} );
OR you can use
var employee = (from res in _db.EMPLOYEEs
where (res.EMAIL == givenInfo || res.USER_NAME == givenInfo)
select new {email=res.EMAIL, username=res.USERNAME} );
Explanation :
Select employee from the db as res.
Filter the employee details as per the where condition.
Select required fields from the employee object by creating an Anonymous object using new { }
Just wrap floated elements in a <div>
and give it this CSS:
.wrapper {
display: table;
margin: auto;
}
And make sure you download the Windows7.1 SDK, not just the Windows 7 one. That caused me a lot of head pounding.
I have a website project.
In my case I had moved the solution file to another path and that cause the problem. I restored it to the previous location and the problem went out.
Once you have applied all the code tricks above (forward declarations, reducing header inclusion to the minimum in public headers, pushing most details inside the implementation file with Pimpl...) and nothing else can be gained language-wise, consider your build system. If you use Linux, consider using distcc (distributed compiler) and ccache (cache compiler).
The first one, distcc, executes the preprocessor step locally and then sends the output to the first available compiler in the network. It requires the same compiler and library versions in all the configured nodes in the network.
The latter, ccache, is a compiler cache. It again executes the preprocessor and then check with an internal database (held in a local directory) if that preprocessor file has already been compiled with the same compiler parameters. If it does, it just pops up the binary and output from the first run of the compiler.
Both can be used at the same time, so that if ccache does not have a local copy it can send it trough the net to another node with distcc, or else it can just inject the solution without further processing.
I had the same error, in my case adding method_decorator helps:
from django.views.decorators.csrf import csrf_protect
from django.utils.decorators import method_decorator
method_decorator(csrf_protect)
def post(self, request):
...
Here's a piece of code that checks whether a number is an integer or not, it works for both Python 2 and Python 3.
import sys
if sys.version < '3':
integer_types = (int, long,)
else:
integer_types = (int,)
isinstance(yourNumber, integer_types) # returns True if it's an integer
isinstance(yourNumber, float) # returns True if it's a float
Notice that Python 2 has both types int
and long
, while Python 3 has only type int
. Source.
If you want to check whether your number is a float
that represents an int
, do this
(isinstance(yourNumber, float) and (yourNumber).is_integer()) # True for 3.0
If you don't need to distinguish between int and float, and are ok with either, then ninjagecko's answer is the way to go
import numbers
isinstance(yourNumber, numbers.Real)
Remove the FormsModule from Declaration:[] and Add the FormsModule in imports:[]
@NgModule({
declarations: [
AppComponent
],
imports: [
BrowserModule,
FormsModule
],
providers: [],
bootstrap: [AppComponent]
})
You should declare it with declarations array(meta property) of @NgModule
as shown below (RC5 and later
),
import {CoursesComponent} from './courses.component';
@NgModule({
imports: [ BrowserModule],
declarations: [ AppComponent,CoursesComponent], //<----here
providers: [],
bootstrap: [ AppComponent ]
})
This was how I solved it:
mysql> DROP DATABASE mydatabase;
ERROR 1010 (HY000): Error dropping database (can't rmdir '.\mydatabase', errno: 13)
mysql>
I went to delete this directory: C:\...\UniServerZ\core\mysql\data\mydatabase
.
mysql> DROP DATABASE mydatabase;
ERROR 1008 (HY000): Can't drop database 'mydatabase'; database doesn't exist
I find that this usually occurs to me when i still have a method declaration in an interface, which a class implements, but that i had later removed and had forgotten to remove it from the interface as well. I usually just save the entire solution every 30mins n then just revert back to an earlier version if i cant find the error.
Look at your function s definition. If you forget using "()" after function declaration somewhere, you ll get plenty of errors with the same format:
... ??: class, interface, or enum expected ...
And also you have forgot closing bracket after your class or function definition ends. But note that these missing bracket, is not the only reason for this type of error.
The change event is triggered on the <select>
element, not the <option>
element. However, that's not the only problem. The way you defined the change
function won't cause a rerender of the component. It seems like you might not have fully grasped the concept of React yet, so maybe "Thinking in React" helps.
You have to store the selected value as state and update the state when the value changes. Updating the state will trigger a rerender of the component.
var MySelect = React.createClass({
getInitialState: function() {
return {
value: 'select'
}
},
change: function(event){
this.setState({value: event.target.value});
},
render: function(){
return(
<div>
<select id="lang" onChange={this.change} value={this.state.value}>
<option value="select">Select</option>
<option value="Java">Java</option>
<option value="C++">C++</option>
</select>
<p></p>
<p>{this.state.value}</p>
</div>
);
}
});
React.render(<MySelect />, document.body);
Also note that <p>
elements don't have a value
attribute. React/JSX simply replicates the well-known HTML syntax, it doesn't introduce custom attributes (with the exception of key
and ref
). If you want the selected value to be the content of the <p>
element then simply put inside of it, like you would do with any static content.
Learn more about event handling, state and form controls:
I've been there too and searched everywhere how /usr/libexec/java_home
works but I couldn't find any information on how it determines the available Java Virtual Machines it lists.
I've experimented a bit and I think it simply executes a ls /Library/Java/JavaVirtualMachines
and then inspects the ./<version>/Contents/Info.plist
of all runtimes it finds there.
It then sorts them descending by the key JVMVersion
contained in the Info.plist and by default it uses the first entry as its default JVM.
I think the only thing we might do is to change the plist: sudo vi /Library/Java/JavaVirtualMachines/jdk1.8.0.jdk/Contents/Info.plist
and then modify the JVMVersion from 1.8.0
to something else that makes it sort it to the bottom instead of the top, like !1.8.0
.
Something like:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
...
<dict>
...
<key>JVMVersion</key>
<string>!1.8.0</string> <!-- changed from '1.8.0' to '!1.8.0' -->`
and then it magically disappears from the top of the list:
/usr/libexec/java_home -verbose
Matching Java Virtual Machines (3):
1.7.0_45, x86_64: "Java SE 7" /Library/Java/JavaVirtualMachines/jdk1.7.0_45.jdk/Contents/Home
1.7.0_09, x86_64: "Java SE 7" /Library/Java/JavaVirtualMachines/jdk1.7.0_09.jdk/Contents/Home
!1.8.0, x86_64: "Java SE 8" /Library/Java/JavaVirtualMachines/jdk1.8.0.jdk/Contents/Home
Now you will need to logout/login and then:
java -version
java version "1.7.0_45"
:-)
Of course I have no idea if something else breaks now or if the 1.8.0-ea version of java still works correctly.
You probably should not do any of this but instead simply deinstall 1.8.0.
However so far this has worked for me.
I use this script to check if a file exists (also it handles the cross origin issue):
$.ajax(url, {
method: 'GET',
dataType: 'jsonp'
})
.done(function(response) {
// exists code
}).fail(function(response) {
// doesnt exist
})
Note that the following syntax error is thrown when the file being checked doesn't contain JSON.
Uncaught SyntaxError: Unexpected token <
I also ran into this problem, and was able to work around a similar EOF error using:
read.table("....csv", sep=",", ...)
Notice that the separator parameter is defined within the more general read.table()
.
In general, the way to deal with circular dependencies is to use setter injection.
I tried the setter injection code that you posted, and it worked for me. I would imagine the reason you are getting the exception is because Bean1 and Bean2 are in the com.myapp.beans package, and you don't have component scanning enabled for that package.
You'd need to add the following to your spring configuration:
<context:component-scan base-package="com.bullethq.accounts.web"/>
or move the beans to a package which is being automatically scanned by Spring.
Marc Charbonneau wrote:
Keep in mind that @"%d" will only work on 32 bit. Once you start using NSInteger for compatibility if you ever compile for a 64 bit platform, you should use @"%ld" as your format specifier.
Interesting, thanks for the tip, I was using @"%d" with my NSInteger
s!
The SDK documentation also recommends to cast NSInteger
to long
in this case (to match the @"%ld"), e.g.:
NSInteger i = 42;
label.text = [NSString stringWithFormat:@"%ld", (long)i];
Source: String Programming Guide for Cocoa - String Format Specifiers (Requires iPhone developer registration)
The way is correct, but can be improved a bit with the extended set-syntax.
set "var=xyz"
Sets the var to the content until the last quotation mark, this ensures that no "hidden" spaces are appended.
Your code would look like
set "var1=A"
set "var2=B"
set "AB=hi"
set "newvar=%var1%%var2%"
echo %newvar% is the concat of var1 and var2
echo !%newvar%! is the indirect content of newvar
Assuming your object name is BASKET, simply set BASKET = "";
To delete all objects in a list, you can directly write list = []
Here is example:
>>> a = [1, 2, 3]
>>> a
[1, 2, 3]
>>> a = []
>>> a
[]
It depends on what you need to do. You can use replace
since you want to replace the value:
select replace(email, '.com', '.org')
from yourtable
Then to UPDATE
your table with the new ending, then you would use:
update yourtable
set email = replace(email, '.com', '.org')
You can also expand on this by checking the last 4 characters of the email value:
update yourtable
set email = replace(email, '.com', '.org')
where right(email, 4) = '.com'
However, the issue with replace()
is that .com
can be will in other locations in the email not just the last one. So you might want to use substring()
the following way:
update yourtable
set email = substring(email, 1, len(email) -4)+'.org'
where right(email, 4) = '.com';
Using substring()
will return the start of the email value, without the final .com
and then you concatenate the .org
to the end. This prevents the replacement of .com
elsewhere in the string.
Alternatively you could use stuff()
, which allows you to do both deleting and inserting at the same time:
update yourtable
set email = stuff(email, len(email) - 3, 4, '.org')
where right(email, 4) = '.com';
This will delete 4 characters at the position of the third character before the last one (which is the starting position of the final .com
) and insert .org
instead.
See SQL Fiddle with Demo for this method as well.
value_counts work only for series. It won't work for entire DataFrame. Try selecting only one column and using this attribute. For example:
df['accepted'].value_counts()
It also won't work if you have duplicate columns. This is because when you select a particular column, it will also represent the duplicate column and will return dataframe instead of series. At that time remove duplicate column by using
df = df.loc[:,~df.columns.duplicated()]
df['accepted'].value_counts()
After MS SQL Server 2012, you can use window function too.
SELECT column_name,
COUNT(column_name) OVER (Partition by column_name)
FROM table_name group by column_name ;
recently I saw that sometimes the flash player doesn't recognize &wmode=opaque
, istead you should pass &WMode=opaque
too (notice the uppercase).
If someone have a Internet Permission in AndroidManifest and still have a problem with Internet Connection, maybe that will be helpful: Android - Fixing the no internet connection issue on emulator.
I followed steps from that website, and everything works for me. The most important:
That is my first post, so I hope it will be helpful.
If you simply need to POST
data and do not require a response from the server, the shortest solution would be to use navigator.sendBeacon()
:
const data = JSON.stringify({
example_1: 123,
example_2: 'Hello, world!',
});
navigator.sendBeacon('example.php', data);
Some of the other answers here inspired me to write a script for automating the mixed sequential execution of SQL tasks using SQLPLUS along with shell commands for a project, a process that was previously manually done. Maybe this (highly sanitized) example will be useful to someone else:
#!/bin/bash
acreds="user_a/supergreatpassword"
bcreds="user_b/anothergreatpassword"
hoststring='fancyoraclehoststring'
runsql () {
# param 1 is $1
sqlplus -S /nolog << EOF
CONNECT $1@$hoststring;
whenever sqlerror exit sql.sqlcode;
set echo off
set heading off
$2
exit;
EOF
}
echo "TS::$(date): Starting SCHEM_A.PROC_YOU_NEED()..."
runsql "$acreds" "execute SCHEM_A.PROC_YOU_NEED();"
echo "TS::$(date): Starting superusefuljob..."
/var/scripts/superusefuljob.sh
echo "TS::$(date): Starting SCHEM_B.SECRET_B_PROC()..."
runsql "$bcreds" "execute SCHEM_B.SECRET_B_PROC();"
echo "TS::$(date): DONE"
runsql
allows you to pass a credential string as the first argument, and any SQL you need as the second argument. The variables containing the credentials are included for illustration, but for security I actually source them from another file. If you wanted to handle multiple database connections, you could easily modify the function to accept the hoststring as an additional parameter.
There are two types of scopes in JavaScript.
Global scope: variable which is announced in global scope can be used anywhere in the program very smoothly. For example:
var carName = " BMW";
// code here can use carName
function myFunction() {
// code here can use carName
}
Functional scope or Local scope: variable declared in this scope can be used in its own function only. For example:
// code here can not use carName
function myFunction() {
var carName = "BMW";
// code here can use carName
}
You can use the Collections API
to achieve what you want easily - read efficiently - enough
Javadoc for Collections.max
Collections.max(arrayList);
Returns the maximum element of the given collection, according to the natural ordering of its elements. All elements in the collection must implement the Comparable interface.
There is an article on the topic, using Rust as the language in the example code:
https://medium.com/@polyglot_factotum/rust-concurrency-five-easy-pieces-871f1c62906a
In summary, the trick is to write your concurrent logic so that it is robust to the non-determinism involved with multiple threads of execution, using tools like channels and condvars.
Then, if that is how you've structured your "components", the easiest way to test them is by using channels to send messages to them, and then block on other channels to assert that the component sends certain expected messages.
The linked-to article is fully written using unit-tests.
The $_GET
variable is populated from the parameters set in the URL. From the URL http://example.com/test.php?foo=bar&baz=buzz
you can get $_GET['foo']
and $_GET['baz']
. So to set these variables, you only have to make a link to that URL.
If you want to get a list of all tablespaces used in the current database instance, you can use the DBA_TABLESPACES view as shown in the following SQL script example:
SQL> connect SYSTEM/fyicenter
Connected.
SQL> SELECT TABLESPACE_NAME, STATUS, CONTENTS
2 FROM USER_TABLESPACES;
TABLESPACE_NAME STATUS CONTENTS
------------------------------ --------- ---------
SYSTEM ONLINE PERMANENT
UNDO ONLINE UNDO
SYSAUX ONLINE PERMANENT
TEMP ONLINE TEMPORARY
USERS ONLINE PERMANENT
http://dba.fyicenter.com/faq/oracle/Show-All-Tablespaces-in-Current-Database.html
demo
branch into master
git fetch --all
demo
branch on localgit pull origin demo
master
branch. This branch will be completely changed with the code on demo
branchgit checkout master
master
branch and run this command.git reset --hard origin/demo
reset
means you will be resetting current branch
--hard
is a flag that means it will be reset without raising any merge conflict
origin/demo
will be the branch that will be considered to be the code that will forcefully overwrite current master
branch
The output of the above command will show you your last commit message on origin/demo
or demo
branch
Then, in the end, force push the code on the master
branch to your remote repo.
git push --force
Here's a more general, regex way of doing this:
re.sub(r'^.+/([^/]+)$', r'\1', url)
Instead of writing some javascript or jquery code(reinventing the wheel). The above scenario can be managed by bootstrap auto-close option. You can provide either of the values to auto-close:
always - (Default) automatically closes the dropdown when any of its elements is clicked.
outsideClick - closes the dropdown automatically only when the user clicks any element outside the dropdown.
disabled - disables the auto close
Take a look at the following plunkr :
http://plnkr.co/edit/gnU8M2fqlE0GscUQtCWa?p=preview
Set
uib-dropdown auto-close="disabled"
Hope this helps :)
To Get The Data From the App.config
Keeping in mind you have to:
System.Configuration
using System.Configuration;
Just Simply do this
string value1 = ConfigurationManager.AppSettings["Value1"];
Alternatively, you can achieve this in one line, if you don't want to add using System.Configuration;
explicitly.
string value1 = System.Configuration.ConfigurationManager.AppSettings["Value1"]
In case anyone looks at this again, you can use this:
Sub test()
Dim sh As Worksheet
Set sh = ThisWorkbook.Sheets("Sheet1")
Dim k As Long
k = sh.Range("A1", sh.Range("A1").End(xlDown).End(xlDown).End(xlUp)).Rows.Count
End Sub
As of May 2017, multiple FROM
s can be used in a single Dockerfile.
See "Builder pattern vs. Multi-stage builds in Docker" (by Alex Ellis) and PR 31257 by Tõnis Tiigi.
The general syntax involves adding
FROM
additional times within your Dockerfile - whichever is the lastFROM
statement is the final base image. To copy artifacts and outputs from intermediate images useCOPY --from=<base_image_number>
.
FROM golang:1.7.3 as builder
WORKDIR /go/src/github.com/alexellis/href-counter/
RUN go get -d -v golang.org/x/net/html
COPY app.go .
RUN CGO_ENABLED=0 GOOS=linux go build -a -installsuffix cgo -o app .
FROM alpine:latest
RUN apk --no-cache add ca-certificates
WORKDIR /root/
COPY --from=builder /go/src/github.com/alexellis/href-counter/app .
CMD ["./app"]
The result would be two images, one for building, one with just the resulting app (much, much smaller)
REPOSITORY TAG IMAGE ID CREATED SIZE
multi latest bcbbf69a9b59 6 minutes ago 10.3MB
golang 1.7.3 ef15416724f6 4 months ago 672MB
what is a base image?
A set of files, plus EXPOSE
'd ports, ENTRYPOINT
and CMD
.
You can add files and build a new image based on that base image, with a new Dockerfile
starting with a FROM
directive: the image mentioned after FROM
is "the base image" for your new image.
does it mean that if I declare
neo4j/neo4j
in aFROM
directive, that when my image is run the neo database will automatically run and be available within the container on port 7474?
Only if you don't overwrite CMD
and ENTRYPOINT
.
But the image in itself is enough: you would use a FROM neo4j/neo4j
if you had to add files related to neo4j
for your particular usage of neo4j
.
Set your .on
listener to check for specific select2 events. The "change" event is the same as usual but the others are specific to the select2 control thus:
The names are self-explanatory. For example, select2-focus
fires when you give focus to the control.
To quote MDN on FormData
(emphasis mine):
The
FormData
interface provides a way to easily construct a set of key/value pairs representing form fields and their values, which can then be easily sent using theXMLHttpRequest.send()
method. It uses the same format a form would use if the encoding type were set to"multipart/form-data"
.
So when using FormData
you are locking yourself into multipart/form-data
. There is no way to send a FormData
object as the body and not sending data in the multipart/form-data
format.
If you want to send the data as application/x-www-form-urlencoded
you will either have to specify the body as an URL-encoded string, or pass a URLSearchParams
object. The latter unfortunately cannot be directly initialized from a form
element. If you don’t want to iterate through your form elements yourself (which you could do using HTMLFormElement.elements
), you could also create a URLSearchParams
object from a FormData
object:
const data = new URLSearchParams();
for (const pair of new FormData(formElement)) {
data.append(pair[0], pair[1]);
}
fetch(url, {
method: 'post',
body: data,
})
.then(…);
Note that you do not need to specify a Content-Type
header yourself.
As noted by monk-time in the comments, you can also create URLSearchParams
and pass the FormData
object directly, instead of appending the values in a loop:
const data = new URLSearchParams(new FormData(formElement));
This still has some experimental support in browsers though, so make sure to test this properly before you use it.
Simply install this jQuery Plugin: jQuery Cross-Domain AJAX for IE8
This 1.4kb plugin works right away in Internet Explorer 8 and 9.
Include the plugin after jQuery, and call your ajax request as normal. Nothing else required.
Here is a simple routine for an array of primitive elements:
for ($i = 0; $i < count($mySimpleArray); $i++)
{
echo $mySimpleArray[$i] . "\n";
}
The default character encoding for a SQL Server database is iso_1, which is ISO 8859-1. Note that the character encoding depends on the data type of a column. You can get an idea of what character encodings are used for the columns in a database as well as the collations using this SQL:
select data_type, character_set_catalog, character_set_schema, character_set_name, collation_catalog, collation_schema, collation_name, count(*) count
from information_schema.columns
group by data_type, character_set_catalog, character_set_schema, character_set_name, collation_catalog, collation_schema, collation_name;
If it's using the default, the character_set_name should be iso_1 for the char and varchar data types. Since nchar and nvarchar store Unicode data in UCS-2 format, the character_set_name for those data types is UNICODE.
Salvaging (and extending) the list from an old version of the Wikipedia page:
Although the reference implementation of reStructuredText is written in Python, there are reStructuredText parsers in other languages too.
The main distribution of reStructuredText is the Python Docutils package. It contains several conversion tools:
Pandoc is a Haskell library for converting from one markup format to another, and a command-line tool that uses this library. It can read Markdown and (subsets of) reStructuredText, HTML, and LaTeX, and it can write Markdown, reStructuredText, HTML, LaTeX, ConTeXt, PDF, RTF, DocBook XML, OpenDocument XML, ODT, GNU Texinfo, MediaWiki markup, groff man pages, and S5 HTML slide shows.
There is an Pandoc online tool (POT) to try this library. Unfortunately, compared to the reStructuredText online renderer (ROR),
docutils
)JRst is a Java reStructuredText parser. It can currently output HTML, XHTML, DocBook xdoc and PDF, BUT seems to have serious problems: neither PDF or (X)HTML generation works using the current full download, result pages in (X)HTML are empty and PDF generation fails on IO problems with XSL files (not bundled??). Note that the original JRst has been removed from the website; a fork is found on GitHub.
Laika is a new library for transforming markup languages to other output formats. Currently it supports input from Markdown and reStructuredText and produce HTML output. The library is written in Scala but should be also usable from Java.
The Nim compiler features the commands rst2html
and rst2tex
which transform reStructuredText files to HTML and TeX files. The standard library provides the following modules (used by the compiler) to handle reStructuredText files programmatically:
Most (but not all) of these tools are based on Docutils (see above) and provide conversion to or from formats that might not be supported by the main distribution.
pip
-installable python package requires docutils
, which does the actual rendering. restview
's major ease-of-use feature is that, when you save changes to your document(s), it automagically re-renders and re-displays them. restview
docutils
to render your document(s) to HTMLSome projects use reStructuredText as a baseline to build on, or provide extra functionality extending the utility of the reStructuredText tools.
The Sphinx documentation generator translates a set of reStructuredText source files into various output formats, automatically producing cross-references, indices etc.
rest2web is a simple tool that lets you build your website from a single template (or as many as you want), and keep the contents in reStructuredText.
Pygments is a generic syntax highlighter for general use in all kinds of software such as forum systems, Wikis or other applications that need to prettify source code. See Using Pygments in reStructuredText documents.
While any plain text editor is suitable to write reStructuredText documents, some editors have better support than others.
The Emacs support via rst-mode comes as part of the Docutils package under /docutils/tools/editors/emacs/rst.el
The vim-common
package for that comes with most GNU/Linux distributions has reStructuredText syntax highlight and indentation support of reStructuredText out of the box:
There is a rst mode for the Jed programmers editor.
gedit, the official text editor of the GNOME desktop environment. There is a gedit reStructuredText plugin.
Geany, a small and lightweight Integrated Development Environment include support for reStructuredText from version 0.12 (October 10, 2007).
Leo, an outlining editor for programmers, supports reStructuredText via rst-plugin or via "@auto-rst" nodes (it's not well-documented, but @auto-rst nodes allow editing rst files directly, parsing the structure into the Leo outline).
It also provides a way to preview the resulting HTML, in a "viewrendered" pane.
The FTE Folding Text Editor - a free (licensed under the GNU GPL) text editor for developers. FTE has a mode for reStructuredText support. It provides color highlighting of basic RSTX elements and special menu that provide easy way to insert most popular RSTX elements to a document.
PyK is a successor of PyEdit and reStInPeace, written in Python with the help of the Qt4 toolkit.
The Eclipse IDE with the ReST Editor plug-in provides support for editing reStructuredText files.
NoTex is a browser based (general purpose) text editor, with integrated project management and syntax highlighting. Plus it enables to write books, reports, articles etc. using rST and convert them to LaTex, PDF or HTML. The PDF files are of high publication quality and are produced via Sphinx with the Texlive LaTex suite.
Notepad++ is a general purpose text editor for Windows. It has syntax highlighting for many languages built-in and support for reStructuredText via a user defined language for reStructuredText.
Visual Studio Code is a general purpose text editor for Windows/macOS/Linux. It has syntax highlighting for many languages built-in and supports reStructuredText via an extension from LeXtudio.
Sublime Text is a completely customizable and extensible source code editor available for Windows, OS X, and Linux. Registration is required for long-term use, but all functions are available in the unregistered version, with occasional reminders to purchase a license. Versions 2 and 3 (currently in beta) support reStructuredText syntax highlighting by default, and several plugins are available through the package manager Package Control to provide snippets and code completion, additional syntax highlighting, conversion to/from RST and other formats, and HTML preview in the browser.
BBEdit (and its free variant TextWrangler) for Mac can syntax-highlight reStructuredText using this codeless language module.
TextMate, a proprietary general-purpose GUI text editor for Mac OS X, has a bundle for reStructuredText.
Intype is a proprietary text editor for Windows, that support reStructuredText out of the box.
E is a proprietary Text Editor licensed under the "Open Company License". It supports TextMate's bundles, so it should support reStructuredText the same way TextMate does.
PyCharm (and other IntelliJ platform IDEs?) has ReST/Sphinx support (syntax highlighting, autocomplete and preview).)
here are some Wiki programs that support the reStructuredText markup as the native markup syntax, or as an add-on:
MediaWiki reStructuredText extension allows for reStructuredText markup in MediaWiki surrounded by <rst>
and </rst>
.
MoinMoin is an advanced, easy to use and extensible WikiEngine with a large community of users. Said in a few words, it is about collaboration on easily editable web pages.
There is a reStructuredText Parser for MoinMoin.
Trac is an enhanced wiki and issue tracking system for software development projects. There is a reStructuredText Support in Trac.
This Wiki is a Webware for Python Wiki written by Ian Bicking. This wiki uses ReStructuredText for its markup.
rstiki is a minimalist single-file personal wiki using reStructuredText syntax (via docutils) inspired by pwyky. It does not support authorship indication, versioning, hierarchy, chrome/framing/templating or styling. It leverages docutils/reStructuredText as the wiki syntax. As such, it's under 200 lines of code, and in a single file. You put it in a directory and it runs.
Ikiwiki is a wiki compiler. It converts wiki pages into HTML pages suitable for publishing on a website. Ikiwiki stores pages and history in a revision control system such as Subversion or Git. There are many other features, including support for blogging, as well as a large array of plugins. It's reStructuredText plugin, however is somewhat limited and is not recommended as its' main markup language at this time.
An Online reStructuredText editor can be used to play with the markup and see the results immediately.
WordPreSt reStructuredText plugin for WordPress. (PHP)
reStructuredText parser plugin for Zine (will become obsolete in version 0.2 when Zine is scheduled to get a native reStructuredText support). Zine is discontinued. (Python)
Pelican is a static blog generator that supports writing articles in ReST. (Python)
Hyde is a static website generator that supports ReST. (Python)
Acrylamid is a static blog generator that supports writing articles in ReST. (Python)
Nikola is a Static Site and Blog Generator that supports ReST. (Python)
Ipsum genera is a static blog generator written in Nim.
Yozuch is a static blog generator written in Python.
function getAge(birthday) {
var today = new Date();
var thisYear = 0;
if (today.getMonth() < birthday.getMonth()) {
thisYear = 1;
} else if ((today.getMonth() == birthday.getMonth()) && today.getDate() < birthday.getDate()) {
thisYear = 1;
}
var age = today.getFullYear() - birthday.getFullYear() - thisYear;
return age;
}
Reflection can take you from an object to a dictionary by iterating over the properties.
To go the other way, you'll have to use a dynamic ExpandoObject (which, in fact, already inherits from IDictionary, and so has done this for you) in C#, unless you can infer the type from the collection of entries in the dictionary somehow.
So, if you're in .NET 4.0 land, use an ExpandoObject, otherwise you've got a lot of work to do...
The error message says that if you're passing scalar values, you have to pass an index. So you can either not use scalar values for the columns -- e.g. use a list:
>>> df = pd.DataFrame({'A': [a], 'B': [b]})
>>> df
A B
0 2 3
or use scalar values and pass an index:
>>> df = pd.DataFrame({'A': a, 'B': b}, index=[0])
>>> df
A B
0 2 3
My issue was as simple as having a null reference that didn't show up in the returned message, I had to debug my API to see it.
There are updated now and then, just keep checking for the latest version.
The above method works good.
Another method (I am assuming web here) is to create your page. Add controls to the page. Then while in design mode go to: Tools > Generate Local Resource. A resource file will automatically appear in the solution with all the controls in the page mapped in the resource file.
To create resources for other languages, append the 4 character language to the end of the file name, before the extension (Account.aspx.en-US.resx, Account.aspx.es-ES.resx...etc).
To retrieve specific entries in the code-behind, simply call this method: GetLocalResourceObject([resource entry key/name])
.
You can calculate the checksum of a file by reading the binary data and using hashlib.md5().hexdigest()
. A function to do this would look like the following:
def File_Checksum_Dis(dirname):
if not os.path.exists(dirname):
print(dirname+" directory is not existing");
for fname in os.listdir(dirname):
if not fname.endswith('~'):
fnaav = os.path.join(dirname, fname);
fd = open(fnaav, 'rb');
data = fd.read();
fd.close();
print("-"*70);
print("File Name is: ",fname);
print(hashlib.md5(data).hexdigest())
print("-"*70);
In case of this similar error Warning: Error in $: object of type 'closure' is not subsettable [No stack trace available]
Just add corresponding package name using :: e.g.
instead of tags(....)
write shiny::tags(....)
You don't need to locate the user if you only need their country. You can look their IP address up in any IP-to-location service (like maxmind, ipregistry or ip2location). This will be accurate most of the time.
If you really need to get their location, you can get their lat/lng with that method, then query Google's or Yahoo's reverse geocoding service.
The definition of the perfmon counters has been broken since the beginning and for some reason appears to be too hard to correct.
A good overview of Windows memory management is available in the video "Mysteries of Memory Management Revealed" on MSDN: It covers more topics than needed to track memory leaks (eg working set management) but gives enough detail in the relevant topics.
To give you a hint of the problem with the perfmon counter descriptions, here is the inside story about private bytes from "Private Bytes Performance Counter -- Beware!" on MSDN:
Q: When is a Private Byte not a Private Byte?
A: When it isn't resident.
The Private Bytes counter reports the commit charge of the process. That is to say, the amount of space that has been allocated in the swap file to hold the contents of the private memory in the event that it is swapped out. Note: I'm avoiding the word "reserved" because of possible confusion with virtual memory in the reserved state which is not committed.
From "Performance Planning" on MSDN:
3.3 Private Bytes
3.3.1 Description
Private memory, is defined as memory allocated for a process which cannot be shared by other processes. This memory is more expensive than shared memory when multiple such processes execute on a machine. Private memory in (traditional) unmanaged dlls usually constitutes of C++ statics and is of the order of 5% of the total working set of the dll.
To answer one of the questions, it is necessary to have both a global and local install for the tools to work.
If you try to run ng serve
on an application without the local install of the CLI (global install only), you will get the following error.
You have to be inside an Angular CLI project in order to use the serve command.
It will also print this message:
Please take the following steps to avoid issues:
"npm install --save-dev @angular/cli@latest"
Run that npm
command to update the CLI locally, and avoid the warning that you are getting.
Other question: It looks like they do not have to be in sync, but it's probably best that they are in order to avoid any unusual behavior with the tool, or any inconsistencies with the code the tool generates.
Why do we need both the global install, and a local install?
The global install is needed to start a new application. The ng new <app-name>
command is run using the global installation of the CLI. In fact, if you try to run ng new
while inside the folder structure of an existing CLI application, you get this lovely error:
You cannot use the
new
command inside an Angular CLI project.
Other commands that can be run from the global install are ng help
, ng get/set
with the --global
option, ng version
, ng doc
, and ng completion
.
The local install of the CLI is used after an application has been built. This way, when new versions of the CLI are available, you can update your global install, and not affect the local install. This is good for the stability of a project. Most ng
commands only make sense with the local version, like lint
, build
and serve
, etc.
According to the CLI GitHub readme, to update the CLI you must update the global and local package. However, I have used the CLI where the global and local version vary without any trouble so far. If I ever run across an error related to having the global and local CLI versions out of sync, I will post that here.
Uri.parse(STRING);
See doc:
String: an RFC 2396-compliant, encoded URI
Url must be canonicalized before using, like this:
Uri.parse(Uri.decode(STRING));
You should be able to use the format method:
"Location: {0:20} Revision {1}".format(Location,Revision)
You will have to figure out the of the format length for each line depending on the length of the label. The User line will need a wider format width than the Location or District lines.
I would suggest that you use a timer, but set it to check every 45 seconds, not minute. Otherwise you can run into situations where with heavy load, the check for a particular minute is missed, because between the time the timer triggers and the time your code runs and checks the current time, you might have missed the target minute.
You can use .is(':visible')
Selects all elements that are visible.
For example:
if($('#selectDiv').is(':visible')){
Also, you can get the div which is visible by:
$('div:visible').callYourFunction();
Live example:
console.log($('#selectDiv').is(':visible'));_x000D_
console.log($('#visibleDiv').is(':visible'));
_x000D_
#selectDiv {_x000D_
display: none; _x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<div id="selectDiv"></div>_x000D_
<div id="visibleDiv"></div>
_x000D_
If nothing else works, make sure that you have correct permissions and ownership set up during building. A quick fix can be:
sudo chown -R <you>:<your_group> *
sudo chmod -R 755 *
He're the full migration for Laravel 5:
public function up()
{
Schema::table('users', function (Blueprint $table) {
$table->unsignedInteger('user_id')->nullable()->change();
});
}
public function down()
{
Schema::table('users', function (Blueprint $table) {
$table->unsignedInteger('user_id')->nullable(false)->change();
});
}
The point is, you can remove nullable
by passing false
as an argument.
Here is a refactored and simplified version of the @sasha_gud answer:
[DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Unicode)]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool GetDiskFreeSpaceEx(string lpDirectoryName,
out ulong lpFreeBytesAvailable,
out ulong lpTotalNumberOfBytes,
out ulong lpTotalNumberOfFreeBytes);
public static ulong GetDiskFreeSpace(string path)
{
if (string.IsNullOrEmpty(path))
{
throw new ArgumentNullException("path");
}
ulong dummy = 0;
if (!GetDiskFreeSpaceEx(path, out ulong freeSpace, out dummy, out dummy))
{
throw new Win32Exception(Marshal.GetLastWin32Error());
}
return freeSpace;
}
IF,
Then,
It is highly recommended that you install xampp 1.7.0 . Download Link
Note: This is not a solution to the above problem, but a FIX which would allow you to continue with your development.
The first thing i noticed is that you have a semi colon just after your closing bracket for your if statement );
You should also try and clean up your if statement by declaring a variable for the answer separately.
function answers() {
var select = document.getElementById("mySelect");
var answer = select.options[select.selectedIndex].value;
if(answer == "To measure time"){
alert("Thats correct");
}
}
Table with Fixed Header
<table cellspacing="0" cellpadding="0" border="0" width="325">_x000D_
<tr>_x000D_
<td>_x000D_
<table cellspacing="0" cellpadding="1" border="1" width="300" >_x000D_
<tr style="color:white;background-color:grey">_x000D_
<th>Header 1</th>_x000D_
<th>Header 2</th>_x000D_
</tr>_x000D_
</table>_x000D_
</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>_x000D_
<div style="width:320px; height:80px; overflow:auto;">_x000D_
<table cellspacing="0" cellpadding="1" border="1" width="300" >_x000D_
<tr>_x000D_
<td>new item</td>_x000D_
<td>new item</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>new item</td>_x000D_
<td>new item</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>new item</td>_x000D_
<td>new item</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>new item</td>_x000D_
<td>new item</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>new item</td>_x000D_
<td>new item</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>new item</td>_x000D_
<td>new item</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>new item</td>_x000D_
<td>new item</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>new item</td>_x000D_
<td>new item</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>new item</td>_x000D_
<td>new item</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>new item</td>_x000D_
<td>new item</td>_x000D_
</tr>_x000D_
</table> _x000D_
</div>_x000D_
</td>_x000D_
</tr>_x000D_
</table>
_x000D_
Result
This is working in all browser
Demo jsfiddle http://jsfiddle.net/nyCKE/6302/
You need to use the enumerate function: python docs
for place, item in enumerate(list):
if "foo" in item:
item = replace_all(item, replaceDictionary)
list[place] = item
print item
Also, it's a bad idea to use the word list as a variable, due to it being a reserved word in python.
Since you had problems with enumerate, an alternative from the itertools library:
for place, item in itertools.zip(itertools.count(0), list):
if "foo" in item:
item = replace_all(item, replaceDictionary)
list[place] = item
print item
There are a lot of good answers here but I noticed something was missing. Most answers seem to be implying that the reason why people use Big O over Big Theta is a difficulty issue, and in some cases this may be true. Often a proof that leads to a Big Theta result is far more involved than one that results in Big O. This usually holds true, but I do not believe this has a large relation to using one analysis over the other.
When talking about complexity we can say many things. Big O time complexity is just telling us what an algorithm is guarantied to run within, an upper bound. Big Omega is far less often discussed and tells us the minimum time an algorithm is guarantied to run, a lower bound. Now Big Theta tells us that both of these numbers are in fact the same for a given analysis. This tells us that the application has a very strict run time, that can only deviate by a value asymptoticly less than our complexity. Many algorithms simply do not have upper and lower bounds that happen to be asymptoticly equivalent.
So as to your question using Big O in place of Big Theta would technically always be valid, while using Big Theta in place of Big O would only be valid when Big O and Big Omega happened to be equal. For instance insertion sort has a time complexity of Big ? at n^2, but its best case scenario puts its Big Omega at n. In this case it would not be correct to say that its time complexity is Big Theta of n or n^2 as they are two different bounds and should be treated as such.
This is an old question. CSS has evolved. There now is the vh
(viewport height) unit, also new layout options like flexbox
or CSS grid
to achieve classical designs in cleaner ways.
I have add this input tag into form tag..
<form id="form_data">
<input type="file" id="file_data" name="browse"
(change)="handleFileInput($event, dataFile, f)" />
</form>
I angular typescript, I have added below lines, get your form id in document forms and make that value as null.
for(let i=0; i<document.forms.length;i++){
if(document.forms[i].length > 0){
if(document.forms[i][0]['value']){ //document.forms[i][0] = "file_data"
document.forms[i][0]['value'] = "";
}
}
}
Print document.forms in console and you can get idea..
The best way is to use a List
within a List
:
List<List<String>> listOfLists = new ArrayList<List<String>>();
We can't define enumeration as string type. The approved types for an enum are byte, sbyte, short, ushort, int, uint, long, or ulong.
If you need more details on enumeration please follow below link,that link will help you to understand enumeration. Enumeration
@narendras1414
In my opinion many of the answers here seem a little bit hacky (e.g. $apply() or $timeout), since messing around with $apply() can lead to unwanted errors.
Usually, when the $location doesn't work it means that something was not implemented the angular way.
In this particular question, the problem seems to be in the non-angular AJAX part. I had a similiar problem, where the redirection using $location should take place after a promise resolved. I would like to illustrate the problem on this example.
The old code:
taskService.createTask(data).then(function(code){
$location.path("task/" + code);
}, function(error){});
Note: taskService.createTask returns a promise.
$q - the angular way to use promises:
let dataPromises = [taskService.createTask(data)];
$q.all(dataPromises).then(function(response) {
let code = response[0];
$location.path("task/" + code);
},
function(error){});
Using $q to resolve the promise solved the redirection problem.
More on the $q service: https://docs.angularjs.org/api/ng/service/$q
You can use conda remove --force
.
The documentation says:
--force Forces removal of a package without removing packages
that depend on it. Using this option will usually
leave your environment in a broken and inconsistent
state
This code will output current time in HH:MM:SS format in console, it takes into account GMT timezones.
var currentTime = Date.now()
var GMT = -(new Date()).getTimezoneOffset()/60;
var totalSeconds = Math.floor(currentTime/1000);
seconds = ('0' + totalSeconds % 60).slice(-2);
var totalMinutes = Math.floor(totalSeconds/60);
minutes = ('0' + totalMinutes % 60).slice(-2);
var totalHours = Math.floor(totalMinutes/60);
hours = ('0' + (totalHours+GMT) % 24).slice(-2);
var timeDisplay = hours + ":" + minutes + ":" + seconds;
console.log(timeDisplay);
//Output is: 11:16:55