In the detached window (Tool Options), the name of the view (Paintbrush) is a grab-bar.
Put your cursor over the grab-bar, click and drag it to the dock area in the main window in order to reattach it to the main window.
new syntax
<%= form_for :user, url: custom_user_path, method: :post do |f|%>
<%end%>
You can call it like that:
<!DOCTYPE html>
<html lang="en">
<head>
<script type="text/javascript">
var person = { name: 'Joe Blow' };
function myfunction() {
document.write(person.name);
}
</script>
</head>
<body>
<script type="text/javascript">
myfunction();
</script>
</body>
</html>
The result should be page with the only content: Joe Blow
Look here: http://jsfiddle.net/HWreP/
Best regards!
Try this. I am using Jupyter notebook (OS: Ubuntu 16.04 LTS on Google Cloud Platform + on Windows). Executed following command in the Jupyter notebook to install opencv:
!pip install opencv-contrib-python #working on both Windows and Ubuntu
After successful installation you will get following message:
Successfully installed opencv-contrib-python-4.1.0.25
Now restart the kernel and try to import opencv as:
import cv2
The same command can be used to installed opencv on Windows as well.
SOLUTION 2: try following commands to install opencv: For Ubuntu: Run following command from terminal:
sudo apt-get install libsm6 libxrender1 libfontconfig1
Restart Jupyter notebook kernel and execute following command:
!pip install opencv-contrib-python
NOTE: You can run all the above commands from the terminal as well without using '!'.
The other solution is correct in that it will get you a reference to the application's delegate, but this will not allow you to access any methods or variables added by your subclass of UIApplication, like your managed object context. To resolve this, simply downcast to "AppDelegate" or what ever your UIApplication subclass happens to be called. In Swift 3, 4 & 5, this is done as follows:
let appDelegate = UIApplication.shared.delegate as! AppDelegate
let aVariable = appDelegate.someVariable
If your user has a local folder e.g. Linux, in your users home folder you could create a .my.cnf file and provide the credentials to access the server there. for example:-
[client]
host=localhost
user=yourusername
password=yourpassword or exclude to force entry
database=mygotodb
Mysql would then open this file for each user account read the credentials and open the selected database.
Not sure on Windows, I upgraded from Windows because I needed the whole house not just the windows (aka Linux) a while back.
Easier way is to use the getString()
function within the activity.
String myString = getString(R.string.mystring);
Reference: http://developer.android.com/guide/topics/resources/string-resource.html
I think this feature is added in a recent Android version, anyone who knows the history can comment on this.
var1 = var1 or 4
The only issue this might have is that if var1 is a falsey value, like False or 0 or [], it will choose 4 instead. That might be an issue.
You are getting this error because you are not giving full path. (C:\Users...\file.exe) If you want to remove this error then either give full path or copy that application (you want to open) to the folder where your project(.exe) is present/saved.
#include <windows.h>
using namespace std;
int main()
{
system ("start C:\\Users\\Folder\\chrome.exe https://www.stackoverflow.com"); //for opening stackoverflow through google chrome , if chorme.exe is in that folder..
return 0;
}
Surprisingly (or not), the vertical-align
tool actually works best for this job. Best of all, no Javascript is required.
In the following example, I am positioning the outer
class in the middle of the body, and the inner
class in the middle of the outer
class.
Preview: http://jsfiddle.net/tLkSV/513/
HTML:
<div id="container">
<span></span><div class="outer">
<span></span><div class="inner">
</div>
</div>
</div>
CSS:
html, body {
height: 100%;
margin: 0;
padding: 0; }
#container {
text-align: center;
height: 100%; }
span {
height: 100%;
vertical-align: middle;
display: inline-block; }
.outer {
width: 100px;
height: 200px;
padding: 0;
border: 1px solid #000;
vertical-align: middle;
display: inline-block; }
.inner {
background: red;
width: 30px;
height: 20px;
vertical-align: middle;
display: inline-block; }
Vertical align works by aligning the centers of elements that are next to each other. Applying vertical-align to a single element does absolutely nothing. If you add a second element that has no width but is the height of the container, your single element will move to vertically center with this no-width element, thus vertically centering it. The only requirements are that you set both elements to inline (or inline-block), and set their vertical-align attribute to vertical-align: middle
.
Note: You may notice in my code below that my <span>
tag and <div>
tag are touching. Because they are both inline elements, a space will actually add a space between the no-width element and your div, so be sure to leave it out.
Use below one,
map.setCenter(bounds.getCenter(), map.getBoundsZoomLevel(bounds));
All I'm really interested in is the ownership and permissions information for the first level subdirectories.
I found a easy solution while playing my fish, which fits your need perfectly.
ll `ls`
or
ls -l $(ls)
We can create static constructor
static class StaticParent
{
StaticParent()
{
//write your initialization code here
}
}
and it is always parameter less.
static class StaticParent
{
static int i =5;
static StaticParent(int i) //Gives error
{
//write your initialization code here
}
}
and it doesn't have the access modifier
Add this to build.gradle file
dexOptions {
javaMaxHeapSize "2g"
}
@echo off
Setlocal enabledelayedexpansion
Set 1=%1
Set 1=!1:"=!
Echo !1!
Echo "!1!"
Set 1=
Demonstrates with or without quotes reguardless of whether original parameter has quotes or not.
And if you want to test the existence of a parameter which may or may not be in quotes, put this line before the echos above:
If '%1'=='' goto yoursub
But if checking for existence of a file that may or may not have quotes then it's:
If EXIST "!1!" goto othersub
Note the use of single quotes and double quotes are different.
This is an old thread, but a new quite elegant solution (with only 4 maybe 3 little drawbacks) is to use a custom annotation.
Check : http://www.adrianwalker.org/2011/12/java-multiline-string.html
A project inspired from that work is hosted on GitHub:
https://github.com/benelog/multiline
Example of Java code:
import org.adrianwalker.multilinestring.Multiline;
...
public final class MultilineStringUsage {
/**
<html>
<head/>
<body>
<p>
Hello<br/>
Multiline<br/>
World<br/>
</p>
</body>
</html>
*/
@Multiline
private static String html;
public static void main(final String[] args) {
System.out.println(html);
}
}
The drawbacks are
<%= variable %>
) :-)And you probably have to configure Eclipse/Intellij-Idea to not reformat automatically your Javadoc comments.
One may find this weird (Javadoc comments are not designed to embed anything other than comments), but as this lack of multiline string in Java is really annoying in the end, I find this to be the least worst solution.
The RFC for the HTTP Header Field X-Frame-Options states that the "ALLOW-FROM" field in the X-Frame-Options header value can only contain one domain. Multiple domains are not allowed.
The RFC suggests a work around for this problem. The solution is to specify the domain name as a url parameter in the iframe src url. The server that hosts the iframe src url can then check the domain name given in the url parameters. If the domain name matches a list of valid domain names, then the server can send the X-Frame-Options header with the value: "ALLOW-FROM domain-name", where domain name is the name of the domain that is trying to embed the remote content. If the domain name is not given or is not valid, then the X-Frame-Options header can be sent with the value: "deny".
The URL listed here might be of interest to you
http://www.codeplex.com/InterIMAP
which was extension to
You want to be able to pass in a Class and get a type-safe instance of that class? Try the following:
public static void main(String [] args) throws Exception {
String s = instanceOf(String.class);
}
public static <T> T instanceOf (Class<T> clazz) throws Exception {
return clazz.newInstance();
}
git stash list
to list your stashed changes.
git stash show
to see what n
is in the below commands.
git stash apply
to apply the most recent stash.
git stash apply stash@{n}
to apply an older stash.
https://git-scm.com/book/en/v2/Git-Tools-Stashing-and-Cleaning
You need "src/Hankees.txt"
Your file is in the source folder which is not counted as the working directory.\
Or you can move the file up to the root directory of your project and just use "Hankees.txt"
The module n
makes version-management easy:
sudo npm install n -g
For the latest stable version:
sudo n stable
For the latest version:
sudo n latest
just reinstall node from the .msi in Windows from the node website.
You can use this repo: GSBorderLabel
It's quite simple:
GSBorderLabel *myLabel = [[GSBorderLabel alloc] initWithTextColor:aColor
andBorderColor:anotherColor
andBorderWidth:2];
A tangential note on the approaches here that load use setTimeout
or setInterval
. In those cases it's possible that when your check runs again, the DOM will already have loaded, and the browser's DOMContentLoaded
event will have been fired, so you can't detect that event reliably using these approaches. What I found is that jQuery's ready
still works, though, so you can embed your usual
jQuery(document).ready(function ($) { ... }
inside your setTimeout
or setInterval
and everything should work as normal.
I think there may be problem that you haven't added click listener for ok positive button.
dlgAlert.setPositiveButton("Ok",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
//dismiss the dialog
}
});
How do you send the message?
The classes in the System.Net.Mail
namespace (which is probably what you should use) has full support for authentication, either specified in Web.config, or using the SmtpClient.Credentials
property.
I created a bit of a hybrid approach between Paul & Adam's approach:
The link that opens the array of links is already in the html. The jquery just creates the array of links and opens each one when the "open-all" button is clicked:
HTML:
<ul class="links">
<li><a href="http://www.google.com/"></a></li>
<li><a href="http://www.yahoo.com/"></a></li>
</ul>
<a id="open-all" href="#">OPEN ALL</a>
JQUERY:
$(function() { // On DOM content ready...
var hrefs = [];
$('.links a').each(function() {
hrefs.push(this.href); // Store the URLs from the links...
});
$('#open-all').click(function() {
for (var i in hrefs) {
window.open(hrefs[i]); // ...that opens each stored link in its own window when clicked...
}
});
});
You can check it out here: https://jsfiddle.net/daveaseeman/vonob51n/1/
For Option 1 used as the placeholder:
select:invalid { color:grey; }
All other options:
select:valid { color:black; }
You can find the my.ini file in windows at this location- C:\ProgramData\MySQL\MySQL Server 5.6
the ProgramData folder is a hidden folder, so make the according setting to see that folder. And open my.ini file as an administrator to edit and then save that.
from here
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
optionsBuilder.UseSqlServer(ConfigurationManager.ConnectionStrings["BloggingDatabase"].ConnectionString);
}
note you may need to add Microsoft.EntityFrameworkCore.SqlServer
Try this:
Yii2 : Validation rule
public function rules() {
return [
['location_id', 'compare', 'compareValue' => 0', 'operator' => '>'],
];
}
There are some subtle differences that mean you can use ViewData and ViewBag in slightly different ways from the view. One advantage is outlined in this post http://weblogs.asp.net/hajan/archive/2010/12/11/viewbag-dynamic-in-asp-net-mvc-3-rc-2.aspx and shows that casting can be avoided in the example by using the ViewBag instead of ViewData.
Python os module
Specifically for Python 3.6/3.7:
os.name
: The name of the operating system dependent module imported. The following names have currently been registered: 'posix', 'nt', 'java'.
In your case, you want to check for 'nt' as os.name
output:
import os
if os.name == 'nt':
...
There is also a note on os.name
:
See also
sys.platform
has a finer granularity.os.uname()
gives system-dependent version information.The platform module provides detailed checks for the system’s identity.
If you are issuing a single command with several select statements, you might use NextResult method to move to next resultset within the datareader: http://msdn.microsoft.com/en-us/library/system.data.idatareader.nextresult.aspx
I show how it could look bellow:
public DataSet SelectOne(int id)
{
DataSet result = new DataSet();
using (DbCommand command = Connection.CreateCommand())
{
command.CommandText = @"
select * from table1
select * from table2
";
var param = ParametersBuilder.CreateByKey(command, "ID", id, null);
command.Parameters.Add(param);
Connection.Open();
using (DbDataReader reader = command.ExecuteReader())
{
result.MainTable.Load(reader);
reader.NextResult();
result.SecondTable.Load(reader);
// ...
}
Connection.Close();
}
return result;
}
I found the mouseleave
will not fire when weird things happen, like the window focus changes suddenly, then the user comes back to the browser. In cases like that, mouseleave
will never fire until the cursor goes over and leaves the element again.
This solution I came up with relies on mouseenter
on the window
object, so it disappears when the mouse is moved anywhere else on the page.
This was designed to work with having multiple elements on the page that will trigger it (like in a table).
var allMenus = $(".menus");
allMenus.popover({
html: true,
trigger: "manual",
placement: "bottom",
content: $("#menuContent")[0].outerHTML
}).on("mouseenter", (e) => {
allMenus.not(e.target).popover("hide");
$(e.target).popover("show");
e.stopPropagation();
}).on("shown.bs.popover", () => {
$(window).on("mouseenter.hidepopover", (e) => {
if ($(e.target).parents(".popover").length === 0) {
allMenus.popover("hide");
$(window).off("mouseenter.hidepopover");
}
});
});
Answered by the OP:
Add this to your CSS file.
html,
body {
height: 100%;
/* The html and body elements cannot have any padding or margin. */
}
/* Wrapper for page content to push down footer */
#wrap {
min-height: 100%;
height: auto !important;
height: 100%;
/* Negative indent footer by it's height */
margin: 0 auto -60px;
}
/* Set the fixed height of the footer here */
#push,
#footer {
height: 60px;
}
#footer {
background-color: #eee;
}
/* Lastly, apply responsive CSS fixes as necessary */
@media (max-width: 767px) {
#footer {
margin-left: -20px;
margin-right: -20px;
padding-left: 20px;
padding-right: 20px;
}
}
For JSON data, it's much easier to POST it as "application/json" content-type. If you use GET, you have to URL-encode the JSON in a parameter and it's kind of messy. Also, there is no size limit when you do POST. GET's size if very limited (4K at most).
Despite that the other answers are correct and thoroughly explained, I found some difficulties understanding them. Here is the method I used (Taken from here):
openssl pkcs12 -in filename.pfx -out cert.pem -nodes
Extracts the private key form a PFX to a PEM file:
openssl pkcs12 -in filename.pfx -nocerts -out key.pem
Exports the certificate (includes the public key only):
openssl pkcs12 -in filename.pfx -clcerts -nokeys -out cert.pem
Removes the password (paraphrase) from the extracted private key (optional):
openssl rsa -in key.pem -out server.key
I dont know if its too late, but i thought it would help someone else.
I wanted the same badly...found it eventually.
Maybe its not perfect,but to me its adequate(for my little dictionary app).
http://www.androidtech.com/downloads/wordnet20-from-prolog-all-3.zip
Its not a dump file, but a MYSQL .sql script file
The words are in WN_SYNSET table and the glossary/meaning in the WN_GLOSS table
list.clear() is documented for clearing the ArrayList.
list.removeAll() has no documentation at all in Eclipse.
I had a problem because my canvas was inside of a container without ID so I used this jquery code below
$('.cropArea canvas').width()
In angular 1, you can use ng-show
and ng-hide
.In your case, you would use ng-hide
. For example:
<li ng-hide="area"></li>
Here's an easy and short way to get a substring if you know the index:
let s = "www.stackoverflow.com"
let result = String(s.characters.prefix(17)) // "www.stackoverflow"
It won't crash the app if your index exceeds string's length:
let s = "short"
let result = String(s.characters.prefix(17)) // "short"
Both examples are Swift 3 ready.
Probably the best way to check for errors in runtime API code is to define an assert style handler function and wrapper macro like this:
#define gpuErrchk(ans) { gpuAssert((ans), __FILE__, __LINE__); }
inline void gpuAssert(cudaError_t code, const char *file, int line, bool abort=true)
{
if (code != cudaSuccess)
{
fprintf(stderr,"GPUassert: %s %s %d\n", cudaGetErrorString(code), file, line);
if (abort) exit(code);
}
}
You can then wrap each API call with the gpuErrchk
macro, which will process the return status of the API call it wraps, for example:
gpuErrchk( cudaMalloc(&a_d, size*sizeof(int)) );
If there is an error in a call, a textual message describing the error and the file and line in your code where the error occurred will be emitted to stderr
and the application will exit. You could conceivably modify gpuAssert
to raise an exception rather than call exit()
in a more sophisticated application if it were required.
A second related question is how to check for errors in kernel launches, which can't be directly wrapped in a macro call like standard runtime API calls. For kernels, something like this:
kernel<<<1,1>>>(a);
gpuErrchk( cudaPeekAtLastError() );
gpuErrchk( cudaDeviceSynchronize() );
will firstly check for invalid launch argument, then force the host to wait until the kernel stops and checks for an execution error. The synchronisation can be eliminated if you have a subsequent blocking API call like this:
kernel<<<1,1>>>(a_d);
gpuErrchk( cudaPeekAtLastError() );
gpuErrchk( cudaMemcpy(a_h, a_d, size * sizeof(int), cudaMemcpyDeviceToHost) );
in which case the cudaMemcpy
call can return either errors which occurred during the kernel execution or those from the memory copy itself. This can be confusing for the beginner, and I would recommend using explicit synchronisation after a kernel launch during debugging to make it easier to understand where problems might be arising.
Note that when using CUDA Dynamic Parallelism, a very similar methodology can and should be applied to any usage of the CUDA runtime API in device kernels, as well as after any device kernel launches:
#include <assert.h>
#define cdpErrchk(ans) { cdpAssert((ans), __FILE__, __LINE__); }
__device__ void cdpAssert(cudaError_t code, const char *file, int line, bool abort=true)
{
if (code != cudaSuccess)
{
printf("GPU kernel assert: %s %s %d\n", cudaGetErrorString(code), file, line);
if (abort) assert(0);
}
}
+
presents one of the relative selectors. Here is a list of all relative selectors:
div p
- All <p>
elements inside of a <div>
element are selected.
div > p
- All <p>
elements whose direct parent is <div>
are selected. It works backwards too (p < div
)
div + p
- All <p>
elements placed immediately after a <div>
element are selected.
div ~ p
- All <p>
elements that are preceded by a <div>
element are selected.
For O(1) random access, which can not be beaten.
If it's a list of constants then you can use Select Case as follows:
Dim Item$: Item = "A"
Select Case Item
Case "A", "B", "C"
' If 'Item' is in the list then do something.
Case Else
' Otherwise do something else.
End Select
Use this code to get Registration ID using GCM
String regId = "", msg = "";
public void getRegisterationID() {
new AsyncTask() {
@Override
protected Object doInBackground(Object...params) {
String msg = "";
try {
if (gcm == null) {
gcm = GoogleCloudMessaging.getInstance(Login.this);
}
regId = gcm.register(YOUR_SENDER_ID);
Log.d("in async task", regId);
// try
msg = "Device registered, registration ID=" + regId;
} catch (IOException ex) {
msg = "Error :" + ex.getMessage();
}
return msg;
}
}.execute(null, null, null);
}
and don't forget to write permissions in manifest...
I hope it helps!
package com.mycompany;
import javax.validation.constraints.Min;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
public class Car {
@NotNull
private String manufacturer;
@NotNull
@Size(min = 2, max = 14)
private String licensePlate;
@Min(2)
private int seatCount;
public Car(String manufacturer, String licencePlate, int seatCount) {
this.manufacturer = manufacturer;
this.licensePlate = licencePlate;
this.seatCount = seatCount;
}
//getters and setters ...
}
@NotNull
, @Size
and @Min
are so-called constraint annotations, that we use to declare constraints, which shall be applied to the fields of a Car instance:
manufacturer
shall never be null
licensePlate
shall never be null and must be between 2 and 14 characters long
seatCount
shall be at least 2.
You could also try explicitly specifying DNS server settings, this worked for me.
In Eclipse:
Window>Preferences>Android>Launch
Default emulator options: -dns-server 8.8.8.8,8.8.4.4
os.getenv('HOSTNAME')
and os.environ['HOSTNAME']
don't always work. In cron jobs and WSDL, HTTP HOSTNAME isn't set. Use this instead:
import socket
socket.gethostbyaddr(socket.gethostname())[0]
It always (even on Windows) returns a fully qualified host name, even if you defined a short alias in /etc/hosts.
If you defined an alias in /etc/hosts then socket.gethostname()
will return the alias. platform.uname()[1]
does the same thing.
I ran into a case where the above didn't work. This is what I'm using now:
import socket
if socket.gethostname().find('.')>=0:
name=socket.gethostname()
else:
name=socket.gethostbyaddr(socket.gethostname())[0]
It first calls gethostname to see if it returns something that looks like a host name, if not it uses my original solution.
You can clone it to get the entire contents, like this:
var html = $("<div />").append($("#div1").clone()).html();
Or make it a plugin, most tend to call this "outerHTML", like this:
jQuery.fn.outerHTML = function() {
return jQuery('<div />').append(this.eq(0).clone()).html();
};
Then you can just call:
var html = $("#div1").outerHTML();
Set args = Wscript.Arguments
For Each arg In args
Wscript.Echo arg
Next
From a command prompt, run the script like this:
CSCRIPT MyScript.vbs 1 2 A B "Arg with spaces"
Will give results like this:
1
2
A
B
Arg with spaces
Is this what you are after? Just index the element and assign a new value.
A[2,1]=150
A
Out[345]:
array([[ 1, 2, 3, 4],
[ 5, 6, 7, 8],
[ 9, 150, 11, 12],
[13, 14, 15, 16]])
Map<String, Integer> map = new HashMap<>();
map.put("test1", 1);
map.put("test2", 2);
Map<String, Integer> map2 = new HashMap<>();
map.forEach(map2::put);
System.out.println("map: " + map);
System.out.println("map2: " + map2);
// Output:
// map: {test2=2, test1=1}
// map2: {test2=2, test1=1}
You can use the forEach
method to do what you want.
What you're doing there is:
map.forEach(new BiConsumer<String, Integer>() {
@Override
public void accept(String s, Integer integer) {
map2.put(s, integer);
}
});
Which we can simplify into a lambda:
map.forEach((s, integer) -> map2.put(s, integer));
And because we're just calling an existing method we can use a method reference, which gives us:
map.forEach(map2::put);
You have to enable auto return in your PayPal account, otherwise it will ignore the return
field.
From the documentation (updated to reflect new layout Jan 2019):
Auto Return is turned off by default. To turn on Auto Return:
- Log in to your PayPal account at https://www.paypal.com or https://www.sandbox.paypal.com The My Account Overview page appears.
- Click the gear icon top right. The Profile Summary page appears.
- Click the My Selling Preferences link in the left column.
- Under the Selling Online section, click the Update link in the row for Website Preferences. The Website Payment Preferences page appears
- Under Auto Return for Website Payments, click the On radio button to enable Auto Return.
- In the Return URL field, enter the URL to which you want your payers redirected after they complete their payments. NOTE: PayPal checks the Return URL that you enter. If the URL is not properly formatted or cannot be validated, PayPal will not activate Auto Return.
- Scroll to the bottom of the page, and click the Save button.
IPN is for instant payment notification. It will give you more reliable/useful information than what you'll get from auto-return.
Documentation for IPN is here: https://www.x.com/sites/default/files/ipnguide.pdf
Online Documentation for IPN: https://developer.paypal.com/docs/classic/ipn/gs_IPN/
The general procedure is that you pass a notify_url
parameter with the request, and set up a page which handles and validates IPN notifications, and PayPal will send requests to that page to notify you when payments/refunds/etc. go through. That IPN handler page would then be the correct place to update the database to mark orders as having been paid.
Here is the function for to check is String is Integer or not ?
public static boolean isStringInteger(String number ){
try{
Integer.parseInt(number);
}catch(Exception e ){
return false;
}
return true;
}
Hi sorry the code for the second one should be:
private static void getAll(CarList c1) {
ArrayList <Car> cars = c1.getAll(); // error incompatible type
for(Car item : cars)
{
System.out.println(item.getMake()
+ " "
+ item.getReg()
);
}
}
I have a class called CarList which contains the arraylist and its method, so in the tester class, i have basically this code to use that CarList class:
CarList c1; c1 = new CarList();
everything else works, such as adding and removing cars and displaying an inidividual car, i just need a code to display all cars in the arraylist.
Of course, the proper way to write a Makefile is to actually document which targets depend on which sources. In the trivial case, the proposed solution will make foo
depend on itself, but of course, make
is smart enough to drop a circular dependency. But if you add a temporary file to your directory, it will "magically" become part of the dependency chain. Better to create an explicit list of dependencies once and for all, perhaps via a script.
GNU make knows how to run gcc
to produce an executable out of a set of .c
and .h
files, so maybe all you really need amounts to
foo: $(wildcard *.h) $(wildcard *.c)
I encountered this error when upgrading from jdk10 to jdk11. Adding the following dependency fixed the problem:
<dependency>
<groupId>org.javassist</groupId>
<artifactId>javassist</artifactId>
<version>3.25.0-GA</version>
</dependency>
Best practice: one form per product is definitely the way to go.
Benefits:
In your specific situation
If you only ever intend to have one form element, in this case a submit
button, one form for all should work just fine.
My recommendation Do one form per product, and change your markup to something like:
<form method="post" action="">
<input type="hidden" name="product_id" value="123">
<button type="submit" name="action" value="add_to_cart">Add to Cart</button>
</form>
This will give you a much cleaner and usable POST
. No parsing. And it will allow you to add more parameters in the future (size, color, quantity, etc).
Note: There's no technical benefit to using
<button>
vs.<input>
, but as a programmer I find it cooler to work withaction=='add_to_cart'
thanaction=='Add to Cart'
. Besides, I hate mixing presentation with logic. If one day you decide that it makes more sense for the button to say "Add" or if you want to use different languages, you could do so freely without having to worry about your back-end code.
8-bit characters with leading 0
'sometext'
.split('')
.map((char) => '00'.concat(char.charCodeAt(0).toString(2)).slice(-8))
.join(' ');
If you need 6 or 7 bit, just change .slice(-8)
One clarification (and a point that confused me):
"remotes/origin/HEAD is the default branch" is not really correct.
remotes/origin/master was the default branch in the remote repository (last time you checked). HEAD is not a branch, it just points to a branch.
Think of HEAD as your working area. When you think of it this way then 'git checkout branchname' makes sense with respect to changing your working area files to be that of a particular branch. You "checkout" branch files into your working area. HEAD for all practical purposes is what is visible to you in your working area.
Check out http://codepad.org. It probably won't solve the poster's problem; but, I think it will be of use to others who read this article.
For those doing some sklearn/numpy post processing (i.e. Deep learning) you can wrap the PIL object with np.array(). This might save you from having to Google it like I did:
from PIL import Image
import requests
import numpy as np
from StringIO import StringIO
response = requests.get(url)
img = np.array(Image.open(StringIO(response.content)))
Use the ALLOW_PAGE_LOCKS clause of ALTER/CREATE INDEX:
ALTER INDEX indexname ON tablename SET (ALLOW_PAGE_LOCKS = OFF);
CREATE TABLE `users` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`dateCreated` datetime DEFAULT CURRENT_TIMESTAMP,
`dateUpdated` datetime DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
PRIMARY KEY (`id`),
UNIQUE KEY `mobile_UNIQUE` (`mobile`)
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;
Stream operations flatMap
and map
accept a function as input.
flatMap
expects the function to return a new stream for each element of the stream and returns a stream which combines all the elements of the streams returned by the function for each element. In other words, with flatMap
, for each element from the source, multiple elements will be created by the function. http://www.zoftino.com/java-stream-examples#flatmap-operation
map
expects the function to return a transformed value and returns a new stream containing the transformed elements. In other words, with map
, for each element from the source, one transformed element will be created by the function.
http://www.zoftino.com/java-stream-examples#map-operation
<video width="320" height="240" controls autoplay>
<source src="movie.mp4" type="video/mp4"> Your browser does not support the video tag.
</video>
Remove autoplay
if you want to disable auto playing video.
You can't do a bulk-update in SSIS within a dataflow task with the OOB components.
The general pattern is to identify your inserts, updates and deletes and push the updates and deletes to a staging table(s) and after the Dataflow Task, use a set-based update or delete in an Execute SQL Task. Look at Andy Leonard's Stairway to Integration Services series. Scroll about 3/4 the way down the article to "Set-Based Updates" to see the pattern.
Stage data
Set based updates
You'll get much better performance with a pattern like this versus using the OLE DB Command
transformation for anything but trivial amounts of data.
If you are into third party tools, I believe CozyRoc and I know PragmaticWorks have a merge destination component.
A more concise--but not necessarily faster--method is to use DataFrame.isin()
and DataFrame.any()
In [27]: n = 10
In [28]: df = DataFrame(randint(4, size=(n, 2)), columns=list('ab'))
In [29]: df
Out[29]:
a b
0 0 0
1 1 1
2 1 1
3 2 3
4 2 3
5 0 2
6 1 2
7 3 0
8 1 1
9 2 2
[10 rows x 2 columns]
In [30]: df.isin([1, 2])
Out[30]:
a b
0 False False
1 True True
2 True True
3 True False
4 True False
5 False True
6 True True
7 False False
8 True True
9 True True
[10 rows x 2 columns]
In [31]: df.isin([1, 2]).any(1)
Out[31]:
0 False
1 True
2 True
3 True
4 True
5 True
6 True
7 False
8 True
9 True
dtype: bool
In [32]: df.loc[df.isin([1, 2]).any(1)]
Out[32]:
a b
1 1 1
2 1 1
3 2 3
4 2 3
5 0 2
6 1 2
8 1 1
9 2 2
[8 rows x 2 columns]
While it is not free (but $39), FireDaemon has worked so well for me I have to recommend it. It will run your batch file but has loads of additional and very useful functionality such as scheduling, service up monitoring, GUI or XML based install of services, dependencies, environmental variables and log management.
I started out using FireDaemon to launch JBoss application servers (run.bat) but shortly after realized that the richness of the FireDaemon configuration abilities allowed me to ditch the batch file and recreate the intent of its commands in the FireDaemon service definition.
There's also a SUPER FireDaemon called Trinity which you might want to look at if you have a large number of Windows servers on which to manage this service (or technically, any service).
First note that with numpy's broadcasting operations it's usually not necessary to duplicate rows and columns. See this and this for descriptions.
But to do this, repeat and newaxis are probably the best way
In [12]: x = array([1,2,3])
In [13]: repeat(x[:,newaxis], 3, 1)
Out[13]:
array([[1, 1, 1],
[2, 2, 2],
[3, 3, 3]])
In [14]: repeat(x[newaxis,:], 3, 0)
Out[14]:
array([[1, 2, 3],
[1, 2, 3],
[1, 2, 3]])
This example is for a row vector, but applying this to a column vector is hopefully obvious. repeat seems to spell this well, but you can also do it via multiplication as in your example
In [15]: x = array([[1, 2, 3]]) # note the double brackets
In [16]: (ones((3,1))*x).transpose()
Out[16]:
array([[ 1., 1., 1.],
[ 2., 2., 2.],
[ 3., 3., 3.]])
Error message looks like this
Error message => ORA-00001: unique constraint (schema.unique_constraint_name) violated
ORA-00001 occurs when: "a query tries to insert a "duplicate" row in a table". It makes an unique constraint to fail, consequently query fails and row is NOT added to the table."
Solution:
Find all columns used in unique_constraint, for instance column a, column b, column c, column d collectively creates unique_constraint and then find the record from source data which is duplicate, using following queries:
-- to find <<owner of the table>> and <<name of the table>> for unique_constraint
select *
from DBA_CONSTRAINTS
where CONSTRAINT_NAME = '<unique_constraint_name>';
Then use Justin Cave's query (pasted below) to find all columns used in unique_constraint:
SELECT column_name, position
FROM all_cons_columns
WHERE constraint_name = <<name of constraint from the error message>>
AND owner = <<owner of the table>>
AND table_name = <<name of the table>>
-- to find duplicates
select column a, column b, column c, column d
from table
group by column a, column b, column c, column d
having count (<any one column used in constraint > ) > 1;
you can either delete that duplicate record from your source data (which was a select query in my particular case, as I experienced it with "Insert into select") or modify to make it unique or change the constraint.
Running:
npm install
from inside your app directory (i.e. where package.json is located) will install the dependencies for your app, rather than install it as a module, as described here. These will be placed in ./node_modules relative to your package.json file (it's actually slightly more complex than this, so check the npm docs here).
You are free to move the node_modules dir to the parent dir of your app if you want, because node's 'require' mechanism understands this. However, if you want to update your app's dependencies with install/update, npm will not see the relocated 'node_modules' and will instead create a new dir, again relative to package.json.
To prevent this, just create a symlink to the relocated node_modules from your app dir:
ln -s ../node_modules node_modules
in case of a similar issue when I'm creating dockerfile I faced the same scenario:- I used below changed in mysql_connect function as:-
if($CONN = @mysqli_connect($DBHOST, $DBUSER, $DBPASS)){ //mysql_query("SET CHARACTER SET 'gbk'", $CONN);
TL;DR:
Modern way is to use COC for intellisense-like completion and one or more language servers (LS) for jump-to-definition (and way way more). For even more functionality (but it's not needed for jump-to-definition) you can install one or more debuggers and get a full blown IDE experience.
Quick-start:
~/.vimrc
:
call plug#begin()
Plug 'neoclide/coc.nvim', {'branch': 'release'}
Plug 'puremourning/vimspector'
call plug#end()
" key mappings example
nmap <silent> gd <Plug>(coc-definition)
nmap <silent> gD <Plug>(coc-implementation)
nmap <silent> gr <Plug>(coc-references)
" there's way more, see `:help coc-key-mappings@en'
:source $MYVIMRC | PlugInstall
to reload VIM config and download plug-insvim
and call :CocInstall coc-marketplace
to get easy access to COC extensions:CocList marketplace
and search for language servers, e.g.:python
to find coc-jedi
,php
to find coc-phpls
, etc.install_gadget.py --help
for available debuggers, e.g.:./install_gadget.py --enable-python
,./install_gadget.py --force-enable-php
, etc.You can jump to definition with gd
, to interface implementation with gD
, find all references with gr
. More keybindings in :help coc-key-mappings@en
.
Full answer:
Language server (LS) is a separate standalone application (one for each programming language) that runs in the background and analyses your whole project in real time exposing extra capabilities to your editor (any editor, not only vim
). You get things like:
Communication with language servers takes place via Language Server Protocol (LSP). Both nvim
and vim8
(or higher) support LSP through plug-ins, the most popular being Conquer of Completion (COC).
List of actively developed language servers and their capabilities is available on Lang Server website. Not all of those are provided by COC extensions. If you want to use one of those you can either write a COC extension yourself or install LS manually and use the combo of following VIM plug-ins as alternative to COC:
Communication with debuggers takes place via Debug Adapter Protocol (DAP). The most popular DAP plug-in for VIM is Vimspector.
Language Server Protocol (LSP) was created by Microsoft for Visual Studio Code and released as an open source project with a permissive MIT license (standardized by collaboration with Red Hat and Codenvy). Later on Microsoft released Debug Adapter Protocol (DAP) as well. Any language supported by VSCode is supported in VIM.
I personally recommend using COC + language servers provided by COC extensions + ALE for extra linting (but with LSP support disabled to avoid conflicts with COC) + Vimspector + debuggers provided by Vimspector (called "gadgets") + following VIM plug-ins:
call plug#begin()
Plug 'neoclide/coc.nvim'
Plug 'dense-analysis/ale'
Plug 'puremourning/vimspector'
Plug 'scrooloose/nerdtree'
Plug 'scrooloose/nerdcommenter'
Plug 'sheerun/vim-polyglot'
Plug 'yggdroot/indentline'
Plug 'tpope/vim-surround'
Plug 'kana/vim-textobj-user'
\| Plug 'glts/vim-textobj-comment'
Plug 'janko/vim-test'
Plug 'vim-scripts/vcscommand.vim'
Plug 'mhinz/vim-signify'
call plug#end()
You can google each to see what they do.
Also, pipe character |
separates VIM commands put in one line which makes it perfect to set up plug-in dependencies, i.e. vim-textobj-comment
doesn't work without vim-textobj-user
so if installation of vim-textobj-user
fails the rest of the line isn't executed. Here pipe is escaped with backslash \
because it's in a new line but for VIM it's still a one-liner.
What about something like:
Alter Table Products
Add LastUpdate varchar(200) null
Do you need something more complex than this?
If you are using Eclipse, then you can setup your JDK (not JRE) in Installed JREs, and then use Open Type (Ctrl + Shift + T), give something like java.util.Collections
You can use zero-length positive look-aheads to specify each of your constraints separately:
(?=.{8,})(?=.*\p{Lu}.*\p{Lu})(?=.*[!@#$&*])(?=.*[0-9])(?=.*\p{Ll}.*\p{Ll})
If your regex engine doesn't support the \p
notation and pure ASCII is enough, then you can replace \p{Lu}
with [A-Z]
and \p{Ll}
with [a-z]
.
read a file name, the file contain the one url per line, like this:
http://www.poolsaboveground.com/apache/hadoop/core/
http://mirrors.sonic.net/apache/hadoop/core/
use command:
python url.py urls.txt
get the result:
Round Trip Time: 253 ms - mirrors.sonic.net
Round Trip Time: 245 ms - www.globalish.com
Round Trip Time: 327 ms - www.poolsaboveground.com
source code(url.py):
import re
import sys
import urlparse
from subprocess import Popen, PIPE
from threading import Thread
class Pinger(object):
def __init__(self, hosts):
for host in hosts:
hostname = urlparse.urlparse(host).hostname
if hostname:
pa = PingAgent(hostname)
pa.start()
else:
continue
class PingAgent(Thread):
def __init__(self, host):
Thread.__init__(self)
self.host = host
def run(self):
p = Popen('ping -n 1 ' + self.host, stdout=PIPE)
m = re.search('Average = (.*)ms', p.stdout.read())
if m: print 'Round Trip Time: %s ms -' % m.group(1), self.host
else: print 'Error: Invalid Response -', self.host
if __name__ == '__main__':
with open(sys.argv[1]) as f:
content = f.readlines()
Pinger(content)
Take a look at this one: http://code.google.com/p/xswingx/
It is not very difficult to implement it by yourself, btw. A couple of listeners and custom renderer and voila.
You can download in the various way you can follow my way. Though files may not download due to 'allow-popups' permission is not set but in your environment, this will work perfectly
<div className="col-6">_x000D_
<a download href="https://www.w3schools.com/images/myw3schoolsimage.jpg" >Test Download </a>_x000D_
</div>
_x000D_
another one this one will also fail due to 'X-Frame-Options' to 'sameorigin'.
<a href="https://www.w3schools.com/images/myw3schoolsimage.jpg" download>_x000D_
<img src="https://www.w3schools.com/images/myw3schoolsimage.jpg" alt="W3Schools" width="104" height="142">_x000D_
</a>
_x000D_
Looping through all the files in the folder is relatively easy:
files = dir('*.csv');
for file = files'
csv = load(file.name);
% Do some stuff
end
If getFiles() returns a java.util.Collection
, !getFiles().isEmpty() && size<5 can be OK.
On the other hand, unless you encapsulate the container which provides method such as boolean sizeBetween(int min, int max)
.
//Component. home.ts :
contacts:IContacts[];
ionViewDidLoad() {
this.rest.getContacts()
.subscribe( res=> this.contacts= res as IContacts[]) ;
// reorderArray. accepts only Arrays
Reorder(indexes){
reorderArray(this.contacts, indexes)
}
// Service . res.ts
getContacts(): Observable<IContacts[]> {
return this.http.get<IContacts[]>(this.apiUrl+"?results=5")
And it works fine
This is good Angular plugin for uploading files, and its free!
For Mysql8->
Query:
SELECT properties, properties->"$.price" FROM book where isbn='978-9730228236' and JSON_EXTRACT(properties, "$.price") > 400;
Data:
mysql> select * from book\G;
*************************** 1. row ***************************
id: 1
isbn: 978-9730228236
properties: {"price": 44.99, "title": "High-Performance Java Persistence", "author": "Vlad Mihalcea", "publisher": "Amazon"}
1 row in set (0.00 sec)
the accepted answer is not correct, and it makes no sens to accept it considering the question
ngAfterViewInit will trigger when the DOM is ready
whine ngOnInit will trigger when the page component is only starting to be created
In my case that happened when uninstalling AspNet 5 RC1 Update 1 to update it for .Net Core 1.0 RC2. so I installed Visual Studio 2015 update 2, selected Microsoft Web Developer tools and everything went back to normal.
To summarize the other answers, in <jre-path>/lib/security/java.security
you can set the value of the property networkaddress.cache.ttl
to adjust how DNS lookups are cached. Note that this is not a system property but a security property. I was able to set this using:
java.security.Security.setProperty("networkaddress.cache.ttl", "<value>");
This can also be set by the system property -Dsun.net.inetaddr.ttl
though this will not override a security property if it is set elsewhere.
I would also like to add that if you are seeing this issue with web services in WebSphere, as I was, setting networkaddress.cache.ttl
will not be enough. You need to set the system property disableWSAddressCaching
to true
. Unlike the time-to-live property, this can be set as a JVM argument or via System.setProperty
).
IBM has a pretty detailed post on how WebSphere handles DNS caching here. The relevant piece to the above is:
To disable address caching for Web services, you need to set an additional JVM custom property disableWSAddressCaching to true. Use this property to disable address caching for Web services. If your system typically runs with lots of client threads, and you encounter lock contention on the wsAddrCache cache, you can set this custom property to true, to prevent caching of the Web services data.
Try this script to create a temporary table TESTTEST and watch the order of precedence as the triggers are called in this order: 1) INSTEAD OF, 2) FOR, 3) AFTER
All of the logic is placed in INSTEAD OF trigger and I have 2 examples of how you might code some scenarios...
Good luck...
CREATE TABLE TESTTEST
(
ID INT,
Modified0 DATETIME,
Modified1 DATETIME
)
GO
CREATE TRIGGER [dbo].[tr_TESTTEST_0] ON [dbo].TESTTEST
INSTEAD OF INSERT,UPDATE,DELETE
AS
BEGIN
SELECT 'INSTEAD OF'
SELECT 'TT0.0'
SELECT * FROM TESTTEST
SELECT *, 'I' Mode
INTO #work
FROM INSERTED
UPDATE #work SET Mode='U' WHERE ID IN (SELECT ID FROM DELETED)
INSERT INTO #work (ID, Modified0, Modified1, Mode)
SELECT ID, Modified0, Modified1, 'D'
FROM DELETED WHERE ID NOT IN (SELECT ID FROM INSERTED)
--Check Security or any other logic to add and remove from #work before processing
DELETE FROM #work WHERE ID=9 -- because you don't want anyone to edit this id?!?!
DELETE FROM #work WHERE Mode='D' -- because you don't want anyone to delete any records
SELECT 'EV'
SELECT * FROM #work
IF(EXISTS(SELECT TOP 1 * FROM #work WHERE Mode='I'))
BEGIN
SELECT 'I0.0'
INSERT INTO dbo.TESTTEST (ID, Modified0, Modified1)
SELECT ID, Modified0, Modified1
FROM #work
WHERE Mode='I'
SELECT 'Cool stuff would happen here if you had FOR INSERT or AFTER INSERT triggers.'
SELECT 'I0.1'
END
IF(EXISTS(SELECT TOP 1 * FROM #work WHERE Mode='D'))
BEGIN
SELECT 'D0.0'
DELETE FROM TESTTEST WHERE ID IN (SELECT ID FROM #work WHERE Mode='D')
SELECT 'Cool stuff would happen here if you had FOR DELETE or AFTER DELETE triggers.'
SELECT 'D0.1'
END
IF(EXISTS(SELECT TOP 1 * FROM #work WHERE Mode='U'))
BEGIN
SELECT 'U0.0'
UPDATE t SET t.Modified0=e.Modified0, t.Modified1=e.Modified1
FROM dbo.TESTTEST t
INNER JOIN #work e ON e.ID = t.ID
WHERE e.Mode='U'
SELECT 'U0.1'
END
DROP TABLE #work
SELECT 'TT0.1'
SELECT * FROM TESTTEST
END
GO
CREATE TRIGGER [dbo].[tr_TESTTEST_1] ON [dbo].TESTTEST
FOR UPDATE
AS
BEGIN
SELECT 'FOR UPDATE'
SELECT 'TT1.0'
SELECT * FROM TESTTEST
SELECT 'I1'
SELECT * FROM INSERTED
SELECT 'D1'
SELECT * FROM DELETED
SELECT 'TT1.1'
SELECT * FROM TESTTEST
END
GO
CREATE TRIGGER [dbo].[tr_TESTTEST_2] ON [dbo].TESTTEST
AFTER UPDATE
AS
BEGIN
SELECT 'AFTER UPDATE'
SELECT 'TT2.0'
SELECT * FROM TESTTEST
SELECT 'I2'
SELECT * FROM INSERTED
SELECT 'D2'
SELECT * FROM DELETED
SELECT 'TT2.1'
SELECT * FROM TESTTEST
END
GO
SELECT 'Start'
INSERT INTO TESTTEST (ID, Modified0) VALUES (9, GETDATE())-- not going to insert
SELECT 'RESTART'
INSERT INTO TESTTEST (ID, Modified0) VALUES (10, GETDATE())--going to insert
SELECT 'RESTART'
UPDATE TESTTEST SET Modified1=GETDATE() WHERE ID=10-- gointo to update
SELECT 'RESTART'
DELETE FROM TESTTEST WHERE ID=10-- not going to DELETE
SELECT 'FINISHED'
SELECT * FROM TESTTEST
DROP TABLE TESTTEST
Ok, thanks to Charles Goodwin for the concept. Here is the answer:
import java.util.*;
public class Test {
public static void main(String[] args) {
List<String> argsList = new ArrayList<String>();
List<String> optsList = new ArrayList<String>();
List<String> doubleOptsList = new ArrayList<String>();
for (int i=0; i < args.length; i++) {
switch (args[i].charAt(0)) {
case '-':
if (args[i].charAt(1) == '-') {
int len = 0;
String argstring = args[i].toString();
len = argstring.length();
System.out.println("Found double dash with command " +
argstring.substring(2, len) );
doubleOptsList.add(argstring.substring(2, len));
} else {
System.out.println("Found dash with command " +
args[i].charAt(1) + " and value " + args[i+1] );
i= i+1;
optsList.add(args[i]);
}
break;
default:
System.out.println("Add a default arg." );
argsList.add(args[i]);
break;
}
}
}
}
file_get_contents()
utilizes the fopen()
wrappers, therefore it is restricted from accessing URLs through the allow_url_fopen
option within php.ini.
You will either need to alter your php.ini to turn this option on or use an alternative method, namely cURL - by far the most popular and, to be honest, standard way to accomplish what you are trying to do.
Step 1: Add new column with integer or numeric as per your requirement
Step 2: Populate data from varchar column to numeric column
Step 3: drop varchar column
Step 4: change new numeric column name as per old varchar column
One other issue on the Windows platform, make sure you are running your command prompt as an Administrative User!
I don't know how many times this has bitten me...
To anyone seeing this later on, as it currently (Aug. 2017) tops google: It is worth mentioning, that this behavior will be altered in Rails 5.2, and has deprecation warnings as of Rails 5.1, as ActiveModel::Dirty changed a bit.
What do I change?
If you're using attribute_changed?
method in the after_*
-callbacks, you'll see a warning like:
DEPRECATION WARNING: The behavior of
attribute_changed?
inside of after callbacks will be changing in the next version of Rails. The new return value will reflect the behavior of calling the method aftersave
returned (e.g. the opposite of what it returns now). To maintain the current behavior, usesaved_change_to_attribute?
instead. (called from some_callback at /PATH_TO/app/models/user.rb:15)
As it mentions, you could fix this easily by replacing the function with saved_change_to_attribute?
. So for example, name_changed?
becomes saved_change_to_name?
.
Likewise, if you're using the attribute_change
to get the before-after values, this changes as well and throws the following:
DEPRECATION WARNING: The behavior of
attribute_change
inside of after callbacks will be changing in the next version of Rails. The new return value will reflect the behavior of calling the method aftersave
returned (e.g. the opposite of what it returns now). To maintain the current behavior, usesaved_change_to_attribute
instead. (called from some_callback at /PATH_TO/app/models/user.rb:20)
Again, as it mentions, the method changes name to saved_change_to_attribute
which returns ["old", "new"]
.
or use saved_changes
, which returns all the changes, and these can be accessed as saved_changes['attribute']
.
Short answer:
$ ssh-keygen -p
This will then prompt you to enter the keyfile location, the old passphrase, and the new passphrase (which can be left blank to have no passphrase).
If you would like to do it all on one line without prompts do:
$ ssh-keygen -p [-P old_passphrase] [-N new_passphrase] [-f keyfile]
Important: Beware that when executing commands they will typically be logged in your ~/.bash_history
file (or similar) in plain text including all arguments provided (i.e. the passphrases in this case). It is, therefore, is recommended that you use the first option unless you have a specific reason to do otherwise.
Notice though that you can still use -f keyfile
without having to specify -P
nor -N
, and that the keyfile defaults to ~/.ssh/id_rsa
, so in many cases, it's not even needed.
You might want to consider using ssh-agent, which can cache the passphrase for a time. The latest versions of gpg-agent also support the protocol that is used by ssh-agent.
Also, you can use Flexbox to achieve the correct result:
.parent {_x000D_
align-items: center; /* For vertical align */_x000D_
background: red;_x000D_
display: flex;_x000D_
height: 250px;_x000D_
/* justify-content: center; <- for horizontal align */_x000D_
width: 250px;_x000D_
}
_x000D_
<div class="parent">_x000D_
<img class="child" src="https://cdn2.iconfinder.com/data/icons/social-icons-circular-black/512/stackoverflow-128.png" />_x000D_
</div>
_x000D_
There are 72 points per inch; if it is sufficient to assume 96 pixels per inch, the formula is rather simple:
points = pixels * 72 / 96
There is a way to get the configured pixels per inch of your display in Windows using GetDeviceCaps
. Microsoft has a guide called "Developing DPI-Aware Applications", look for the section "Creating DPI-Aware Fonts".
The W3C has defined the pixel measurement px
as exactly 1/96th of 1in regardless of the actual resolution of your display, so the above formula should be good for all web work.
I figured out how to use multiple left outer joins in VB.NET using LINQ to SQL:
Dim db As New ContractDataContext()
Dim query = From o In db.Orders _
Group Join v In db.Vendors _
On v.VendorNumber Equals o.VendorNumber _
Into ov = Group _
From x In ov.DefaultIfEmpty() _
Group Join s In db.Status _
On s.Id Equals o.StatusId Into os = Group _
From y In os.DefaultIfEmpty() _
Where o.OrderNumber >= 100000 And o.OrderNumber <= 200000 _
Select Vendor_Name = x.Name, _
Order_Number = o.OrderNumber, _
Status_Name = y.StatusName
I face Similar problem now I understand we have some more option : varStatus="loop", Here will be loop will variable which will hold the index of lop.
It can use for use to read for Zeor base index or 1 one base index.
${loop.count}` it will give 1 starting base index.
${loop.index} it will give 0 base index as normal Index of array
start from 0.
For Example :
<c:forEach var="currentImage" items="${cityBannerImages}" varStatus="loop">
<picture>
<source srcset="${currentImage}" media="(min-width: 1000px)"></source>
<source srcset="${cityMobileImages[loop.count]}" media="(min-width:600px)"></source>
<img srcset="${cityMobileImages[loop.count]}" alt=""></img>
</picture>
</c:forEach>
For more Info please refer this link
You can use the LIKE operator to compare the content of a T-SQL string, e.g.
SELECT * FROM [table] WHERE [field] LIKE '%stringtosearchfor%'.
The percent character '%' is a wild card- in this case it says return any records where [field] at least contains the value "stringtosearchfor".
I got away with simply using two if tags, thought I'd add an answer in case it's of use to anyone else:
<c:if test="${condition}">
...
</c:if>
<c:if test="${!condition}">
...
</c:if>
whilst technically not an if-else
per se, the behaviour is the same and avoids the clunky approach of using the choose
tag, so depending on how complex your requirement is this might be preferable.
In my case, I have DotNet Core 2.2 Web App running on DigitalOcean with docker and nginx as reverse proxy. With this code in Startup.cs I can get the client IP
app.UseForwardedHeaders(new ForwardedHeadersOptions
{
ForwardedHeaders = ForwardedHeaders.All,
RequireHeaderSymmetry = false,
ForwardLimit = null,
KnownNetworks = { new IPNetwork(IPAddress.Parse("::ffff:172.17.0.1"), 104) }
});
::ffff:172.17.0.1 was the ip that I was getting before using
Request.HttpContext.Connection.RemoteIpAddress.ToString();
DAO
is an abstraction of data persistence.
Repository
is an abstraction of a collection of objects.
DAO
would be considered closer to the database, often table-centric.
Repository
would be considered closer to the Domain, dealing only in Aggregate Roots.
Repository
could be implemented using DAO
's, but you wouldn't do the opposite.
Also, a Repository
is generally a narrower interface. It should be simply a collection of objects, with a Get(id)
, Find(ISpecification)
, Add(Entity)
.
A method like Update
is appropriate on a DAO
, but not a Repository
- when using a Repository
, changes to entities would usually be tracked by separate UnitOfWork.
It does seem common to see implementations called a Repository
that is really more of a DAO
, and hence I think there is some confusion about the difference between them.
I wanna Disable an Input Field on a form and when i submit the form the values from the disabled form is not submitted.
Use Case: i am trying to get Lat Lng from Google Map and wanna Display it.. but dont want the user to edit it.
You can use the readonly
property in your input field
<input type="text" readonly="readonly" />
As mentioned in this tutorial, it's as simple as:
To install
brew install gradle
To upgrade
brew upgrade gradle
(using Homebrew of course)
Also see (finally) updated docs.
Cheers :)!
interface supports Python 2.7 and Python 3.4+.
To install interface you have to
pip install python-interface
Example Code:
from interface import implements, Interface
class MyInterface(Interface):
def method1(self, x):
pass
def method2(self, x, y):
pass
class MyClass(implements(MyInterface)):
def method1(self, x):
return x * 2
def method2(self, x, y):
return x + y
You may try to use 'Joiner' class instead of removing the last character from your generated text;
List<String> textList = new ArrayList<>();
textList.add("text1");
textList.add("text2");
textList.add("text3");
Joiner joiner = Joiner.on(",").useForNull("null");
String output = joiner.join(textList);
//output : "text1,text2,text3"
Instead of CharSet.forName, using com.google.common.base.Charsets from Google's Guava (http://code.google.com/p/guava-libraries/wiki/StringsExplained#Charsets) is is slightly nicer:
InputStream is = new ByteArrayInputStream( myString.getBytes(Charsets.UTF_8) );
Which CharSet you use depends entirely on what you're going to do with the InputStream, of course.
onNewIntent()
is meant as entry point for singleTop activities which already run somewhere else in the stack and therefore can't call onCreate()
. From activities lifecycle point of view it's therefore needed to call onPause()
before onNewIntent()
. I suggest you to rewrite your activity to not use these listeners inside of onNewIntent()
. For example most of the time my onNewIntent()
methods simply looks like this:
@Override
protected void onNewIntent(Intent intent) {
super.onNewIntent(intent);
// getIntent() should always return the most recent
setIntent(intent);
}
With all setup logic happening in onResume()
by utilizing getIntent()
.
import csv
with open(..., 'wb') as myfile:
wr = csv.writer(myfile, quoting=csv.QUOTE_ALL)
wr.writerow(mylist)
Edit: this only works with python 2.x.
To make it work with python 3.x replace wb
with w
(see this SO answer)
with open(..., 'w', newline='') as myfile:
wr = csv.writer(myfile, quoting=csv.QUOTE_ALL)
wr.writerow(mylist)
select sequence_owner, sequence_name from dba_sequences;
DBA_SEQUENCES -- all sequences that exist
ALL_SEQUENCES -- all sequences that you have permission to see
USER_SEQUENCES -- all sequences that you own
Note that since you are, by definition, the owner of all the sequences returned from USER_SEQUENCES
, there is no SEQUENCE_OWNER
column in USER_SEQUENCES
.
When you COUNT(*)
it takes in count column indexes, so it will be the best result. Mysql with MyISAM engine actually stores row count, it doensn't count all rows each time you try to count all rows. (based on primary key's column)
Using PHP to count rows is not very smart, because you have to send data from mysql to php. Why do it when you can achieve the same on the mysql side?
If the COUNT(*)
is slow, you should run EXPLAIN
on the query, and check if indexes are really used, and where should they be added.
The following is not the fastest way, but there is a case, where COUNT(*)
doesn't really fit - when you start grouping results, you can run into problem, where COUNT
doesn't really count all rows.
The solution is SQL_CALC_FOUND_ROWS
. This is usually used when you are selecting rows but still need to know the total row count (for example, for paging).
When you select data rows, just append the SQL_CALC_FOUND_ROWS
keyword after SELECT:
SELECT SQL_CALC_FOUND_ROWS [needed fields or *] FROM table LIMIT 20 OFFSET 0;
After you have selected needed rows, you can get the count with this single query:
SELECT FOUND_ROWS();
FOUND_ROWS()
has to be called immediately after the data selecting query.
In conclusion, everything actually comes down to how many entries you have and what is in the WHERE statement. You should really pay attention on how indexes are being used, when there are lots of rows (tens of thousands, millions, and up).
#python3
import datetime
print(
'1: test-{date:%Y-%m-%d_%H:%M:%S}.txt'.format( date=datetime.datetime.now() )
)
d = datetime.datetime.now()
print( "2a: {:%B %d, %Y}".format(d))
# see the f" to tell python this is a f string, no .format
print(f"2b: {d:%B %d, %Y}")
print(f"3: Today is {datetime.datetime.now():%Y-%m-%d} yay")
1: test-2018-02-14_16:40:52.txt
2a: March 04, 2018
2b: March 04, 2018
3: Today is 2018-11-11 yay
Description:
Using the new string format to inject value into a string at placeholder {}, value is the current time.
Then rather than just displaying the raw value as {}, use formatting to obtain the correct date format.
https://docs.python.org/3/library/string.html#formatexamples
There is a library called Chameleon (https://github.com/viccalexander/Chameleon) which one can use for gradient colors. It even has styles of gradient to implement. This is how you can add it in swift 4 podfile pod 'ChameleonFramework/Swift', :git => 'https://github.com/ViccAlexander/Chameleon.git', :branch => 'wip/swift4'
import ChameleonFramework
let colors:[UIColor] = [
UIColor.flatPurpleColorDark(),
UIColor.flatWhiteColor()
]
view.backgroundColor = GradientColor(.TopToBottom, frame: view.frame, colors: colors)
As of 2021 insted of null i had to add {} in order to make it work!
axios.post(
url,
{},
{
params: {
key,
checksum
}
}
)
.then(response => {
return success(response);
})
.catch(error => {
return fail(error);
});
New Table...
It could be some other line as well. PHP is not always that exact.
Probably you are just missing a semicolon on previous line.
How to reproduce this error, put this in a file called a.php
:
<?php
$a = 5
$b = 7; // Error happens here.
print $b;
?>
Run it:
eric@dev ~ $ php a.php
PHP Parse error: syntax error, unexpected T_VARIABLE in
/home/el/code/a.php on line 3
Explanation:
The PHP parser converts your program to a series of tokens. A T_VARIABLE
is a Token of type VARIABLE. When the parser processes tokens, it tries to make sense of them, and throws errors if it receives a variable where none is allowed.
In the simple case above with variable $b
, the parser tried to process this:
$a = 5 $b = 7;
The PHP parser looks at the $b after the 5 and says "that is unexpected".
Here is my code:
background: #e8e3e3; /* Old browsers */
background: -moz-linear-gradient(top, rgba(232, 227, 227, 0.95) 0%, rgba(246, 242, 242, 0.95) 100%); /* FF3.6+ */
background: -webkit-gradient(linear, left top, left bottom, color-stop(0%,rgba(232, 227, 227, 0.95)), color-stop(100%,rgba(246, 242, 242, 0.95))); /* Chrome,Safari4+ */
background: -webkit-linear-gradient(top, rgba(232, 227, 227, 0.95) 0%,rgba(246, 242, 242, 0.95) 100%); /* Chrome10+,Safari5.1+ */
background: -o-linear-gradient(top, rgba(232, 227, 227, 0.95) 0%,rgba(246, 242, 242, 0.95) 100%); /* Opera 11.10+ */
background: -ms-linear-gradient(top, rgba(232, 227, 227, 0.95) 0%,rgba(246, 242, 242, 0.95) 100%); /* IE10+ */
background: linear-gradient(to bottom, rgba(232, 227, 227, 0.95) 0%,rgba(246, 242, 242, 0.95) 100%); /* W3C */
filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='rgba(232, 227, 227, 0.95)', endColorstr='rgba(246, 242, 242, 0.95)',GradientType=0 ); /* IE6-9 */
Use Range("A1").Text
instead of .Value
post comment edit:
Why?
Because the .Text
property of Range object returns what is literally visible in the spreadsheet, so if you cell displays for example i100l:25he*_92
then <- Text
will return exactly what it in the cell including any formatting.
The .Value
and .Value2
properties return what's stored in the cell under the hood excluding formatting. Specially .Value2
for date types, it will return the decimal representation.
If you want to dig deeper into the meaning and performance, I just found this article
which seems like a good guide
another edit
Here you go @Santosh
type in (MANUALLY) the values from the DEFAULT (col A) to other columns
Do not format column A at all
Format column B as Text
Format column C as Date[dd/mm/yyyy]
Format column D as Percentage
now,
paste this code in a module
Sub main()
Dim ws As Worksheet, i&, j&
Set ws = Sheets(1)
For i = 3 To 7
For j = 1 To 4
Debug.Print _
"row " & i & vbTab & vbTab & _
Cells(i, j).Text & vbTab & _
Cells(i, j).Value & vbTab & _
Cells(i, j).Value2
Next j
Next i
End Sub
and Analyse
the output! Its really easy and there isn't much more i can do to help :)
.TEXT .VALUE .VALUE2
row 3 hello hello hello
row 3 hello hello hello
row 3 hello hello hello
row 3 hello hello hello
row 4 1 1 1
row 4 1 1 1
row 4 01/01/1900 31/12/1899 1
row 4 1.00% 0.01 0.01
row 5 helo1$$ helo1$$ helo1$$
row 5 helo1$$ helo1$$ helo1$$
row 5 helo1$$ helo1$$ helo1$$
row 5 helo1$$ helo1$$ helo1$$
row 6 63 63 63
row 6 =7*9 =7*9 =7*9
row 6 03/03/1900 03/03/1900 63
row 6 6300.00% 63 63
row 7 29/05/2013 29/05/2013 41423
row 7 29/05/2013 29/05/2013 29/05/2013
row 7 29/05/2013 29/05/2013 41423
row 7 29/05/2013% 29/05/2013% 29/05/2013%
I came up with a mix of defining a class like David's answer, but not requiring a Where class to go with it. It looks something like:
var resultsGroupings = resultsRecords.GroupBy(r => new { r.IdObj1, r.IdObj2, r.IdObj3})
.Select(r => new ResultGrouping {
IdObj1= r.Key.IdObj1,
IdObj2= r.Key.IdObj2,
IdObj3= r.Key.IdObj3,
Results = r.ToArray(),
Count = r.Count()
});
private class ResultGrouping
{
public short IdObj1{ get; set; }
public short IdObj2{ get; set; }
public int IdObj3{ get; set; }
public ResultCsvImport[] Results { get; set; }
public int Count { get; set; }
}
Where resultRecords
is my initial list I'm grouping, and its a List<ResultCsvImport>
. Note that the idea here to is that, I'm grouping by 3 columns, IdObj1 and IdObj2 and IdObj3
If you prefer immutable data objects, or if you just dont want to be destructive to the input list, you can use Guava's predicates.
ImmutableList.copyOf(Iterables.filter(tourists, Predicates.notNull()))
sc queryex <service name>
taskkill /F /PID <Service PID>
eg
-Confirm
is a switch in most PowerShell cmdlets that forces the cmdlet to ask for user confirmation. What you're actually looking for is the Read-Host
cmdlet:
$confirmation = Read-Host "Are you Sure You Want To Proceed:"
if ($confirmation -eq 'y') {
# proceed
}
or the PromptForChoice()
method of the host user interface:
$title = 'something'
$question = 'Are you sure you want to proceed?'
$choices = New-Object Collections.ObjectModel.Collection[Management.Automation.Host.ChoiceDescription]
$choices.Add((New-Object Management.Automation.Host.ChoiceDescription -ArgumentList '&Yes'))
$choices.Add((New-Object Management.Automation.Host.ChoiceDescription -ArgumentList '&No'))
$decision = $Host.UI.PromptForChoice($title, $question, $choices, 1)
if ($decision -eq 0) {
Write-Host 'confirmed'
} else {
Write-Host 'cancelled'
}
Edit:
As M-pixel pointed out in the comments the code could be simplified further, because the choices can be passed as a simple string array.
$title = 'something'
$question = 'Are you sure you want to proceed?'
$choices = '&Yes', '&No'
$decision = $Host.UI.PromptForChoice($title, $question, $choices, 1)
if ($decision -eq 0) {
Write-Host 'confirmed'
} else {
Write-Host 'cancelled'
}
To turn on "Install via USB" and "USB Debugging(Security changes)" need to sign in to xiaomi account then these 2 can be turned on and work with redmi as developer
Note:When turning on USB Debugging(Security changes) few security alerts will be poped up all need to be accepted to work on developer mode
I had the similar problem. Just after adding below dependency
<dependency>
<groupId>xerces</groupId>
<artifactId>xercesImpl</artifactId>
<version>2.9.1</version>
<type>bundle</type>
</dependency>
caused the problem. I deleted that dependency even then I'm getting the same error. I don't know what happened. I tried updating the maven dependency configuration which solved my issue.
If you are trying to allocate space for an array of pointers, such as
char** my_array_of_strings; // or some array of pointers such as int** or even void**
then you will need to consider word size (8 bytes in a 64-bit system, 4 bytes in a 32-bit system) when allocating space for n pointers. The size of a pointer is the same of your word size.
So while you may wish to allocate space for n pointers, you are actually going to need n times 8 or 4 (for 64-bit or 32-bit systems, respectively)
To avoid overflowing your allocated memory for n elements of 8 bytes:
my_array_of_strings = (char**) malloc( n * 8 ); // for 64-bit systems
my_array_of_strings = (char**) malloc( n * 4 ); // for 32-bit systems
This will return a block of n pointers, each consisting of 8 bytes (or 4 bytes if you're using a 32-bit system)
I have noticed that Linux will allow you to use all n pointers when you haven't compensated for word size, but when you try to free that memory it realizes its mistake and it gives out that rather nasty error. And it is a bad one, when you overflow allocated memory, many security issues lie in wait.
I suggest loganfsmyths method, using an array to hold the data.
var bufs = [];
stdout.on('data', function(d){ bufs.push(d); });
stdout.on('end', function(){
var buf = Buffer.concat(bufs);
}
IN my current working example, i am working with GRIDfs and npm's Jimp.
var bucket = new GridFSBucket(getDBReference(), { bucketName: 'images' } );
var dwnldStream = bucket.openDownloadStream(info[0]._id);// original size
dwnldStream.on('data', function(chunk) {
data.push(chunk);
});
dwnldStream.on('end', function() {
var buff =Buffer.concat(data);
console.log("buffer: ", buff);
jimp.read(buff)
.then(image => {
console.log("read the image!");
IMAGE_SIZES.forEach( (size)=>{
resize(image,size);
});
});
I did some other research
with a string method but that did not work, per haps because i was reading from an image file, but the array method did work.
const DISCLAIMER = "DONT DO THIS";
var data = "";
stdout.on('data', function(d){
bufs+=d;
});
stdout.on('end', function(){
var buf = Buffer.from(bufs);
//// do work with the buffer here
});
When i did the string method i got this error from npm jimp
buffer: <Buffer 00 00 00 00 00>
{ Error: Could not find MIME for Buffer <null>
basically i think the type coersion from binary to string didnt work so well.
We can define maximum pool size in following way:
<pool>
<min-pool-size>5</min-pool-size>
<max-pool-size>200</max-pool-size>
<prefill>true</prefill>
<use-strict-min>true</use-strict-min>
<flush-strategy>IdleConnections</flush-strategy>
</pool>
That is, you are referencing an image, but instead of providing an external url, the png image data is in the url itself, embedded in the style sheet. data:image/png;base64 tells the browser that the data is inline, is a png image and is in this case base64 encoded. The encoding is needed because png images can contain bytes that are invalid inside a HTML document (or within the HTTP protocol even).
Neither
UPDATE … IF (@@ROWCOUNT = 0) INSERT
nor
IF EXISTS(...) UPDATE ELSE INSERT
patterns work as expected under high concurrency. Both may fail. Both may fail very frequently. MERGE is the king - it holds up much better.Let us do some stress testing and see for ourselves.
Here is the table we shall be using:
CREATE TABLE dbo.TwoINTs
(
ID INT NOT NULL PRIMARY KEY,
i1 INT NOT NULL ,
i2 INT NOT NULL ,
version ROWVERSION
) ;
GO
INSERT INTO dbo.TwoINTs
( ID, i1, i2 )
VALUES ( 1, 0, 0 ) ;
IF EXISTS(…) THEN pattern frequently fails under high concurrency.
Let us insert or update rows in a loop using the following simple logic: if a row with given ID exists, update it, and otherwise insert a new one. The following loop implements this logic. Cut and paste it into two tabs, switch into text mode in both tabs, and run them simultaneously.
-- hit Ctrl+T to execute in text mode
SET NOCOUNT ON ;
DECLARE @ID INT ;
SET @ID = 0 ;
WHILE @ID > -100000
BEGIN ;
SET @ID = ( SELECT MIN(ID)
FROM dbo.TwoINTs
) - 1 ;
BEGIN TRY ;
BEGIN TRANSACTION ;
IF EXISTS ( SELECT *
FROM dbo.TwoINTs
WHERE ID = @ID )
BEGIN ;
UPDATE dbo.TwoINTs
SET i1 = 1
WHERE ID = @ID ;
END ;
ELSE
BEGIN ;
INSERT INTO dbo.TwoINTs
( ID, i1, i2 )
VALUES ( @ID, 0, 0 ) ;
END ;
COMMIT ;
END TRY
BEGIN CATCH ;
ROLLBACK ;
SELECT error_message() ;
END CATCH ;
END ;
When we run this script simultaneously in two tabs, we shall immediately get a huge amount of primary key violations in both tabs. This demonstrates how unreliable the IF EXISTS pattern is when it executes under high concurrency.
Note: this example also demonstrates that it is not safe to use SELECT MAX(ID)+1 or SELECT MIN(ID)-1 as the next available unique value if we do it under concurrency.
Typically you model the enum itself as a class with the enum
stereotype
Do you want to this code?
public static enum FieldIndex {
HDB_TRX_ID, //TRX ID
HDB_SYS_ID //SYSTEM ID
}
public String print(ArrayList<String> itemName){
return itemName.get(FieldIndex.HDB_TRX_ID.ordinal());
}
You create the same maps.
But you can fill the difference when you will use it. With first case you'll be able to use special HashMap methods (but I don't remember anyone realy useful), and you'll be able to pass it as a HashMap parameter:
public void foo (HashMap<String, Object) { ... }
...
HashMap<String, Object> m1 = ...;
Map<String, Object> m2 = ...;
foo (m1);
foo ((HashMap<String, Object>)m2);
For me it is like this,
Access
Storage
Size
Insertion/Deletion
Please use this
window.open("url","_self");
- The first parameter "url" is full path of which page you want to open.
- The second parameter "_self", It's used for open page in same tab. You want open the page in another tab please use "_blank".
To check whether select box has any values:
if( $('#fruit_name').has('option').length > 0 ) {
To check whether selected value is empty:
if( !$('#fruit_name').val() ) {
Does m
really need to be a data.frame()
or will a matrix()
suffice?
m <- matrix(0, ncol = 30, nrow = 2)
You can wrap a data.frame()
around that if you need to:
m <- data.frame(m)
or all in one line: m <- data.frame(matrix(0, ncol = 30, nrow = 2))
If you've got a Mac the easiest way to split those would be to use DfontSplitter, available at https://peter.upfold.org.uk/projects/dfontsplitter
The Windows version they provide doesn't work with ttc files.
You can use map() function:
a = list(map(lambda x: x - 13, a))
return RedirectToAction("ProductImageManager","Index", new { id=id });
Here is an invalid parameters order, should be an action first
AND
ensure your routing table is correct
You can use DataTable.Select
:
var strExpr = "CostumerID = 1 AND OrderCount > 2";
var strSort = "OrderCount DESC";
// Use the Select method to find all rows matching the filter.
foundRows = ds.Table[0].Select(strExpr, strSort);
Or you can use DataView
:
ds.Tables[0].DefaultView.RowFilter = strExpr;
UPDATE I'm not sure why you want to have a DataSet returned. But I'd go with the following solution:
var dv = ds.Tables[0].DefaultView;
dv.RowFilter = strExpr;
var newDS = new DataSet();
var newDT = dv.ToTable();
newDS.Tables.Add(newDT);
Try this,
$('td').click(function(){
var row_index = $(this).parent().index();
var col_index = $(this).index();
});
If you need the index of table contain td then you can change it to
var row_index = $(this).parent('table').index();
Main reason: Enums help you to write well-structured code where the semantic meaning of parameters is clear and strongly-typed at compile time - for all the reasons other answers have given.
Quid pro quo: in Java out of the box, an Enum's array of members is final. That's normally good as it helps value safety and testing, but in some situations it could be a drawback, for example if you are extending existing base code perhaps from a library. In contrast, if the same data is in a class with static fields you can easily add new instances of that class at runtime (you might also need to write code to add these to any Iterable you have for that class). But this behaviour of Enums can be changed: using reflection you can add new members at runtime or replace existing members, though this should probably only be done in specialised situations where there is no alternative: i.e. it's a hacky solution and may produce unexpected issues, see my answer on Can I add and remove elements of enumeration at runtime in Java.
The error you gave is due to the fact that in python, dictionary keys must be immutable types (if key can change, there will be problems), and list is a mutable type.
Your error says that you try to use a list as dictionary key, you'll have to change your list into tuples if you want to put them as keys in your dictionary.
According to the python doc :
The only types of values not acceptable as keys are values containing lists or dictionaries or other mutable types that are compared by value rather than by object identity, the reason being that the efficient implementation of dictionaries requires a key’s hash value to remain constant
7zip
(7za) can be used for adding/updating files/directories nicely:
Example:
Replacing (regardless of file date) the MANIFEST.MF
file in a JAR file. The /source/META-INF
directory contains the MANIFEST.MF
file that you want to put into the jar
(zip):
7za a /tmp/file.jar /source/META-INF/
Only update (does not replace the target if the source is older)
7za u /tmp/file.jar /source/META-INF/
I have had another issue giving me a 504. It's pretty far out but I'll write it up here for googlers and posterity...
I have a client calling an IIS hosted webservice hosted in another domain (Active Directory). There is not full trust between the client domain and the domain where the web services is hosted. One of the many challenges with the selective trust between these two domains is that Kerberos does not work when calling from one to the other.
In my case I was trying to call a service in another domain where I found out that a SPN was registered. Like this : http/myurl.test.local (just an example)
This forces the call to use Kerberos instead of letting it fall back to NTLM and this gave me a 405 back from the calling server.
After removing the spn and allowing the call to fall back to NTLM, it works fine.
As I said ... this is not something you are likely to run into, as most organizations do not venture into having such a selective trusts between two domains ... But it gives a 504 and caused me a few (more) gray hairs.
Expanding on @Eric's answer, you need to be careful that the keyWindow is actually the window you want. If you are trying to utilize this method after tapping something in an alert view for example, the keyWindow will actually be the alert's window, and that will cause problems for you no doubt. This happened to me in the wild when handling deep links via an alert and caused SIGABRTs with NO STACK TRACE. Total bitch to debug.
Here's the code I'm using now:
- (UIViewController *)getTopMostViewController {
UIWindow *topWindow = [UIApplication sharedApplication].keyWindow;
if (topWindow.windowLevel != UIWindowLevelNormal) {
NSArray *windows = [UIApplication sharedApplication].windows;
for(topWindow in windows)
{
if (topWindow.windowLevel == UIWindowLevelNormal)
break;
}
}
UIViewController *topViewController = topWindow.rootViewController;
while (topViewController.presentedViewController) {
topViewController = topViewController.presentedViewController;
}
return topViewController;
}
Feel free to mix this with whatever flavor of retrieving the top view controller you like from the other answers on this question.
I have found that this is sometimes caused by running a MS Dos version of a file. If that's the case dos2ux should fix that.
dos2ux file1 > file2
std::queue<myclass*>
that's it
Welcome to bash. It's an old, dark and mysterious thing, capable of great magic. :-)
The option you're asking about is for the find
command though, not for bash. From your command line, you can man find
to see the options.
The one you're looking for is -o
for "or":
list="$(find /home/user/Desktop -name '*.bmp' -o -name '*.txt')"
That said ... Don't do this. Storage like this may work for simple filenames, but as soon as you have to deal with special characters, like spaces and newlines, all bets are off. See ParsingLs for details.
$ touch 'one.txt' 'two three.txt' 'foo.bmp'
$ list="$(find . -name \*.txt -o -name \*.bmp -type f)"
$ for file in $list; do if [ ! -f "$file" ]; then echo "MISSING: $file"; fi; done
MISSING: ./two
MISSING: three.txt
Pathname expansion (globbing) provides a much better/safer way to keep track of files. Then you can also use bash arrays:
$ a=( *.txt *.bmp )
$ declare -p a
declare -a a=([0]="one.txt" [1]="two three.txt" [2]="foo.bmp")
$ for file in "${a[@]}"; do ls -l "$file"; done
-rw-r--r-- 1 ghoti staff 0 24 May 16:27 one.txt
-rw-r--r-- 1 ghoti staff 0 24 May 16:27 two three.txt
-rw-r--r-- 1 ghoti staff 0 24 May 16:27 foo.bmp
The Bash FAQ has lots of other excellent tips about programming in bash.
An example of how to implement it:
public bool ValidateSocialSecNumber(string socialSecNumber)
{
//Accepts only 10 digits, no more no less. (Like Mike's answer)
Regex pattern = new Regex(@"(?<!\d)\d{10}(?!\d)");
if(pattern.isMatch(socialSecNumber))
{
//Do something
return true;
}
else
{
return false;
}
}
You could've also done it in another way by e.g. using Match
and then wrapping a try-catch block around the pattern matching. However, if a wrong input is given quite often, it's quite expensive to throw an exception. Thus, I prefer the above way, in simple cases at least.
You can quickly serve static content in JAVA Spring-boot App via thymeleaf
(ref: source)
I assume you have already added Spring Boot plugin apply plugin: 'org.springframework.boot'
and the necessary buildscript
Then go ahead and ADD thymeleaf to your build.gradle
==>
dependencies {
compile('org.springframework.boot:spring-boot-starter-web')
compile("org.springframework.boot:spring-boot-starter-thymeleaf")
testCompile('org.springframework.boot:spring-boot-starter-test')
}
Lets assume you have added home.html at src/main/resources
To serve this file, you will need to create a controller.
package com.ajinkya.th.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
public class HomePageController {
@RequestMapping("/")
public String homePage() {
return "home";
}
}
Thats it ! Now restart your gradle server. ./gradlew bootRun
Using an absolute or relative string as the filename.
name_of_file = input("What is the name of the file: ")
completeName = '/home/user/Documents'+ name_of_file + ".txt"
file1 = open(completeName , "w")
toFile = input("Write what you want into the field")
file1.write(toFile)
file1.close()
I found this multidrop-down menu which work great in all device.
Also, have hover style
It supports multi-level submenus with bootstrap 4.
$( document ).ready( function () {_x000D_
$( '.navbar a.dropdown-toggle' ).on( 'click', function ( e ) {_x000D_
var $el = $( this );_x000D_
var $parent = $( this ).offsetParent( ".dropdown-menu" );_x000D_
$( this ).parent( "li" ).toggleClass( 'show' );_x000D_
_x000D_
if ( !$parent.parent().hasClass( 'navbar-nav' ) ) {_x000D_
$el.next().css( { "top": $el[0].offsetTop, "left": $parent.outerWidth() - 4 } );_x000D_
}_x000D_
$( '.navbar-nav li.show' ).not( $( this ).parents( "li" ) ).removeClass( "show" );_x000D_
return false;_x000D_
} );_x000D_
} );
_x000D_
.navbar-light .navbar-nav .nav-link {_x000D_
color: rgb(64, 64, 64);_x000D_
}_x000D_
.btco-menu li > a {_x000D_
padding: 10px 15px;_x000D_
color: #000;_x000D_
}_x000D_
_x000D_
.btco-menu .active a:focus,_x000D_
.btco-menu li a:focus ,_x000D_
.navbar > .show > a:focus{_x000D_
background: transparent;_x000D_
outline: 0;_x000D_
}_x000D_
_x000D_
.dropdown-menu .show > .dropdown-toggle::after{_x000D_
transform: rotate(-90deg);_x000D_
}
_x000D_
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/css/bootstrap.min.css" integrity="sha384-rwoIResjU2yc3z8GV/NPeZWAv56rSmLldC3R/AZzGRnGxQQKnKkoFVhFQhNUwEyJ" crossorigin="anonymous">_x000D_
_x000D_
<script src="https://code.jquery.com/jquery-3.1.1.slim.min.js" integrity="sha384-A7FZj7v+d/sdmMqp/nOQwliLvUsJfDHW+k9Omg/a/EheAdgtzNs3hpfag6Ed950n" crossorigin="anonymous"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/tether/1.4.0/js/tether.min.js" integrity="sha384-DztdAPBWPRXSA/3eYEEUWrWCy7G5KFbe8fFjk5JAIxUYHKkDx6Qin1DkWx51bBrb" crossorigin="anonymous"></script>_x000D_
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/js/bootstrap.min.js" integrity="sha384-vBWWzlZJ8ea9aCX4pEW3rVHjgjt7zpkNpZk+02D9phzyeVkE+jo0ieGizqPLForn" crossorigin="anonymous"></script>_x000D_
_x000D_
<nav class="navbar navbar-toggleable-md navbar-light bg-faded btco-menu">_x000D_
<button class="navbar-toggler navbar-toggler-right" type="button" data-toggle="collapse" data-target="#navbarNavDropdown" aria-controls="navbarNavDropdown" aria-expanded="false" aria-label="Toggle navigation">_x000D_
<span class="navbar-toggler-icon"></span>_x000D_
</button>_x000D_
<a class="navbar-brand" href="#">Navbar</a>_x000D_
<div class="collapse navbar-collapse" id="navbarNavDropdown">_x000D_
<ul class="navbar-nav">_x000D_
<li class="nav-item active">_x000D_
<a class="nav-link" href="#">Home <span class="sr-only">(current)</span></a>_x000D_
</li>_x000D_
<li class="nav-item">_x000D_
<a class="nav-link" href="#">Features</a>_x000D_
</li>_x000D_
<li class="nav-item">_x000D_
<a class="nav-link" href="#">Pricing</a>_x000D_
</li>_x000D_
<li class="nav-item dropdown">_x000D_
<a class="nav-link dropdown-toggle" href="https://bootstrapthemes.co" id="navbarDropdownMenuLink" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">Dropdown link</a>_x000D_
<ul class="dropdown-menu" aria-labelledby="navbarDropdownMenuLink">_x000D_
<li><a class="dropdown-item" href="#">Action</a></li>_x000D_
<li><a class="dropdown-item" href="#">Another action</a></li>_x000D_
<li><a class="dropdown-item dropdown-toggle" href="#">Submenu</a>_x000D_
<ul class="dropdown-menu">_x000D_
<li><a class="dropdown-item" href="#">Submenu action</a></li>_x000D_
<li><a class="dropdown-item" href="#">Another submenu action</a></li>_x000D_
_x000D_
<li><a class="dropdown-item dropdown-toggle" href="#">Subsubmenu</a>_x000D_
<ul class="dropdown-menu">_x000D_
<li><a class="dropdown-item" href="#">Subsubmenu action</a></li>_x000D_
<li><a class="dropdown-item" href="#">Another subsubmenu action</a></li>_x000D_
</ul>_x000D_
</li>_x000D_
<li><a class="dropdown-item dropdown-toggle" href="#">Second subsubmenu</a>_x000D_
<ul class="dropdown-menu">_x000D_
<li><a class="dropdown-item" href="#">Subsubmenu action</a></li>_x000D_
<li><a class="dropdown-item" href="#">Another subsubmenu action</a></li>_x000D_
</ul>_x000D_
</li>_x000D_
</ul>_x000D_
</li>_x000D_
</ul>_x000D_
</li>_x000D_
</ul>_x000D_
</div>_x000D_
</nav>
_x000D_
You'll need pattern recognition for that. To determine small differences between two images, Hopfield nets work fairly well and are quite easy to implement. I don't know any available implementations, though.
The standard library includes the ordered and the unordered map (std::map
and std::unordered_map
) containers. In an ordered map the elements are sorted by the key, insert and access is in O(log n). Usually the standard library internally uses red black trees for ordered maps. But this is just an implementation detail. In an unordered map insert and access is in O(1). It is just another name for a hashtable.
An example with (ordered) std::map
:
#include <map>
#include <iostream>
#include <cassert>
int main(int argc, char **argv)
{
std::map<std::string, int> m;
m["hello"] = 23;
// check if key is present
if (m.find("world") != m.end())
std::cout << "map contains key world!\n";
// retrieve
std::cout << m["hello"] << '\n';
std::map<std::string, int>::iterator i = m.find("hello");
assert(i != m.end());
std::cout << "Key: " << i->first << " Value: " << i->second << '\n';
return 0;
}
Output:
23 Key: hello Value: 23
If you need ordering in your container and are fine with the O(log n) runtime then just use std::map
.
Otherwise, if you really need a hash-table (O(1) insert/access), check out std::unordered_map
, which has a similar to std::map
API (e.g. in the above example you just have to search and replace map
with unordered_map
).
The unordered_map
container was introduced with the C++11 standard revision. Thus, depending on your compiler, you have to enable C++11 features (e.g. when using GCC 4.8 you have to add -std=c++11
to the CXXFLAGS).
Even before the C++11 release GCC supported unordered_map
- in the namespace std::tr1
. Thus, for old GCC compilers you can try to use it like this:
#include <tr1/unordered_map>
std::tr1::unordered_map<std::string, int> m;
It is also part of boost, i.e. you can use the corresponding boost-header for better portability.
if you are ok with null, undefined, NaN, 0, and false all casting to '' then (s ? s+'' : '')
is faster.
see http://jsperf.com/cast-to-string/8
note - there are significant differences across browsers at this time.
Note: This assumes that you will declare constants for row and column indexes named COLUMN_HEADING_ROW
, FIRST_COL
, and LAST_COL
, and that _xlSheet
is the name of the ExcelSheet
(using Microsoft.Interop.Excel
)
First, define the range:
var columnHeadingsRange = _xlSheet.Range[
_xlSheet.Cells[COLUMN_HEADING_ROW, FIRST_COL],
_xlSheet.Cells[COLUMN_HEADING_ROW, LAST_COL]];
Then, set the background color of that range:
columnHeadingsRange.Interior.Color = XlRgbColor.rgbSkyBlue;
Finally, set the font color:
columnHeadingsRange.Font.Color = XlRgbColor.rgbWhite;
And here's the code combined:
var columnHeadingsRange = _xlSheet.Range[
_xlSheet.Cells[COLUMN_HEADING_ROW, FIRST_COL],
_xlSheet.Cells[COLUMN_HEADING_ROW, LAST_COL]];
columnHeadingsRange.Interior.Color = XlRgbColor.rgbSkyBlue;
columnHeadingsRange.Font.Color = XlRgbColor.rgbWhite;
Or you could try:
I found it to be pretty nice to do it like this (usage in the view):
@Html.HiddenJsonFor(m => m.TrackingTypes)
Here is the according helper method Extension class:
public static class DataHelpers
{
public static MvcHtmlString HiddenJsonFor<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> expression)
{
return HiddenJsonFor(htmlHelper, expression, (IDictionary<string, object>) null);
}
public static MvcHtmlString HiddenJsonFor<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> expression, object htmlAttributes)
{
return HiddenJsonFor(htmlHelper, expression, HtmlHelper.AnonymousObjectToHtmlAttributes(htmlAttributes));
}
public static MvcHtmlString HiddenJsonFor<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> expression, IDictionary<string, object> htmlAttributes)
{
var name = ExpressionHelper.GetExpressionText(expression);
var metadata = ModelMetadata.FromLambdaExpression(expression, htmlHelper.ViewData);
var tagBuilder = new TagBuilder("input");
tagBuilder.MergeAttributes(htmlAttributes);
tagBuilder.MergeAttribute("name", name);
tagBuilder.MergeAttribute("type", "hidden");
var json = JsonConvert.SerializeObject(metadata.Model);
tagBuilder.MergeAttribute("value", json);
return MvcHtmlString.Create(tagBuilder.ToString());
}
}
It is not super-sofisticated, but it solves the problem of where to put it (in Controller or in view?) The answer is obviously: neither ;)
Cartesian product of two tables gives all the possible combinations of tuples like the example in mathematics the cross product of two sets . since many a times there are some junk values which occupy unnecessary space in the memory too so here joins comes to rescue which give the combination of only those attribute values which are required and are meaningful.
inner join gives the repeated field in the table twice whereas natural join here solves the problem by just filtering the repeated columns and displaying it only once.else, both works the same. natural join is more efficient since it preserves the memory .Also , redundancies are removed in natural join .
equi join of two tables are such that they display only those tuples which matches the value in other table . for example : let new1 and new2 be two tables . if sql query select * from new1 join new2 on new1.id = new.id (id is the same column in two tables) then start from new2 table and join which matches the id in second table . besides , non equi join do not have equality operator they have <,>,and between operator .
theta join consists of all the comparison operator including equality and others < , > comparison operator. when it uses equality(=) operator it is known as equi join .
The accepted way to rename a table in Laravel 4 is to use the Schema builder. So you would want to do:
Schema::rename('photos', 'images');
From http://laravel.com/docs/4.2/schema#creating-and-dropping-tables
If you really want to write out a raw SQL query yourself, you can always do:
DB::statement('alter table photos rename to images');
Note: Laravel's DB class also supports running raw SQL select
, insert
, update
, and delete
queries, like:
$users = DB::select('select id, name from users');
For more info, see http://laravel.com/docs/4.2/database#running-queries.
A great way of handling this is with regular expressions.
string modifiedString = Regex.Replace(originalString, @"(\r\n)|\n|\r", "<br/>");
This will replace any of the 3 legal types of newline with the html tag.
if you want to change only the colour of the flag on hover
use this:
.fa-flag:hover {_x000D_
color: red;_x000D_
}
_x000D_
<link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet"/>_x000D_
_x000D_
<i class="fa fa-flag fa-3x"></i>
_x000D_
You can use the following script to add swap on Amazon Linux.
https://github.com/chetankapoor/swap
Download the script using wget:
wget https://raw.githubusercontent.com/chetankapoor/swap/master/swap.sh -O swap.sh
Then run the script with the following format:
sh swap.sh 2G
For a complete tutorial you can visit:
I like to use functional style, such as:
function href(url,txt) {
return "<a href='" +url+ "'>" +txt+ "</a>"
}
function li(txt) {
return "<li>" +txt+ "</li>"
}
function ul(arr) {
return "<ul>" + arr.map(li).join("") + "</ul>"
}
document.write(
ul(
[
href("http://url1","link1"),
href("http://url2","link2"),
href("http://url3","link3")
]
)
)
This style looks readable and transparent. It leads to the creation of utilities which reduces repetition in code.
This also tends to use intermediate strings automatically.
Try Collections.shuffle(list).If usage of this method is barred for solving the problem, then one can look at the actual implementation.
You can use the blade template engine:
@include('view.name')
'view.name' would live in your main views folder:
// for laravel 4.X
app/views/view/name.blade.php
// for laravel 5.X
resources/views/view/name.blade.php
Another example
@include('hello.world');
would display the following view
// for laravel 4.X
app/views/hello/world.blade.php
// for laravel 5.X
resources/views/hello/world.blade.php
Another example
@include('some.directory.structure.foo');
would display the following view
// for Laravel 4.X
app/views/some/directory/structure/foo.blade.php
// for Laravel 5.X
resources/views/some/directory/structure/foo.blade.php
So basically the dot notation defines the directory hierarchy that your view is in, followed by the view name, relative to app/views
folder for laravel 4.x or your resources/views
folder in laravel 5.x
ADDITIONAL
If you want to pass parameters: @include('view.name', array('paramName' => 'value'))
You can then use the value in your views like so <p>{{$paramName}}</p>
Clearly a Cell cannot contain another cell as it becomes a never-ending recursion.
However a Cell CAN contain a pointer to another cell.
typedef struct Cell {
bool isParent;
struct Cell* child;
} Cell;
var x = $('#container').get(0).outerHTML;
This problem mostly occurs due to the error in setText()
method
Solution is simple put your Integer
value by converting into string
type
as
textview.setText(Integer.toString(integer_value));
I had to handle this a while back. I removed the Tab from the TabPages collection (I think that's it) and added it back in when the conditions changed. But that was only in Winforms where I could keep the tab around until I needed it again.
Determine if any string is a date
function checkIsAValidDate($myDateString){
return (bool)strtotime($myDateString);
}
foreach (DataTable table in ds.Tables)
{
foreach (DataRow dr in table.Rows)
{
var ParentId=dr["ParentId"].ToString();
}
}
Building on alko's answer that almost worked for me, except for the filtering step (where I get: ValueError: cannot reindex from a duplicate axis
), here is the final solution I used:
# join the dataframes
united_data = pd.concat([data1, data2, data3, ...])
# group the data by the whole row to find duplicates
united_data_grouped = united_data.groupby(list(united_data.columns))
# detect the row indices of unique rows
uniq_data_idx = [x[0] for x in united_data_grouped.indices.values() if len(x) == 1]
# extract those unique values
uniq_data = united_data.iloc[uniq_data_idx]
There are many ways to achieve this but the easiest way in Python 3.6+, in my opinion, is this:
print(f"{1:03}")
Here is Very simple answer. :D
<div class="col-lg-2" v-for="pic in pics">
<img :src="`../assets/${pic}.png`" :alt="pic">
</div>
Use following code to perform if-else conditioning in python: Here, I am checking the length of the string. If the length is less than 3 then do nothing, if more then 3 then I check the last 3 characters. If last 3 characters are "ing" then I add "ly" at the end otherwise I add "ing" at the end.
Code-
if (len(s)<=3):
return s
elif s[-3:]=="ing":
return s+"ly"
else: return s + "ing"
Yes, do
NSString *str = [NSString stringWithFormat: @"first part %@ second part", varyingString];
For concatenation you can use stringByAppendingString
NSString *str = @"hello ";
str = [str stringByAppendingString:@"world"]; //str is now "hello world"
For multiple strings
NSString *varyingString1 = @"hello";
NSString *varyingString2 = @"world";
NSString *str = [NSString stringWithFormat: @"%@ %@", varyingString1, varyingString2];
//str is now "hello world"
It appears that without the class constraint:
bool Compare<T> (T x, T y) where T: class
{
return x == y;
}
One should realize that while class
constrained Equals
in the ==
operator inherits from Object.Equals
, while that of a struct overrides ValueType.Equals
.
Note that:
bool Compare<T> (T x, T y) where T: struct
{
return x == y;
}
also gives out the same compiler error.
As yet I do not understand why having a value type equality operator comparison is rejected by the compiler. I do know for a fact though, that this works:
bool Compare<T> (T x, T y)
{
return x.Equals(y);
}
I found AlecRust's solution quite helpful, but I add something to resolve one problem: When you click on a single accordion to expand it and then you click on the button to expand, they will all be opened. But, if you click again on the button to collapse, the single accordion expand before won't be collapse.
I've used imageButton, but you can also apply that logic to buttons.
/*** Expand all ***/
$(".expandAll").click(function (event) {
$('.accordion .ui-accordion-header:not(.ui-state-active)').next().slideDown();
return false;
});
/*** Collapse all ***/
$(".collapseAll").click(function (event) {
$('.accordion').accordion({
collapsible: true,
active: false
});
$('.accordion .ui-accordion-header').next().slideUp();
return false;
});
Also, if you have accordions inside an accordion and you want to expand all only on that second level, you can add a query:
/*** Expand all Second Level ***/
$(".expandAll").click(function (event) {
$('.accordion .ui-accordion-header:not(.ui-state-active)').nextAll(':has(.accordion .ui-accordion-header)').slideDown();
return false;
});
Well actually...
I wouldn't have the Fragment try to finish the Activity. That places too much authority on the Fragment in my opinion. Instead, I would use the guide here: http://developer.android.com/training/basics/fragments/communicating.html
Have the Fragment define an interface which the Activity must implement. Make a call up to the Activity, then let the Activity decide what to do with the information. If the activity wishes to finish itself, then it can.
When I'm in a C mood, I usually use zip and list comprehensions for scanf-like behavior. Like this:
input = '1 3.0 false hello'
(a, b, c, d) = [t(s) for t,s in zip((int,float,strtobool,str),input.split())]
print (a, b, c, d)
Note that for more complex format strings, you do need to use regular expressions:
import re
input = '1:3.0 false,hello'
(a, b, c, d) = [t(s) for t,s in zip((int,float,strtobool,str),re.search('^(\d+):([\d.]+) (\w+),(\w+)$',input).groups())]
print (a, b, c, d)
Note also that you need conversion functions for all types you want to convert. For example, above I used something like:
strtobool = lambda s: {'true': True, 'false': False}[s]
you can use ClearContents. ex,
Range("X").Cells.ClearContents
I've seen both methods been used in seed files.
// Uncomment the below to wipe the table clean before populating
DB::table('table_name')->truncate();
//or
DB::table('table_name')->delete();
Even though you can not use the first one if you want to set foreign keys.
Cannot truncate a table referenced in a foreign key constraint
So it might be a good idea to use the second one.
For others that find themselves here, the css I was looking for was
overflow-wrap: break-word;
Which will only break a word if it needs to (the length of the single word is greater than the width of the p), unlike word-break: break-all
which can break the last word of every line.
router.navigate
is just a convenience method that wraps router.navigateByUrl
, it boils down to:
navigate(commands: any[], extras) {
return router.navigateByUrl(router.createUrlTree(commands, extras), extras);
}
As mentioned in other answers router.navigateByUrl
will only accept absolute URLs:
// This will work
router.navigateByUrl("http://localhost/team/33/user/11")
// This WON'T work even though relativeTo parameter is in the signature
router.navigateByUrl("../22", {relativeTo: route})
All the relative calculations are done by router.createUrlTree
and router.navigate
. Array syntax is used to treat every array element as a URL modifying "command". E.g. ".."
- go up, "path"
- go down, {expand: true}
- add query param, etc.. You can use it like this:
// create /team/33/user/11
router.navigate(['/team', 33, 'user', 11]);
// assuming the current url is `/team/33/user/11` and the route points to `user/11`
// navigate to /team/33/user/11/details
router.navigate(['details'], {relativeTo: route});
// navigate to /team/33/user/22
router.navigate(['../22'], {relativeTo: route});
// navigate to /team/44/user/22
router.navigate(['../../team/44/user/22'], {relativeTo: route});
That {relativeTo: route}
parameter is important as that's what router will use as the root for relative operations.
Get it through your component's constructor:
// In my-awesome.component.ts:
constructor(private route: ActivatedRoute, private router: Router) {}
// Example call
onNavigateClick() {
// Navigates to a parent component
this.router.navigate([..], { relativeTo: this.route })
}
Nicest thing about this directive is that it will retrieve the ActivatedRoute
for you. Under the hood it's using already familiar:
router.navigateByUrl(router.createUrlTree(commands, { relativeTo: route }), { relativeTo: route });
Following variants will produce identical result:
[routerLink]="['../..']"
// if the string parameter is passed it will be wrapped into an array
routerLink="../.."
If you are running on Redhat, do following
Stop Jenkins
$sudo service jenkins stop
change port number in /etc/sysconfig/jenkins
like i did for port 8081
JENKINS_PORT="8081"
start Jenkins again
$sudo service jenkins start
Update:
Short answer - You should almost always be using the utf8mb4
charset and utf8mb4_unicode_ci
collation.
To alter database:
ALTER DATABASE dbname CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
See:
Aaron's comment on this answer How to make MySQL handle UTF-8 properly
What's the difference between utf8_general_ci and utf8_unicode_ci
Conversion guide: https://dev.mysql.com/doc/refman/5.5/en/charset-unicode-conversion.html
Original Answer:
MySQL 4.1 and above has a default character set of UTF-8. You can verify this in your my.cnf
file, remember to set both client and server (default-character-set
and character-set-server
).
If you have existing data that you wish to convert to UTF-8, dump your database, and import it back as UTF-8 making sure:
SET NAMES utf8
before you query/insert into the databaseDEFAULT CHARSET=utf8
when creating new tablesmy.cnf
). remember any languages you use (such as PHP) must be UTF-8 as well. Some versions of PHP will use their own MySQL client library, which may not be UTF-8 aware.If you do want to migrate existing data remember to backup first! Lots of weird choping of data can happen when things don't go as planned!
Some resources:
You can use Git GUI on Windows, see instructions:
http://php.net/manual/en/function.print-r.php This function can be used to format output,
$output = print_r($array,1);
$output
is a string variable, it can be logged like every other string. In pure php you can use trigger_error
Ex. trigger_error($output);
http://php.net/manual/en/function.trigger-error.php
if you need to format it also in html, you can use <pre>
tag
This little template will help you:
template<typename T> class ByRef {
public:
ByRef() {
}
ByRef(const T value) : mValue(value) {
}
operator T&() const {
return((T&)mValue);
}
private:
T mValue;
};
Then you'll be able to:
virtual const ULONG Write(ULONG &State = ByRef<ULONG>(0), bool sequence = true);
The favicon doesn't have to be 16x16 or 32x32. You can create a favicon that is 80x80 or 100x100, just make sure that both values are the same size, and obviously don't make it too large or too small, choose a reasonable size.
In Angular 5 you can easily obtain and modify a copy of the urlTree by parsing the current url. This will include query params and fragments.
let urlTree = this.router.parseUrl(this.router.url);
urlTree.queryParams['newParamKey'] = 'newValue';
this.router.navigateByUrl(urlTree);
The "correct way" to modify a query parameter is probably with the createUrlTree like below which creates a new UrlTree from the current while letting us modify it using NavigationExtras.
import { Router } from '@angular/router';
constructor(private router: Router) { }
appendAQueryParam() {
const urlTree = this.router.createUrlTree([], {
queryParams: { newParamKey: 'newValue' },
queryParamsHandling: "merge",
preserveFragment: true });
this.router.navigateByUrl(urlTree);
}
In order to remove a query parameter this way you can set it to undefined
or null
.
Well, i agree with the @Mishkin Berteig - Agile Coach answer. Using the form is the quick way to use the POST features.
Anyway, i see some mention about javascript, but no code. I have that for my own needs, which includes jquery for easy POST plus others.
Basically, using the driver.execute_script()
you can send any javascript, including Ajax queries.
#/usr/local/env/python
# -*- coding: utf8 -*-
# proxy is used to inspect data involved on the request without so much code.
# using a basic http written in python. u can found it there: http://voorloopnul.com/blog/a-python-proxy-in-less-than-100-lines-of-code/
import selenium
from selenium import webdriver
import requests
from selenium.webdriver.common.proxy import Proxy, ProxyType
jquery = open("jquery.min.js", "r").read()
#print jquery
proxy = Proxy()
proxy.proxy_type = ProxyType.MANUAL
proxy.http_proxy = "127.0.0.1:3128"
proxy.socks_proxy = "127.0.0.1:3128"
proxy.ssl_proxy = "127.0.0.1:3128"
capabilities = webdriver.DesiredCapabilities.PHANTOMJS
proxy.add_to_capabilities(capabilities)
driver = webdriver.PhantomJS(desired_capabilities=capabilities)
driver.get("http://httpbin.org")
driver.execute_script(jquery) # ensure we have jquery
ajax_query = '''
$.post( "post", {
"a" : "%s",
"b" : "%s"
});
''' % (1,2)
ajax_query = ajax_query.replace(" ", "").replace("\n", "")
print ajax_query
result = driver.execute_script("return " + ajax_query)
#print result
#print driver.page_source
driver.close()
# this retuns that from the proxy, and is OK
'''
POST http://httpbin.org/post HTTP/1.1
Accept: */*
Referer: http://httpbin.org/
Origin: http://httpbin.org
X-Requested-With: XMLHttpRequest
User-Agent: Mozilla/5.0 (Windows NT 6.2; WOW64) AppleWebKit/538.1 (KHTML, like Gecko) PhantomJS/2.0.0 Safari/538.1
Content-Type: application/x-www-form-urlencoded; charset=UTF-8
Content-Length: 7
Cookie: _ga=GAxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx; _gat=1
Connection: Keep-Alive
Accept-Encoding: gzip, deflate
Accept-Language: es-ES,en,*
Host: httpbin.org
None
a=1&b=2 <<---- that is OK, is the data contained into the POST
None
'''