static __attribute__ ((noinline)) void foo()
{
}
This is what worked for me.
Anyone can define "token_type" as an OAuth 2.0 extension, but currently "bearer" token type is the most common one.
https://tools.ietf.org/html/rfc6750
Basically that's what Facebook is using. Their implementation is a bit behind from the latest spec though.
If you want to be more secure than Facebook (or as secure as OAuth 1.0 which has "signature"), you can use "mac" token type.
However, it will be hard way since the mac spec is still changing rapidly.
You can revert all your files under your working directory and index by typing following this command
git reset --hard <SHAsum of your commit>
You can also type
git reset --hard HEAD #your current head point
or
git reset --hard HEAD^ #your previous head point
Hope it helps
You may have to replace getActivity() with MainActivity.this for those that are having issues with this.
You have to placed this code in application.rb
config.action_dispatch.default_headers = {
'Access-Control-Allow-Origin' => '*',
'Access-Control-Request-Method' => %w{GET POST OPTIONS}.join(",")
}
I solved same issue by adding polyfill following:
<script src="https://cdn.polyfill.io/v3/polyfill.min.js?features=default,Array.prototype.includes,Array.prototype.find"></script>
A polyfill is a piece of code (usually JavaScript on the Web) used to provide modern functionality on older browsers that do not natively support it.
Hope someone find this helpful.
Here is a macro I use to get the maximum value for signed integers, which is independent of the size of the signed integer type used, and for which gcc -Woverflow won't complain
#define SIGNED_MAX(x) (~(-1 << (sizeof(x) * 8 - 1)))
int a = SIGNED_MAX(a);
long b = SIGNED_MAX(b);
char c = SIGNED_MAX(c); /* if char is signed for this target */
short d = SIGNED_MAX(d);
long long e = SIGNED_MAX(e);
Did you remember to include the closing brace in main?
#include <iostream>
#include "Attack.h"
using namespace std;
int main()
{
Attack attackObj;
attackObj.printShiz();
}
After trying a few things, this worked for me:
go to your virtualenv directory (but don't run workon):
cd ~/.virtualenv/name_of_broken_venv
Now delete these files:
rm -rf .Python bin/python* lib/python2.7/* include/python2.7
Then to rebuild your venv, run:
virtualenv .
workon name_of_broken_venv
pip freeze
You should now see a list of your installed packages again.
You can do it using remote debugging, here is official documentation. Basic process:
*
from dev tools on pc/mac.*
This is now "Remote devices".
I arrived here because I thought I should check in SO if there are adequate answers, after a syntax error that gave me this error, or if I could possibly post an answer myself.
OK, the answers here explain what this error is, so not much more to say, but nevertheless I will give my 2 cents using my words:
This error is caused by the fact that you basically generate a new table with your subquery for the FROM
command.
That's what a derived table
is, and as such, it needs to have an alias
(actually a name reference to it).
So given the following hypothetical query:
SELECT id, key1
FROM (
SELECT t1.ID id, t2.key1 key1, t2.key2 key2, t2.key3 key3
FROM table1 t1
LEFT JOIN table2 t2 ON t1.id = t2.id
WHERE t2.key3 = 'some-value'
) AS tt
So, at the end, the whole subquery inside the FROM
command will produce the table that is aliased as tt
and it will have the following columns id
, key1
, key2
, key3
.
So, then with the initial SELECT
from that table we finally select the id
and key1
from the tt
.
i found out why my first row was default selected and found out how to not select it by default.
By default my datagridview was the object with the first tab-stop on my windows form. Making the tab stop first on another object (maybe disabling tabstop for the datagrid at all will work to) disabled selecting the first row
Your C# action "Save" doesn't execute because your AJAX url is pointing to "/Home/SaveDetailedInfo" and not "/Home/Save".
To call another action from within an action you can maybe try this solution: link
Here's another better solution : link
[HttpPost]
public ActionResult SaveDetailedInfo(Option[] Options)
{
return Json(new { status = "Success", message = "Success" });
}
[HttpPost]
public ActionResult Save()
{
return RedirectToAction("SaveDetailedInfo", Options);
}
AJAX:
Initial ajax call url: "/Home/Save"
on success callback:
make new ajax url: "/Home/SaveDetailedInfo"
I was doing this for a TextView in a ViewHolder for a RecyclerView. I'm not so sure why, but it didn't work for me in the ViewHolder initialization.
public ViewHolder(View itemView) {
super(itemView);
textView = (TextView) itemView.findViewById(R.id.text_view);
textView.setTextColor(context.getResources().getColor(R.color.myColor));
// Other stuff
}
But when I moved it to the onBindViewHolder, it worked fine.
public void onBindViewHolder(ViewHolder holder, int position){
// Other stuff
holder.textView.setTextColor(context.getResources().getColor(R.color.myColor));
}
Hope this helps someone.
Something like that:
var dictionary = {"data":[{"id":"0","name":"ABC"},{"id":"1", "name":"DEF"}], "images": [{"id":"0","name":"PQR"},{"id":"1","name":"xyz"}]};
for (item in dictionary) {
for (subItem in dictionary[item]) {
console.log(dictionary[item][subItem].id);
console.log(dictionary[item][subItem].name);
}
}
If you have direct access to the remote repo, you could always use:
git reset --soft HEAD^
This works since there is no attempt to modify the non-existent working directory. For more details please see the original answer:
How can I uncommit the last commit in a git bare repository?
Use OnClientClick = "return false;"
this works for me
brew cask upgrade chromedriver
var size = 10; var arrayOfArrays = [];
for (var i=0; i<bigarray.length; i+=size) {
arrayOfArrays.push(bigarray.slice(i,i+size));
}
console.log(arrayOfArrays);
Unlike splice()
, slice()
is non-destructive to the original array.
See here: Git doesn't clone all branches on subsequent clones?
If you really want this by pulling branches instead of push --mirror
, you can have a look here:
"fetch --all" in a git bare repository doesn't synchronize local branches to the remote ones
This answer provides detailed steps on how to achieve that relatively easily:
There are many tools that will make this easy. See monjardin's answer for more details about what's involved.
However, doing this isn't necessarily difficult. It sounds like you're using Java, so I would recommend looking into something like GDAL. It provides java wrappers for their routines, and they have all the tools required to convert from Lat/Lon (geographic coordinates) to UTM (projected coordinate system) or some other reasonable map projection.
UTM is nice, because it's meters, so easy to work with. However, you will need to get the appropriate UTM zone for it to do a good job. There are some simple codes available via googling to find an appropriate zone for a lat/long pair.
Except for some internal logging, Close == Dispose.
Dispose calls tcpClient.Client.Shutdown( SocketShutdown.Both ), but its eats any errors. Maybe if you call it directly, you can get some useful exception information.
I was facing with this problem some time ago and I found java.util.LinkedList
is best for my case. It has several methods, with different namings, but they're doing what is needed:
push() -> LinkedList.addLast(); // Or just LinkedList.add();
pop() -> LinkedList.pollLast();
shift() -> LinkedList.pollFirst();
unshift() -> LinkedList.addFirst();
This works:
public enum Direction {
NORTH, SOUTH, EAST, WEST;
public Direction oppose() {
switch(this) {
case NORTH: return SOUTH;
case SOUTH: return NORTH;
case EAST: return WEST;
case WEST: return EAST;
}
throw new RuntimeException("Case not implemented");
}
}
Here is a solution where you set the ylabel of one of the plots and adjust the position of it so it is centered vertically. This way you avoid problems mentioned by KYC.
import numpy as np
import matplotlib.pyplot as plt
def set_shared_ylabel(a, ylabel, labelpad = 0.01):
"""Set a y label shared by multiple axes
Parameters
----------
a: list of axes
ylabel: string
labelpad: float
Sets the padding between ticklabels and axis label"""
f = a[0].get_figure()
f.canvas.draw() #sets f.canvas.renderer needed below
# get the center position for all plots
top = a[0].get_position().y1
bottom = a[-1].get_position().y0
# get the coordinates of the left side of the tick labels
x0 = 1
for at in a:
at.set_ylabel('') # just to make sure we don't and up with multiple labels
bboxes, _ = at.yaxis.get_ticklabel_extents(f.canvas.renderer)
bboxes = bboxes.inverse_transformed(f.transFigure)
xt = bboxes.x0
if xt < x0:
x0 = xt
tick_label_left = x0
# set position of label
a[-1].set_ylabel(ylabel)
a[-1].yaxis.set_label_coords(tick_label_left - labelpad,(bottom + top)/2, transform=f.transFigure)
length = 100
x = np.linspace(0,100, length)
y1 = np.random.random(length) * 1000
y2 = np.random.random(length)
f,a = plt.subplots(2, sharex=True, gridspec_kw={'hspace':0})
a[0].plot(x, y1)
a[1].plot(x, y2)
set_shared_ylabel(a, 'shared y label (a. u.)')
If you merged the branch, then reverted the merge using a pull request and merged that pull request to revert.
The easiest way I felt was to:
git revert -m 1 xxxxxx
(if the revert was merged using a branch) or using git revert xxxxxx
if it was a simple revertSurprised no one mentioned C# 4.0 optional parameters that work like this:
public void SomeMethod(int a, int b = 0)
{
//some code
}
Edit: I know that at the time the question was asked, C# 4.0 didn't exist. But this question still ranks #1 in Google for "C# optional arguments" so I thought - this answer worth being here. Sorry.
Well you are trying to compare Date with Nvarchar which is wrong. Should be
Where dates between date1 And date2
-- both date1 & date2 should be date/datetime
If date1,date2 strings; server will convert them to date type before filtering.
In android I would use this code:
Uri myUI = Uri.parse ("http://example.com/query").buildUpon().appendQueryParameter("q","random word A3500 bank 24").build();
Where Uri
is a android.net.Uri
A convenient way would be boost's string algorithms library.
#include <boost/algorithm/string/classification.hpp> // Include boost::for is_any_of
#include <boost/algorithm/string/split.hpp> // Include for boost::split
// ...
std::vector<std::string> words;
std::string s;
boost::split(words, s, boost::is_any_of(", "), boost::token_compress_on);
inside Firebase Functions transform the timestamp like so:
timestampObj.toDate()
timestampObj.toMillis().toString()
documentation here https://firebase.google.com/docs/reference/js/firebase.firestore.Timestamp
You can use .length
after the selector to see if it matched any elements, like this:
if($("#" + name).length == 0) {
//it doesn't exist
}
The full version:
$("li.friend").live('click', function(){
name = $(this).text();
if($("#" + name).length == 0) {
$("div#chatbar").append("<div class='labels'><div id='" + name + "' style='display:none;'></div>" + name + "</div>");
} else {
alert('this record already exists');
}
});
Or, the non-jQuery version for this part (since it's an ID):
$("li.friend").live('click', function(){
name = $(this).text();
if(document.getElementById(name) == null) {
$("div#chatbar").append("<div class='labels'><div id='" + name + "' style='display:none;'></div>" + name + "</div>");
} else {
alert('this record already exists');
}
});
You can get this one-liner to do what you want using Array.prototype.every, Object.is, and ES6 arrow functions:
const all = arr => arr.every(x => Object.is(arr[0], x));
Completely reset?
Delete the .git
directory locally.
Recreate the git repostory:
$ cd (project-directory)
$ git init
$ (add some files)
$ git add .
$ git commit -m 'Initial commit'
Push to remote server, overwriting. Remember you're going to mess everyone else up doing this … you better be the only client.
$ git remote add origin <url>
$ git push --force --set-upstream origin master
Here is a short example, the C++ way using rdbuf
. I got this from the web. I can't find my original source on this:
#include <fstream>
#include <iostream>
int main ()
{
std::ifstream f1 ("C:\\me.txt",std::fstream::binary);
std::ofstream f2 ("C:\\me2.doc",std::fstream::trunc|std::fstream::binary);
f2<<f1.rdbuf();
return 0;
}
String tmpHtml = "<html>a whole bunch of html stuff</html>";
String htmlTextStr = Html.fromHtml(tmpHtml).toString();
Generic Conversion Macros (TN059 Other Considerations section is important):
A2CW (LPCSTR) -> (LPCWSTR)
A2W (LPCSTR) -> (LPWSTR)
W2CA (LPCWSTR) -> (LPCSTR)
W2A (LPCWSTR) -> (LPSTR)
This is what I came up with using only jQuery. It's just a matter of putting the pieces together.
//Gather date information from local system
var ThisMonth = new Date().getMonth() + 1;
var ThisDay = new Date().getDate();
var ThisYear = new Date().getFullYear();
var ThisDate = ThisMonth.toString() + "/" + ThisDay.toString() + "/" + ThisYear.toString();
//Gather time information from local system
var ThisHour = new Date().getHours();
var ThisMinute = new Date().getMinutes();
var ThisTime = ThisHour.toString() + ":" + ThisMinute.toString();
//Concatenate date and time for date-time stamp
var ThisDateTime = ThisDate + " " + ThisTime;
This is a nasty one... mysterious error and no clear fix.
update/revert/commit did NOT work in my situation. I hadn't done anything weird - just some svn moves.
What DID work for me was:
svn remove offender
svn commit
cd ..
rm -fR parent
svn up parent
cd parent
svn remove offender again
svn commit
copy offender back in (minus .svn dirs)
svn add
svn commit
Weird to say the least. Basically, the svn remove --force offender
wasn't doing completely removing for some reason. Which is sort of what the error message was saying. Only by removing the parent, then updating the parent, did this become obvious because then the offender reappeared! svn removing offender again then properly removed it.
You did not add #
before id of the button. You do not have right selector in your jquery code. So jquery is never execute in your button click. its submitted your form directly not passing any ajax request.
See documentation: http://api.jquery.com/category/selectors/
its your friend.
Try this:
It seems that id: $("#Shareitem").val()
is wrong if you want to pass the value of
<input type="hidden" name="id" value="" id="id">
you need to change this line:
id: $("#Shareitem").val()
by
id: $("#id").val()
All together:
<script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
<script>
$(document).ready(function(){
$("#Shareitem").click(function(e){
e.preventDefault();
$.ajax({type: "POST",
url: "/imball-reagens/public/shareitem",
data: { id: $("#Shareitem").val(), access_token: $("#access_token").val() },
success:function(result){
$("#sharelink").html(result);
}});
});
});
</script>
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
In my case, the warning occurred because of just the regular type of boolean indexing -- because the series had only np.nan. Demonstration (pandas 1.0.3):
>>> import pandas as pd
>>> import numpy as np
>>> pd.Series([np.nan, 'Hi']) == 'Hi'
0 False
1 True
>>> pd.Series([np.nan, np.nan]) == 'Hi'
~/anaconda3/envs/ms3/lib/python3.7/site-packages/pandas/core/ops/array_ops.py:255: FutureWarning: elementwise comparison failed; returning scalar instead, but in the future will perform elementwise comparison
res_values = method(rvalues)
0 False
1 False
I think with pandas 1.0 they really want you to use the new 'string'
datatype which allows for pd.NA
values:
>>> pd.Series([pd.NA, pd.NA]) == 'Hi'
0 False
1 False
>>> pd.Series([np.nan, np.nan], dtype='string') == 'Hi'
0 <NA>
1 <NA>
>>> (pd.Series([np.nan, np.nan], dtype='string') == 'Hi').fillna(False)
0 False
1 False
Don't love at which point they tinkered with every-day functionality such as boolean indexing.
The following is the un-installation for PostgreSQL 9.1 installed using the EnterpriseDB installer. You most probably have to replace folder /9.1/ with your version number. If /Library/Postgresql/
doesn't exist then you probably installed PostgreSQL with a different method like homebrew
or Postgres.app
.
To remove the EnterpriseDB One-Click install of PostgreSQL 9.1:
Run the uninstaller:
sudo /Library/PostgreSQL/9.1/uninstall-postgresql.app/Contents/MacOS/installbuilder.sh
If you installed with the Postgres Installer, you can do:
open /Library/PostgreSQL/9.2/uninstall-postgresql.app
It will ask for the administrator password and run the uninstaller.
Remove the PostgreSQL and data folders. The Wizard will notify you that these were not removed.
sudo rm -rf /Library/PostgreSQL
Remove the ini file:
sudo rm /etc/postgres-reg.ini
Remove the PostgreSQL user using System Preferences -> Users & Groups.
Restore your shared memory settings:
sudo rm /etc/sysctl.conf
That should be all! The uninstall wizard would have removed all icons and start-up applications files so you don't have to worry about those.
From the man page:
-h, --no-filename
Suppress the prefixing of file names on output. This is the default when there
is only one file (or only standard input) to search.
argmax()
will only return the first occurrence for each row.
http://docs.scipy.org/doc/numpy/reference/generated/numpy.argmax.html
If you ever need to do this for a shaped array, this works better than unravel
:
import numpy as np
a = np.array([[1,2,3], [4,3,1]]) # Can be of any shape
indices = np.where(a == a.max())
You can also change your conditions:
indices = np.where(a >= 1.5)
The above gives you results in the form that you asked for. Alternatively, you can convert to a list of x,y coordinates by:
x_y_coords = zip(indices[0], indices[1])
You may try this example:
<form>_x000D_
<h1>Hello! I'm duke! What's you name?</h1>_x000D_
<input type="text" name="user">_x000D_
<br>_x000D_
<br>_x000D_
<input type="submit" value="submit"> _x000D_
<input type="reset">_x000D_
</form>_x000D_
<h1>Hello ${param.user}</h1> _x000D_
<!-- its Expression Language -->
_x000D_
Dictionaries do not have any inherent order. Or, rather, their inherent order is "arbitrary but not random", so it doesn't do you any good.
In different terms, your d
and your e
would be exactly equivalent dictionaries.
What you can do here is to use an OrderedDict
:
from collections import OrderedDict
d = { '123': { 'key1': 3, 'key2': 11, 'key3': 3 },
'124': { 'key1': 6, 'key2': 56, 'key3': 6 },
'125': { 'key1': 7, 'key2': 44, 'key3': 9 },
}
d_ascending = OrderedDict(sorted(d.items(), key=lambda kv: kv[1]['key3']))
d_descending = OrderedDict(sorted(d.items(),
key=lambda kv: kv[1]['key3'], reverse=True))
The original d
has some arbitrary order. d_ascending
has the order you thought you had in your original d
, but didn't. And d_descending
has the order you want for your e
.
If you don't really need to use e
as a dictionary, but you just want to be able to iterate over the elements of d
in a particular order, you can simplify this:
for key, value in sorted(d.items(), key=lambda kv: kv[1]['key3'], reverse=True):
do_something_with(key, value)
If you want to maintain a dictionary in sorted order across any changes, instead of an OrderedDict
, you want some kind of sorted dictionary. There are a number of options available that you can find on PyPI, some implemented on top of trees, others on top of an OrderedDict
that re-sorts itself as necessary, etc.
As @epascarello mentioned for W3C standard browsers, you should use:
body.addEventListener("load", init, false);
However, if you want it to work on IE<9 as well you can use:
var prefix = window.addEventListener ? "" : "on";
var eventName = window.addEventListener ? "addEventListener" : "attachEvent";
document.body[eventName](prefix + "load", init, false);
Or if you want it in a single line:
document.body[window.addEventListener ? 'addEventListener' : 'attachEvent'](
window.addEventListener ? "load" : "onload", init, false);
Note: here I get a straight reference to the body element via the document, saving the need for the first line.
Also, if you're using jQuery, and you want to use the DOM ready
event rather than when the body load
s, the answer can be even shorter...
$(init);
==
checks for reference equality, however when writing code like:
Integer a = 1;
Integer b = 1;
Java is smart enough to reuse the same immutable for a
and b
, so this is true: a == b
. Curious, I wrote a small example to show where java stops optimizing in this way:
public class BoxingLol {
public static void main(String[] args) {
for (int i = 0; i < Integer.MAX_VALUE; i++) {
Integer a = i;
Integer b = i;
if (a != b) {
System.out.println("Done: " + i);
System.exit(0);
}
}
System.out.println("Done, all values equal");
}
}
When I compile and run this (on my machine), I get:
Done: 128
I had a similar issue when attempting to start a process without showing the console window. I tested with several different combinations of property values until I found one that exhibited the behavior I wanted.
Here is a page detailing why the UseShellExecute
property must be set to false.
http://msdn.microsoft.com/en-us/library/system.diagnostics.processstartinfo.createnowindow.aspx
Under Remarks section on page:
If the UseShellExecute property is true or the UserName and Password properties are not null, the CreateNoWindow property value is ignored and a new window is created.
ProcessStartInfo startInfo = new ProcessStartInfo();
startInfo.FileName = fullPath;
startInfo.Arguments = args;
startInfo.RedirectStandardOutput = true;
startInfo.RedirectStandardError = true;
startInfo.UseShellExecute = false;
startInfo.CreateNoWindow = true;
Process processTemp = new Process();
processTemp.StartInfo = startInfo;
processTemp.EnableRaisingEvents = true;
try
{
processTemp.Start();
}
catch (Exception e)
{
throw;
}
here are few differences between Comparator and Comparable I found on web :
If you see then logical difference between these two is Comparator in Java compare two objects provided to him, while Comparable interface compares "this" reference with the object specified.
Comparable in Java is used to implement natural ordering of object. In Java API String, Date and wrapper classes implement Comparable interface.
If any class implement Comparable interface in Java then collection of that object either List or Array can be sorted automatically by using Collections.sort() or Array.sort() method and object will be sorted based on there natural order defined by CompareTo method.
Objects which implement Comparable in Java can be used as keys in a sorted map or elements in a sorted set for example TreeSet, without specifying any Comparator.
site:How to use Comparator and Comparable in Java? With example
Read more: How to use Comparator and Comparable in Java? With example
Alternatively if you want to persist in using the DocumentType
class.
Then you could just add the following annotation on top of your DocumentType class.
@XmlRootElement(name="document")
Note: the String value "document"
refers to the name of the root tag of the xml message.
I suppose you want form based authentication using deployment descriptors and j_security_check
.
You can also do this in JSF by just using the same predefinied field names j_username
and j_password
as demonstrated in the tutorial.
E.g.
<form action="j_security_check" method="post">
<h:outputLabel for="j_username" value="Username" />
<h:inputText id="j_username" />
<br />
<h:outputLabel for="j_password" value="Password" />
<h:inputSecret id="j_password" />
<br />
<h:commandButton value="Login" />
</form>
You could do lazy loading in the User
getter to check if the User
is already logged in and if not, then check if the Principal
is present in the request and if so, then get the User
associated with j_username
.
package com.stackoverflow.q2206911;
import java.io.IOException;
import java.security.Principal;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.context.FacesContext;
@ManagedBean
@SessionScoped
public class Auth {
private User user; // The JPA entity.
@EJB
private UserService userService;
public User getUser() {
if (user == null) {
Principal principal = FacesContext.getCurrentInstance().getExternalContext().getUserPrincipal();
if (principal != null) {
user = userService.find(principal.getName()); // Find User by j_username.
}
}
return user;
}
}
The User
is obviously accessible in JSF EL by #{auth.user}
.
To logout do a HttpServletRequest#logout()
(and set User
to null!). You can get a handle of the HttpServletRequest
in JSF by ExternalContext#getRequest()
. You can also just invalidate the session altogether.
public String logout() {
FacesContext.getCurrentInstance().getExternalContext().invalidateSession();
return "login?faces-redirect=true";
}
For the remnant (defining users, roles and constraints in deployment descriptor and realm), just follow the Java EE 6 tutorial and the servletcontainer documentation the usual way.
Update: you can also use the new Servlet 3.0 HttpServletRequest#login()
to do a programmatic login instead of using j_security_check
which may not per-se be reachable by a dispatcher in some servletcontainers. In this case you can use a fullworthy JSF form and a bean with username
and password
properties and a login
method which look like this:
<h:form>
<h:outputLabel for="username" value="Username" />
<h:inputText id="username" value="#{auth.username}" required="true" />
<h:message for="username" />
<br />
<h:outputLabel for="password" value="Password" />
<h:inputSecret id="password" value="#{auth.password}" required="true" />
<h:message for="password" />
<br />
<h:commandButton value="Login" action="#{auth.login}" />
<h:messages globalOnly="true" />
</h:form>
And this view scoped managed bean which also remembers the initially requested page:
@ManagedBean
@ViewScoped
public class Auth {
private String username;
private String password;
private String originalURL;
@PostConstruct
public void init() {
ExternalContext externalContext = FacesContext.getCurrentInstance().getExternalContext();
originalURL = (String) externalContext.getRequestMap().get(RequestDispatcher.FORWARD_REQUEST_URI);
if (originalURL == null) {
originalURL = externalContext.getRequestContextPath() + "/home.xhtml";
} else {
String originalQuery = (String) externalContext.getRequestMap().get(RequestDispatcher.FORWARD_QUERY_STRING);
if (originalQuery != null) {
originalURL += "?" + originalQuery;
}
}
}
@EJB
private UserService userService;
public void login() throws IOException {
FacesContext context = FacesContext.getCurrentInstance();
ExternalContext externalContext = context.getExternalContext();
HttpServletRequest request = (HttpServletRequest) externalContext.getRequest();
try {
request.login(username, password);
User user = userService.find(username, password);
externalContext.getSessionMap().put("user", user);
externalContext.redirect(originalURL);
} catch (ServletException e) {
// Handle unknown username/password in request.login().
context.addMessage(null, new FacesMessage("Unknown login"));
}
}
public void logout() throws IOException {
ExternalContext externalContext = FacesContext.getCurrentInstance().getExternalContext();
externalContext.invalidateSession();
externalContext.redirect(externalContext.getRequestContextPath() + "/login.xhtml");
}
// Getters/setters for username and password.
}
This way the User
is accessible in JSF EL by #{user}
.
I downloaded and extracted Crypto++ in C:\cryptopp. I used Visual Studio Express 2012 to build all the projects inside (as instructed in readme), and everything was built successfully. Then I made a test project in some other folder and added cryptolib as a dependency.
The conversion was probably not successful. The only thing that was successful was the running of VCUpgrade. The actual conversion itself failed but you don't know until you experience the errors you are seeing. For some of the details, see Visual Studio on the Crypto++ wiki.
Any ideas how to fix this?
To resolve your issues, you should download vs2010.zip
if you want static C/C++ runtime linking (/MT
or /MTd
), or vs2010-dynamic.zip
if you want dynamic C/C++ runtime linking (/MT
or /MTd
). Both fix the latent, silent failures produced by VCUpgrade.
vs2010.zip
, vs2010-dynamic.zip
and vs2005-dynamic.zip
are built from the latest GitHub sources. As of this writing (JUN 1 2016), that's effectively pre-Crypto++ 5.6.4. If you are using the ZIP files with a down level Crypto++, like 5.6.2 or 5.6.3, then you will run into minor problems.
There are two minor problems I am aware. First is a rename of bench.cpp
to bench1.cpp
. Its error is either:
C1083: Cannot open source file: 'bench1.cpp': No such file or directory
LNK2001: unresolved external symbol "void __cdecl OutputResultOperations(char const *,char const *,bool,unsigned long,double)" (?OutputResultOperations@@YAXPBD0_NKN@Z)
The fix is to either (1) open cryptest.vcxproj
in notepad, find bench1.cpp
, and then rename it to bench.cpp
. Or (2) rename bench.cpp
to bench1.cpp
on the filesystem. Please don't delete this file.
The second problem is a little trickier because its a moving target. Down level releases, like 5.6.2 or 5.6.3, are missing the latest classes available in GitHub. The missing class files include HKDF (5.6.3), RDRAND (5.6.3), RDSEED (5.6.3), ChaCha (5.6.4), BLAKE2 (5.6.4), Poly1305 (5.6.4), etc.
The fix is to remove the missing source files from the Visual Studio project files since they don't exist for the down level releases.
Another option is to add the missing class files from the latest sources, but there could be complications. For example, many of the sources subtly depend upon the latest config.h
, cpu.h
and cpu.cpp
. The "subtlety" is you won't realize you are getting an under-performing class.
An example of under-performing class is BLAKE2. config.h
adds compile time ARM-32 and ARM-64 detection. cpu.h
and cpu.cpp
adds runtime ARM instruction detection, which depends upon compile time detection. If you add BLAKE2 without the other files, then none of the detection occurs and you get a straight C/C++ implementation. You probably won't realize you are missing the NEON opportunity, which runs around 9 to 12 cycles-per-byte versus 40 cycles-per-byte or so for vanilla C/C++.
Refer to following links:
You cannot pass more than three arguments, if you want to pass only 1 argument then use void for the other two arguments.
1. private class DownloadFilesTask extends AsyncTask<URL, Integer, Long>
2. protected class InitTask extends AsyncTask<Context, Integer, Integer>
An asynchronous task is defined by a computation that runs on a background thread and whose result is published on the UI thread. An asynchronous task is defined by 3 generic types, called Params, Progress and Result, and 4 steps, called onPreExecute, doInBackground, onProgressUpdate and onPostExecute.
KPBird
I thought i'd expand on the above answer by talking about how you'd fit modules together into an application. I'd read about this in the doug crockford book but being new to javascript it was all still a bit mysterious.
I come from a c# background so have added some terminology I find useful from there.
Html
You'll have some kindof top level html file. It helps to think of this as your project file. Every javascript file you add to the project wants to go into this, unfortunately you dont get tool support for this (I'm using IDEA).
You need add files to the project with script tags like this:
<script type="text/javascript" src="app/native/MasterFile.js" /></script>
<script type="text/javascript" src="app/native/SomeComponent.js" /></script>
It appears collapsing the tags causes things to fail - whilst it looks like xml it's really something with crazier rules!
Namespace file
MasterFile.js
myAppNamespace = {};
that's it. This is just for adding a single global variable for the rest of our code to live in. You could also declare nested namespaces here (or in their own files).
Module(s)
SomeComponent.js
myAppNamespace.messageCounter= (function(){
var privateState = 0;
var incrementCount = function () {
privateState += 1;
};
return function (message) {
incrementCount();
//TODO something with the message!
}
})();
What we're doing here is assigning a message counter function to a variable in our application. It's a function which returns a function which we immediately execute.
Concepts
I think it helps to think of the top line in SomeComponent as being the namespace where you are declaring something. The only caveat to this is all your namespaces need to appear in some other file first - they are just objects rooted by our application variable.
I've only taken minor steps with this at the moment (i'm refactoring some normal javascript out of an extjs app so I can test it) but it seems quite nice as you can define little functional units whilst avoiding the quagmire of 'this'.
You can also use this style to define constructors by returning a function which returns an object with a collection of functions and not calling it immediately.
If you need to mix colour from variable and alpha transparency, and with solutions that include rgba()
function you get an error like
background-color: rgba(#{$color}, 0.3);
^
$color: #002366 is not a color.
?
¦ background-color: rgba(#{$color}, 0.3);
¦ ^^^^^^^^^^^^^^^^^^^^
Something like this might be useful.
$meeting-room-colors: (
Neumann: '#002366',
Turing: '#FF0000',
Lovelace: '#00BFFF',
Shared: '#00FF00',
Chilling: '#FF1493',
);
$color-alpha: EE;
@each $name, $color in $meeting-room-colors {
.#{$name} {
background-color: #{$color}#{$color-alpha};
}
}
If you are willing to use external libraries, You can use _.difference in underscore.js to achieve this. _.difference returns the values from array that are not present in the other arrays.
_.difference([1,2,3,4,5][1,4,10])
==>[2,3,5]
Forget all. Just use:
$date = date("Y-m-d H:i:s",strtotime(str_replace('/','-',$date)))
we can simply use in.next().charAt(0); to assign + - * / operations as characters by initializing operation as a char.
import java.util.*; public class Calculator {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
char operation;
int num1;
int num2;
System.out.println("Enter First Number");
num1 = in.nextInt();
System.out.println("Enter Operation");
operation = in.next().charAt(0);
System.out.println("Enter Second Number");
num2 = in.nextInt();
if (operation == '+')//make sure single quotes
{
System.out.println("your answer is " + (num1 + num2));
}
if (operation == '-')
{
System.out.println("your answer is " + (num1 - num2));
}
if (operation == '/')
{
System.out.println("your answer is " + (num1 / num2));
}
if (operation == '*')
{
System.out.println("your answer is " + (num1 * num2));
}
}
}
After going down a bit of a bit of a rabbit hole trying to follow the answers to this question (maybe because I had to do this in a visual studio project), I found the easier path was to
Cut and paste the file(s) I no longer want to track into a temporary location
Commit the "deletion" of those files
Commit a modification of the .gitignore
to exclude the files I had temporarily moved
Move the files back into the folder.
I found this to be the most straight forward way to go about it (at least in a visual studio, or I would assume other IDE heave based environment like Android Studio), without accidentally shooting myself in the foot with a pretty pervasive git rm -rf --cached .
, after which the visual studio project I was working on didn't load.
Inkscape is a vector drawing program that exports PNG images. So, you end up editing SVG documents and exporting them to PNGs. Inkscape is good if you're starting from scratch, but wouldn't be ideal if you just want to edit existing PNGs.
Note--Inkscape is open source and available for free on multiple platforms.
These are all very sub-optimal solutions. From the GZIP spec
ID2 (IDentification 2)
These have the fixed values ID1 = 31 (0x1f, \037), ID2 = 139 (0x8b, \213), to identify the file as being in gzip format.
Has to be coded into whatever language you're using.
Just add an <img>
tag to your README.md with relative src to your repository. If you're not using relative src, make sure the server supports CORS.
It works because GitHub support inline-html
<img src="/docs/logo.png" alt="My cool logo"/>
# My cool project and above is the logo of it
Observe here
If you do not want to go the previous page i.e. do not let the user go back to the login screen once authorization is done, then you can use;
App.Current.MainPage = new HomePage();
If you want to enable back functionality, just use
Navigation.PushModalAsync(new HomePage())
Quoting the sqlite documentation:
SQLite supports a limited subset of ALTER TABLE. The ALTER TABLE command in SQLite allows the user to rename a table or to add a new column to an existing table. It is not possible to rename a colum, remove a column, or add or remove constraints from a table.
What you can do of course is, create a new table with the new layout, SELECT * FROM old_table
, and fill the new table with the values you'll receive.
The term polymorphism comes from:
poly = many
morphism = the ability to change
In programming, polymorphism is a "technique" that lets you "look" at an object as being more than one type of thing. For instance:
A student object is also a person object. If you "look" (ie cast) at the student, you can probably ask for the student ID. You can't always do that with a person, right? (a person is not necessarily a student, thus might not have a student ID). However, a person probably has a name. A student does too.
Bottom line, "looking" at the same object from different "angles" can give you different "perspectives" (ie different properties or methods)
So this technique lets you build stuff that can be "looked" at from different angles.
Why do we use polymorphism? For starters ... abstraction. At this point it should be enough info :)
a = [1, 2, 3]
p [a, (2...a.size+2).to_a].transpose
There are two ways to write case statements, you seem to be using a combination of the two
case a.updatedDate
when 1760 then 'Entered on' + a.updatedDate
when 1710 then 'Viewed on' + a.updatedDate
else 'Last Updated on' + a.updateDate
end
or
case
when a.updatedDate = 1760 then 'Entered on' + a.updatedDate
when a.updatedDate = 1710 then 'Viewed on' + a.updatedDate
else 'Last Updated on' + a.updateDate
end
are equivalent. They may not work because you may need to convert date types to varchars to append them to other varchars.
If you want to plot a single line connecting all the points in the list
plt.plot(li[:])
plt.show()
This will plot a line connecting all the pairs in the list as points on a Cartesian plane from the starting of the list to the end. I hope that this is what you wanted.
In C, using a previously undeclared function constitutes an implicit declaration of the function. In an implicit declaration, the return type is int
if I recall correctly. Now, GCC has built-in definitions for some standard functions. If an implicit declaration does not match the built-in definition, you get this warning.
To fix the problem, you have to declare the functions before using them; normally you do this by including the appropriate header. I recommend not to use the -fno-builtin-*
flags if possible.
Instead of stdlib.h, you should try:
#include <string.h>
That's where strcpy
and strncpy
are defined, at least according to the strcpy
(2) man page.
The exit
function is defined in stdlib.h, though, so I don't know what's going on there.
Java is a statically typed language, so the compiler does most of this checking for you. Once you declare a variable to be a certain type, the compiler will ensure that it is only ever assigned values of that type (or values that are sub-types of that type).
The examples you gave (int
, array, double
) these are all primitives, and there are no sub-types of them. Thus, if you declare a variable to be an int
:
int x;
You can be sure it will only ever hold int
values.
If you declared a variable to be a List
, however, it is possible that the variable will hold sub-types of List
. Examples of these include ArrayList
, LinkedList
, etc.
If you did have a List
variable, and you needed to know if it was an ArrayList
, you could do the following:
List y;
...
if (y instanceof ArrayList) {
...its and ArrayList...
}
However, if you find yourself thinking you need to do that, you may want to rethink your approach. In most cases, if you follow object-oriented principles, you will not need to do this. There are, of course, exceptions to every rule, though.
I tried casting to a string and testing for a zero-length string and it worked.
CASE
WHEN LEN(CAST(field_value AS VARCHAR(MAX))) = 0 THEN
DO THIS
END AS field
While it may work on some platforms, be aware that platform.architecture
is not always a reliable way to determine whether python is running in 32-bit or 64-bit. In particular, on some OS X multi-architecture builds, the same executable file may be capable of running in either mode, as the example below demonstrates. The quickest safe multi-platform approach is to test sys.maxsize
on Python 2.6, 2.7, Python 3.x.
$ arch -i386 /usr/local/bin/python2.7
Python 2.7.9 (v2.7.9:648dcafa7e5f, Dec 10 2014, 10:10:46)
[GCC 4.2.1 (Apple Inc. build 5666) (dot 3)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import platform, sys
>>> platform.architecture(), sys.maxsize
(('64bit', ''), 2147483647)
>>> ^D
$ arch -x86_64 /usr/local/bin/python2.7
Python 2.7.9 (v2.7.9:648dcafa7e5f, Dec 10 2014, 10:10:46)
[GCC 4.2.1 (Apple Inc. build 5666) (dot 3)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import platform, sys
>>> platform.architecture(), sys.maxsize
(('64bit', ''), 9223372036854775807)
Arrays.sort(numArray);
int middle = ((numArray.length) / 2);
if(numArray.length % 2 == 0){
int medianA = numArray[middle];
int medianB = numArray[middle-1];
median = (medianA + medianB) / 2;
} else{
median = numArray[middle + 1];
}
EDIT: I initially had medianB
setting to middle+1
in the even length arrays, this was wrong due to arrays starting count at 0. I have updated it to use middle-1
which is correct and should work properly for an array with an even length.
It is an attribute on the test method... you don't use Assert. Looks like this:
[ExpectedException(typeof(ExceptionType))]
public void YourMethod_should_throw_exception()
There's no built-in option to make the json module functions return byte strings instead of unicode strings. However, this short and simple recursive function will convert any decoded JSON object from using unicode strings to UTF-8-encoded byte strings:
def byteify(input):
if isinstance(input, dict):
return {byteify(key): byteify(value)
for key, value in input.iteritems()}
elif isinstance(input, list):
return [byteify(element) for element in input]
elif isinstance(input, unicode):
return input.encode('utf-8')
else:
return input
Just call this on the output you get from a json.load
or json.loads
call.
A couple of notes:
return {byteify(key): byteify(value) for key, value in input.iteritems()}
with return dict([(byteify(key), byteify(value)) for key, value in input.iteritems()])
, since dictionary comprehensions weren't supported until Python 2.7.object_hook
or object_pairs_hook
parameters. Mirec Miskuf's answer is so far the only one that manages to pull this off correctly, although as a consequence, it's significantly more complicated than my approach.If no other driver package worked for your obscure device go read how to make a truly universal abd and fastboot driver out of Google's USB driver. The trick is to use CompatibleID
instead of HardwareID
in the driver's INF Models section
You should update the "Microsoft.CodeDom.Providers.DotNetCompilerPlatform" and "Microsoft.Net.Compilers" packages in your project .
From the official documentation:
It is also convenient to have a ~/.pgpass file to avoid regularly having to type in passwords. See Section 30.13 for more information.
...
This file should contain lines of the following format:
hostname:port:database:username:password
The password field from the first line that matches the current connection parameters will be used.
function scrollToBottom() {
$("#mContainer").animate({ scrollTop: $("#mContainer")[0].scrollHeight }, 1000);
}
This is the solution work from me and you find, I'm sure
you could do:
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.image as mpimg
def rgb_to_gray(img):
grayImage = np.zeros(img.shape)
R = np.array(img[:, :, 0])
G = np.array(img[:, :, 1])
B = np.array(img[:, :, 2])
R = (R *.299)
G = (G *.587)
B = (B *.114)
Avg = (R+G+B)
grayImage = img
for i in range(3):
grayImage[:,:,i] = Avg
return grayImage
image = mpimg.imread("your_image.png")
grayImage = rgb_to_gray(image)
plt.imshow(grayImage)
plt.show()
One statement can be written as such:
someValues.forEach(x => console.log(x));
or multiple statements can be enclosed in {}
like this:
someValues.forEach(x => { let a = 2 + x; console.log(a); });
The following signature will do:
List<Email> findByEmailIdInAndPincodeIn(List<String> emails, List<String> pinCodes);
Spring Data JPA supports a large number of keywords to build a query. IN
and AND
are among them.
you can generate curl error after its execution
$url = 'http://example.com';
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$result = curl_exec($ch);
if(curl_errno($ch)){
echo 'Request Error:' . curl_error($ch);
}
and here are curl error code
if someone need more information about curl errors
<?php
$error_codes=array(
[1] => 'CURLE_UNSUPPORTED_PROTOCOL',
[2] => 'CURLE_FAILED_INIT',
[3] => 'CURLE_URL_MALFORMAT',
[4] => 'CURLE_URL_MALFORMAT_USER',
[5] => 'CURLE_COULDNT_RESOLVE_PROXY',
[6] => 'CURLE_COULDNT_RESOLVE_HOST',
[7] => 'CURLE_COULDNT_CONNECT',
[8] => 'CURLE_FTP_WEIRD_SERVER_REPLY',
[9] => 'CURLE_REMOTE_ACCESS_DENIED',
[11] => 'CURLE_FTP_WEIRD_PASS_REPLY',
[13] => 'CURLE_FTP_WEIRD_PASV_REPLY',
[14]=>'CURLE_FTP_WEIRD_227_FORMAT',
[15] => 'CURLE_FTP_CANT_GET_HOST',
[17] => 'CURLE_FTP_COULDNT_SET_TYPE',
[18] => 'CURLE_PARTIAL_FILE',
[19] => 'CURLE_FTP_COULDNT_RETR_FILE',
[21] => 'CURLE_QUOTE_ERROR',
[22] => 'CURLE_HTTP_RETURNED_ERROR',
[23] => 'CURLE_WRITE_ERROR',
[25] => 'CURLE_UPLOAD_FAILED',
[26] => 'CURLE_READ_ERROR',
[27] => 'CURLE_OUT_OF_MEMORY',
[28] => 'CURLE_OPERATION_TIMEDOUT',
[30] => 'CURLE_FTP_PORT_FAILED',
[31] => 'CURLE_FTP_COULDNT_USE_REST',
[33] => 'CURLE_RANGE_ERROR',
[34] => 'CURLE_HTTP_POST_ERROR',
[35] => 'CURLE_SSL_CONNECT_ERROR',
[36] => 'CURLE_BAD_DOWNLOAD_RESUME',
[37] => 'CURLE_FILE_COULDNT_READ_FILE',
[38] => 'CURLE_LDAP_CANNOT_BIND',
[39] => 'CURLE_LDAP_SEARCH_FAILED',
[41] => 'CURLE_FUNCTION_NOT_FOUND',
[42] => 'CURLE_ABORTED_BY_CALLBACK',
[43] => 'CURLE_BAD_FUNCTION_ARGUMENT',
[45] => 'CURLE_INTERFACE_FAILED',
[47] => 'CURLE_TOO_MANY_REDIRECTS',
[48] => 'CURLE_UNKNOWN_TELNET_OPTION',
[49] => 'CURLE_TELNET_OPTION_SYNTAX',
[51] => 'CURLE_PEER_FAILED_VERIFICATION',
[52] => 'CURLE_GOT_NOTHING',
[53] => 'CURLE_SSL_ENGINE_NOTFOUND',
[54] => 'CURLE_SSL_ENGINE_SETFAILED',
[55] => 'CURLE_SEND_ERROR',
[56] => 'CURLE_RECV_ERROR',
[58] => 'CURLE_SSL_CERTPROBLEM',
[59] => 'CURLE_SSL_CIPHER',
[60] => 'CURLE_SSL_CACERT',
[61] => 'CURLE_BAD_CONTENT_ENCODING',
[62] => 'CURLE_LDAP_INVALID_URL',
[63] => 'CURLE_FILESIZE_EXCEEDED',
[64] => 'CURLE_USE_SSL_FAILED',
[65] => 'CURLE_SEND_FAIL_REWIND',
[66] => 'CURLE_SSL_ENGINE_INITFAILED',
[67] => 'CURLE_LOGIN_DENIED',
[68] => 'CURLE_TFTP_NOTFOUND',
[69] => 'CURLE_TFTP_PERM',
[70] => 'CURLE_REMOTE_DISK_FULL',
[71] => 'CURLE_TFTP_ILLEGAL',
[72] => 'CURLE_TFTP_UNKNOWNID',
[73] => 'CURLE_REMOTE_FILE_EXISTS',
[74] => 'CURLE_TFTP_NOSUCHUSER',
[75] => 'CURLE_CONV_FAILED',
[76] => 'CURLE_CONV_REQD',
[77] => 'CURLE_SSL_CACERT_BADFILE',
[78] => 'CURLE_REMOTE_FILE_NOT_FOUND',
[79] => 'CURLE_SSH',
[80] => 'CURLE_SSL_SHUTDOWN_FAILED',
[81] => 'CURLE_AGAIN',
[82] => 'CURLE_SSL_CRL_BADFILE',
[83] => 'CURLE_SSL_ISSUER_ERROR',
[84] => 'CURLE_FTP_PRET_FAILED',
[84] => 'CURLE_FTP_PRET_FAILED',
[85] => 'CURLE_RTSP_CSEQ_ERROR',
[86] => 'CURLE_RTSP_SESSION_ERROR',
[87] => 'CURLE_FTP_BAD_FILE_LIST',
[88] => 'CURLE_CHUNK_FAILED');
?>
i=-62 . If you want to convert it to a unsigned representation. It would be 4294967234 for a 32 bit integer. A simple way would be to
num=-62
unsigned int n;
n = num
cout<<n;
4294967234
You can better use as follows
<a href="url_to_delete" onclick="return confirm('Are you sure you want to delete this item?');">Delete</a>
In your comment on @Kenneth's answer you're saying that ReadAsStringAsync()
is returning empty string.
That's because you (or something - like model binder) already read the content, so position of internal stream in Request.Content is on the end.
What you can do is this:
public static string GetRequestBody()
{
var bodyStream = new StreamReader(HttpContext.Current.Request.InputStream);
bodyStream.BaseStream.Seek(0, SeekOrigin.Begin);
var bodyText = bodyStream.ReadToEnd();
return bodyText;
}
You need:
$ro = preg_replace('/\s+/', ' ',$row['message']);
You are using \s\s+
which means whitespace(space, tab or newline) followed by one or more whitespace. Which effectively means replace two or more whitespace with a single space.
What you want is replace one or more whitespace with single whitespace, so you can use the pattern \s\s*
or \s+
(recommended)
If you just want the milliseconds since 01-JAN-1970, then you can use
var theMoment = moment(); // or whatever your moment instance is
var millis;
millis = +theMoment; // a short but not very readable form
// or
millis = theMoment.valueOf();
// or (almost sure not as efficient as above)
millis = theMoment.toDate().getTime();
Use this code. It worked for me. I considered for 3 columns. Change the loop value for your code.
TableColumn column = null;
for (int i = 0; i < 3; i++) {
column = table.getColumnModel().getColumn(i);
if (i == 0)
column.setMaxWidth(10);
if (i == 2)
column.setMaxWidth(50);
}
Try Like this:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use DB;
class UserController extends Controller
{
function index(){
$users = DB::table('users')->get();
foreach ($users as $user)
{
var_dump($user->name);
}
}
}
?>
Using session
, I successfully passed a parameter (name
) from servlet #1 to servlet #2, using response.sendRedirect
in servlet #1. Servlet #1 code:
protected void doPost(HttpServletRequest request, HttpServletResponse response) {
String name = request.getParameter("name");
String password = request.getParameter("password");
...
request.getSession().setAttribute("name", name);
response.sendRedirect("/todo.do");
In Servlet #2, you don't need to get name
back. It's already connected to the session. You could do String name = (String) request.getSession().getAttribute("name");
---but you don't need this.
If Servlet #2 calls a JSP, you can show name
this way on the JSP webpage:
<h1>Welcome ${name}</h1>
I would like to expand on Martin's answer there...
His solution is rather nice, but it can be tweaked so any "variable type" can be printed like that.(It's actually Value Type, more on the topic). That said, "tweaked" may be a strong word for this. Regardless, it may be helpful.
Martins Solution:
a.getClass().getName()
However, If you want it to work with anything you can do this:
((Object) myVar).getClass().getName()
//OR
((Object) myInt).getClass().getSimpleName()
In this case, the primitive will simply be wrapped in a Wrapper. You will get the Object of the primitive in that case.
I myself used it like this:
private static String nameOf(Object o) {
return o.getClass().getSimpleName();
}
Using Generics:
public static <T> String nameOf(T o) {
return o.getClass().getSimpleName();
}
After reading many articles I decided to put all the attributes information together:
- atomic //default
- nonatomic
- strong=retain //default
- weak= unsafe_unretained
- retain
- assign //default
- unsafe_unretained
- copy
- readonly
- readwrite //default
Below is a link to the detailed article where you can find these attributes.
Many thanks to all the people who give best answers here!!
Here is the Sample Description from Article
Example :
@property (retain) NSString *name;
@synthesize name;
Example:
@property (nonatomic, retain) NSString *name;
@synthesize name;
Explain:
Suppose there is an atomic string property called "name", and if you call [self setName:@"A"] from thread A, call [self setName:@"B"] from thread B, and call [self name] from thread C, then all operation on different thread will be performed serially which means if one thread is executing setter or getter, then other threads will wait. This makes property "name" read/write safe but if another thread D calls [name release] simultaneously then this operation might produce a crash because there is no setter/getter call involved here. Which means an object is read/write safe (ATOMIC) but not thread safe as another threads can simultaneously send any type of messages to the object. Developer should ensure thread safety for such objects.
If the property "name" was nonatomic, then all threads in above example - A,B, C and D will execute simultaneously producing any unpredictable result. In case of atomic, Either one of A, B or C will execute first but D can still execute in parallel.
Example:
@property (strong, nonatomic) ViewController *viewController;
@synthesize viewController;
Example :
@property (weak, nonatomic) IBOutlet UIButton *myButton;
@synthesize myButton;
Strong & Weak Explanation, Thanks to BJ Homer:
Imagine our object is a dog, and that the dog wants to run away (be deallocated). Strong pointers are like a leash on the dog. As long as you have the leash attached to the dog, the dog will not run away. If five people attach their leash to one dog, (five strong pointers to one object), then the dog will not run away until all five leashes are detached. Weak pointers, on the other hand, are like little kids pointing at the dog and saying "Look! A dog!" As long as the dog is still on the leash, the little kids can still see the dog, and they'll still point to it. As soon as all the leashes are detached, though, the dog runs away no matter how many little kids are pointing to it. As soon as the last strong pointer (leash) no longer points to an object, the object will be deallocated, and all weak pointers will be zeroed out. When we use weak? The only time you would want to use weak, is if you wanted to avoid retain cycles (e.g. the parent retains the child and the child retains the parent so neither is ever released).
Example:
@property (nonatomic, retain) NSString *name;
@synthesize name;
Example:
@property (nonatomic, assign) NSString *address;
@synthesize address;
unsafe_unretained
-unsafe_unretained is an ownership qualifier that tells ARC how to insert retain/release calls -unsafe_unretained is the ARC version of assign.
Example:
@property (nonatomic, unsafe_unretained) NSString *nickName;
@synthesize nickName;
Example:
@property (nonatomic, copy) NSArray *myArray;
@synthesize myArray;
You can encode it in PHP :)
<img src="data:image/gif;base64,<?php echo base64_encode(file_get_contents("feed-icon.gif")); ?>">
Or display in our dynamic CSS.php file:
background: url("data:image/gif;base64,<?php echo base64_encode(file_get_contents("feed-icon.gif")); ?>");
1 That’s sort of a “quick-n-dirty” technique but it works. Here is another encoding method using fopen() instead of file_get_contents():
<?php // convert image to dataURL
$img_source = "feed-icon.gif"; // image path/name
$img_binary = fread(fopen($img_source, "r"), filesize($img_source));
$img_string = base64_encode($img_binary);
?>
You can't target each word in CSS. However, with a bit of jQuery you probably could.
With jQuery you can wrap each word in a <span>
and then CSS set span to display:block
which would put it on its own line.
In theory of course :P
you can do something like that:
where regexp_like(name, 'string$', 'i');
You need an scp client. Putty is not one. You can use WinSCP or PSCP. Both are free software.
This is what I use:
Uri baseUri = new Uri(Request.RequestUri.AbsoluteUri.Replace(Request.RequestUri.PathAndQuery, String.Empty));
Then when I combine it with another relative path, I use the following:
string resourceRelative = "~/images/myImage.jpg";
Uri resourceFullPath = new Uri(baseUri, VirtualPathUtility.ToAbsolute(resourceRelative));
Using MySql 8 I got the same error when connecting my code to the DB, using the pip install mysql-connector-python did solve this error.
You've missed the id out before the NOT; it needs to be specified.
SELECT * FROM transactions WHERE id NOT LIKE '1%' AND id NOT LIKE '2%'
SqlCommand.ExecuteNonQuery Method
You can use the ExecuteNonQuery to perform catalog operations (for example, querying the structure of a database or creating database objects such as tables), or to change the data in a database without using a DataSet by executing UPDATE, INSERT, or DELETE statements. Although the ExecuteNonQuery returns no rows, any output parameters or return values mapped to parameters are populated with data. For UPDATE, INSERT, and DELETE statements, the return value is the number of rows affected by the command. When a trigger exists on a table being inserted or updated, the return value includes the number of rows affected by both the insert or update operation and the number of rows affected by the trigger or triggers. For all other types of statements, the return value is -1. If a rollback occurs, the return value is also -1.
SqlCommand.ExecuteScalar Method Executes a Transact-SQL statement against the connection and returns the number of rows affected.
So to get no. of statements returned by SELECT statement you have to use ExecuteScalar method.
So try below code:
SqlConnection conn = new SqlConnection("Data Source=;Initial Catalog=;Persist Security Info=True;User ID=;Password=");
conn.Open();
SqlCommand command = new SqlCommand("Select id from [table1] where name=@zip", conn);
command.Parameters.AddWithValue("@zip","india");
// int result = command.ExecuteNonQuery();
using (SqlDataReader reader = command.ExecuteReader())
{
if (reader.Read())
{
Console.WriteLine(String.Format("{0}",reader["id"]));
}
}
conn.Close();
This Function takes the URL then returns the image BASE64
function getBase64FromImageUrl(url) {
var img = new Image();
img.setAttribute('crossOrigin', 'anonymous');
img.onload = function () {
var canvas = document.createElement("canvas");
canvas.width =this.width;
canvas.height =this.height;
var ctx = canvas.getContext("2d");
ctx.drawImage(this, 0, 0);
var dataURL = canvas.toDataURL("image/png");
alert(dataURL.replace(/^data:image\/(png|jpg);base64,/, ""));
};
img.src = url;
}
Call it like this :
getBase64FromImageUrl("images/slbltxt.png")
Step 1: setAdapter to your listview.
listView.setAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_multiple_choice, GENRES));
Step 2: set choice mode for listview .The second line of below code represents which checkbox should be checked.
listView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
listView.setItemChecked(2, true);
listView.setOnItemClickListener(this);
private static String[] GENRES = new String[] {
"Action", "Adventure", "Animation", "Children", "Comedy", "Documentary", "Drama",
"Foreign", "History", "Independent", "Romance", "Sci-Fi", "Television", "Thriller"
};
Step 3: Checked views are returned in SparseBooleanArray, so you might use the below code to get key or values.The below sample are simply displayed selected names in a single String.
@Override
public void onItemClick(AdapterView<?> adapter, View arg1, int arg2, long arg3)
{
SparseBooleanArray sp=getListView().getCheckedItemPositions();
String str="";
for(int i=0;i<sp.size();i++)
{
str+=GENRES[sp.keyAt(i)]+",";
}
Toast.makeText(this, ""+str, Toast.LENGTH_SHORT).show();
}
json = " { \"success\" : false, \"errors\": { \"text\" : \"??????!\" } }";
return new MemoryStream(Encoding.UTF8.GetBytes(json));
This ought to do the trick: just limit the result to 1 row; if a row comes back the $lectureName
is Assigned, otherwise it's Available.
function checkLectureStatus($lectureName)
{
$con = connectvar();
mysql_select_db("mydatabase", $con);
$result = mysql_query(
"SELECT * FROM preditors_assigned WHERE lecture_name='$lectureName' LIMIT 1");
if(mysql_fetch_array($result) !== false)
return 'Assigned';
return 'Available';
}
Unirest is the best library I've come across for making HTTP requests from Node. It's aiming at being a multiplatform framework, so learning how it works on Node will serve you well if you need to use an HTTP client on Ruby, PHP, Java, Python, Objective C, .Net or Windows 8 as well. As far as I can tell the unirest libraries are mostly backed by existing HTTP clients (e.g. on Java, the Apache HTTP client, on Node, Mikeal's Request libary) - Unirest just puts a nicer API on top.
Here are a couple of code examples for Node.js:
var unirest = require('unirest')
// GET a resource
unirest.get('http://httpbin.org/get')
.query({'foo': 'bar'})
.query({'stack': 'overflow'})
.end(function(res) {
if (res.error) {
console.log('GET error', res.error)
} else {
console.log('GET response', res.body)
}
})
// POST a form with an attached file
unirest.post('http://httpbin.org/post')
.field('foo', 'bar')
.field('stack', 'overflow')
.attach('myfile', 'examples.js')
.end(function(res) {
if (res.error) {
console.log('POST error', res.error)
} else {
console.log('POST response', res.body)
}
})
You can jump straight to the Node docs here
Let's discuss why an "object not found" error can be thrown in R in addition to explaining what it means. What it means (to many) is obvious: the variable in question, at least according to the R interpreter, has not yet been defined, but if you see your object in your code there can be multiple reasons for why this is happening:
check syntax of your declarations. If you mis-typed even one letter or used upper case instead of lower case in a later calling statement, then it won't match your original declaration and this error will occur.
Are you getting this error in a notebook or markdown document? You may simply need to re-run an earlier cell that has your declarations before running the current cell where you are calling the variable.
Are you trying to knit your R document and the variable works find when you run the cells but not when you knit the cells? If so - then you want to examine the snippet I am providing below for a possible side effect that triggers this error:
{r sourceDataProb1, echo=F, eval=F}
# some code here
The above snippet is from the beginning of an R markdown cell. If eval and echo are both set to False this can trigger an error when you try to knit the document. To clarify. I had a use case where I had left these flags as False because I thought i did not want my code echoed or its results to show in the markdown HTML I was generating. But since the variable was then used in later cells, this caused an error during knitting. Simple trial and error with T/F TRUE/FALSE flags can establish if this is the source of your error when it occurs in knitting an R markdown document from RStudio.
Lastly: did you remove the variable or clear it from memory after declaring it?
alignment-baseline
is not the right attribute to use here. The correct answer is to use a combination of dominant-baseline="central"
and text-anchor="middle"
:
<svg width="200" height="100">_x000D_
<g>_x000D_
<rect x="0" y="0" width="200" height="100" style="stroke:red; stroke-width:3px; fill:white;"/>_x000D_
<text x="50%" y="50%" style="dominant-baseline:central; text-anchor:middle; font-size:40px;">TEXT</text>_x000D_
</g>_x000D_
</svg>
_x000D_
On Ubuntu 14.04 I resolved this by using the pip installation bootstrap script, as described in the documentation
wget https://bootstrap.pypa.io/get-pip.py
sudo python get-pip.py
That's an OK solution for a development environment.
i've successfully removed dependencies of a package using this bash line:
for dep in $(pip show somepackage | grep Requires | sed 's/Requires: //g; s/,//g') ; do pip uninstall -y $dep ; done
this worked on pip 1.5.4
If your program is "publicly available non-commercial in nature" and has "a publicly available Web site that meets the basic quality standards", then you can try and get a free license of Excelsior. If its not then it's expensive, but still a viable option.
Program: https://www.excelsiorjet.com
As a side note: Here's a study of all existing Jar to EXE programs, which is a bit depressing - https://www.excelsior-usa.com/articles/java-to-exe.html
this will also work, if you like
xcopy C:\Test\Log "c:\Test\Backup-%date:~4,2%-%date:~7,2%-%date:~10,4%_%time:~0,2%%time:~3,2%" /s /i
del C:\Test\Log
A shorter awk alternative:
awk 1 ORS=' '
An awk program is built up of rules which consist of conditional code-blocks, i.e.:
condition { code-block }
If the code-block is omitted, the default is used: { print $0 }
. Thus, the 1
is interpreted as a true condition and print $0
is executed for each line.
When awk
reads the input it splits it into records based on the value of RS
(Record Separator), which by default is a newline, thus awk
will by default parse the input line-wise. The splitting also involves stripping off RS
from the input record.
Now, when printing a record, ORS
(Output Record Separator) is appended to it, default is again a newline. So by changing ORS
to a space all newlines are changed to spaces.
Use this,
AppCompatActivity activity = (AppCompatActivity) view.getContext();
Fragment myFragment = new MyFragment();
activity.getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container, myFragment).addToBackStack(null).commit();
As a NOT TO DO - Another way would be to use:
divControl.Attributes.Add("style", "height: number");
But don't use this as its messy and the answer by AviewAnew is the correct way.
You can use this as well
import numpy as np
x=np.array(['1.1', '2.2', '3.3'])
x=np.asfarray(x,float)
What is the target platform of your application? I think you should set the platform to x86
, do not set it to Any CPU
.
First you have to go config.inc.php file then change the following instruction
$cfg['Servers'][$i]['user'] ='';
$cfg['Servers'][$i]['password'] ='';
or
By using CHMOD yes:
For Recursive file:
chmod -R 777 foldername or pathname
For non recursive:
chmod 777 foldername or pathname
Adding another use case where I found this happening. I was using a ADF Fusion application and the column type being used was a varchar2(4000) which could not accommodate the text and hence this error.
Try This :
In HTML and JS :
// Convert Password Field To Text On Hover._x000D_
var passField = $('input[type=password]');_x000D_
$('.show-pass').hover(function() {_x000D_
passField.attr('type', 'text');_x000D_
}, function() {_x000D_
passField.attr('type', 'password');_x000D_
})
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
<link href="https://stackpath.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet"/>_x000D_
<!-- An Input PassWord Field With Eye Font-Awesome Class -->_x000D_
<input type="password" placeholder="Type Password">_x000D_
<i class="show-pass fa fa-eye fa-lg"></i>
_x000D_
You were right in thinking mod was a good place to start. Here is an expression which will return true if $number
is even, false if odd:
$number % 2 == 0
Works for every integerPHP value, see as well Arithmetic OperatorsPHP.
Example:
$number = 20;
if ($number % 2 == 0) {
print "It's even";
}
Output:
It's even
How to get append input field value as json like
temp:[
{
test:'test 1',
testData: [
{testName: 'do',testId:''}
],
testRcd:'value'
},
{
test:'test 2',
testData: [
{testName: 'do1',testId:''}
],
testRcd:'value'
}
],
You want to edit this file: "\xampp\phpMyAdmin\config.inc.php"
change this line:
$cfg['Servers'][$i]['password'] = 'WhateverPassword';
to whatever your password is. If you don't remember your password, then run this command within the Shell:
mysqladmin.exe -u root password WhateverPassword
where WhateverPassword is your new password.
Simple use this great free online tool:
Adding to Tim's answer:
#search:placeholder-shown {
// show background image, I like svg
// when using svg, do not use HEX for colour; you can use rbg/a instead
// also notice the single quotes
background-image url('data:image/svg+xml; utf8, <svg>... <g fill="grey"...</svg>')
// other background props
}
#search:not(:placeholder-shown) { background-image: none;}
Thunks versus Sagas
Redux-Thunk
and Redux-Saga
differ in a few important ways, both are middleware libraries for Redux (Redux middleware is code that intercepts actions coming into the store via the dispatch() method).
An action can be literally anything, but if you're following best practices, an action is a plain javascript object with a type field, and optional payload, meta, and error fields. e.g.
const loginRequest = {
type: 'LOGIN_REQUEST',
payload: {
name: 'admin',
password: '123',
}, };
Redux-Thunk
In addition to dispatching standard actions, Redux-Thunk
middleware allows you to dispatch special functions, called thunks
.
Thunks (in Redux) generally have the following structure:
export const thunkName =
parameters =>
(dispatch, getState) => {
// Your application logic goes here
};
That is, a thunk
is a function that (optionally) takes some parameters and returns another function. The inner function takes a dispatch function
and a getState
function -- both of which will be supplied by the Redux-Thunk
middleware.
Redux-Saga
Redux-Saga
middleware allows you to express complex application logic as pure functions called sagas. Pure functions are desirable from a testing standpoint because they are predictable and repeatable, which makes them relatively easy to test.
Sagas are implemented through special functions called generator functions. These are a new feature of ES6 JavaScript
. Basically, execution jumps in and out of a generator everywhere you see a yield statement. Think of a yield
statement as causing the generator to pause and return the yielded value. Later on, the caller can resume the generator at the statement following the yield
.
A generator function is one defined like this. Notice the asterisk after the function keyword.
function* mySaga() {
// ...
}
Once the login saga is registered with Redux-Saga
. But then the yield
take on the the first line will pause the saga until an action with type 'LOGIN_REQUEST'
is dispatched to the store. Once that happens, execution will continue.
You can use r libraries for 3 D plotting.
Steps are:
First create a data frame using data.frame() command.
Create a 3D plot by using scatterplot3D library.
Or You can also rotate your chart using rgl library by plot3d() command.
Alternately you can use plot3d() command from rcmdr library.
In MATLAB, you can use surf(), mesh() or surfl() command as per your requirement.
[http://in.mathworks.com/help/matlab/examples/creating-3-d-plots.html]
I would be very careful if you are considering adopting this hashbang convention.
Once you hashbang, you can’t go back. This is probably the stickiest issue. Ben’s post put forward the point that when pushState is more widely adopted then we can leave hashbangs behind and return to traditional URLs. Well, fact is, you can’t. Earlier I stated that URLs are forever, they get indexed and archived and generally kept around. To add to that, cool URLs don’t change. We don’t want to disconnect ourselves from all the valuable links to our content. If you’ve implemented hashbang URLs at any point then want to change them without breaking links the only way you can do it is by running some JavaScript on the root document of your domain. Forever. It’s in no way temporary, you are stuck with it.
You really want to use pushState instead of hashbangs, because making your URLs ugly and possibly broken -- forever -- is a colossal and permanent downside to hashbangs.
They have a different human-readable meaning.
However, depending on the query optimizer, they may have the same meaning to the machine.
You should always code to be readable.
That is to say, if this is a built-in relationship, use the explicit join. if you are matching on weakly related data, use the where clause.
First some code, then the explanaition. The official docs describing this are here.
import { trigger, transition, animate, style } from '@angular/animations'
@Component({
...
animations: [
trigger('slideInOut', [
transition(':enter', [
style({transform: 'translateY(-100%)'}),
animate('200ms ease-in', style({transform: 'translateY(0%)'}))
]),
transition(':leave', [
animate('200ms ease-in', style({transform: 'translateY(-100%)'}))
])
])
]
})
In your template:
<div *ngIf="visible" [@slideInOut]>This element will slide up and down when the value of 'visible' changes from true to false and vice versa.</div>
I found the angular way a bit tricky to grasp, but once you understand it, it quite easy and powerful.
The animations part in human language:
->then animate the translateY value until we are at 0%, where the element would naturally be.
When the element is removed, animate the translateY value (currently 0), to -100% (off screen).
The easing function we're using is ease-in, in 200 milliseconds, you can change that to your liking.
Hope this helps!
sed -i 's/[^[:print:]]//' FILENAME
Also, this acts like dos2unix
You could also consider going parallel, especially if you don't care about the sequence and more about getting something done for each item:
SomeIEnumerable<T>.AsParallel().ForAll( Action<T> / Delegate / Lambda )
For example:
var numbers = new[] { 1, 2, 3, 4, 5 };
numbers.AsParallel().ForAll( Console.WriteLine );
HTH.
Using the arrow package:
>>> import arrow
>>> arrow.get(2010, 12, 31).timestamp
1293753600
>>> time.gmtime(1293753600)
time.struct_time(tm_year=2010, tm_mon=12, tm_mday=31,
tm_hour=0, tm_min=0, tm_sec=0,
tm_wday=4, tm_yday=365, tm_isdst=0)
This is my general way:
View namebar = view.findViewById(R.id.namebar);
ViewGroup parent = (ViewGroup) namebar.getParent();
if (parent != null) {
parent.removeView(namebar);
}
Indeed is a matter of taste. There are many flavors for converting such letters.
function replaceAccents($str)
{
$a = array('À', 'Á', 'Â', 'Ã', 'Ä', 'Å', 'Æ', 'Ç', 'È', 'É', 'Ê', 'Ë', 'Ì', 'Í', 'Î', 'Ï', 'Ð', 'Ñ', 'Ò', 'Ó', 'Ô', 'Õ', 'Ö', 'Ø', 'Ù', 'Ú', 'Û', 'Ü', 'Ý', 'ß', 'à', 'á', 'â', 'ã', 'ä', 'å', 'æ', 'ç', 'è', 'é', 'ê', 'ë', 'ì', 'í', 'î', 'ï', 'ñ', 'ò', 'ó', 'ô', 'õ', 'ö', 'ø', 'ù', 'ú', 'û', 'ü', 'ý', 'ÿ', 'A', 'a', 'A', 'a', 'A', 'a', 'C', 'c', 'C', 'c', 'C', 'c', 'C', 'c', 'D', 'd', 'Ð', 'd', 'E', 'e', 'E', 'e', 'E', 'e', 'E', 'e', 'E', 'e', 'G', 'g', 'G', 'g', 'G', 'g', 'G', 'g', 'H', 'h', 'H', 'h', 'I', 'i', 'I', 'i', 'I', 'i', 'I', 'i', 'I', 'i', '?', '?', 'J', 'j', 'K', 'k', 'L', 'l', 'L', 'l', 'L', 'l', '?', '?', 'L', 'l', 'N', 'n', 'N', 'n', 'N', 'n', '?', 'O', 'o', 'O', 'o', 'O', 'o', 'Œ', 'œ', 'R', 'r', 'R', 'r', 'R', 'r', 'S', 's', 'S', 's', 'S', 's', 'Š', 'š', 'T', 't', 'T', 't', 'T', 't', 'U', 'u', 'U', 'u', 'U', 'u', 'U', 'u', 'U', 'u', 'U', 'u', 'W', 'w', 'Y', 'y', 'Ÿ', 'Z', 'z', 'Z', 'z', 'Ž', 'ž', '?', 'ƒ', 'O', 'o', 'U', 'u', 'A', 'a', 'I', 'i', 'O', 'o', 'U', 'u', 'U', 'u', 'U', 'u', 'U', 'u', 'U', 'u', '?', '?', '?', '?', '?', '?');
$b = array('A', 'A', 'A', 'A', 'A', 'A', 'AE', 'C', 'E', 'E', 'E', 'E', 'I', 'I', 'I', 'I', 'D', 'N', 'O', 'O', 'O', 'O', 'O', 'O', 'U', 'U', 'U', 'U', 'Y', 's', 'a', 'a', 'a', 'a', 'a', 'a', 'ae', 'c', 'e', 'e', 'e', 'e', 'i', 'i', 'i', 'i', 'n', 'o', 'o', 'o', 'o', 'o', 'o', 'u', 'u', 'u', 'u', 'y', 'y', 'A', 'a', 'A', 'a', 'A', 'a', 'C', 'c', 'C', 'c', 'C', 'c', 'C', 'c', 'D', 'd', 'D', 'd', 'E', 'e', 'E', 'e', 'E', 'e', 'E', 'e', 'E', 'e', 'G', 'g', 'G', 'g', 'G', 'g', 'G', 'g', 'H', 'h', 'H', 'h', 'I', 'i', 'I', 'i', 'I', 'i', 'I', 'i', 'I', 'i', 'IJ', 'ij', 'J', 'j', 'K', 'k', 'L', 'l', 'L', 'l', 'L', 'l', 'L', 'l', 'l', 'l', 'N', 'n', 'N', 'n', 'N', 'n', 'n', 'O', 'o', 'O', 'o', 'O', 'o', 'OE', 'oe', 'R', 'r', 'R', 'r', 'R', 'r', 'S', 's', 'S', 's', 'S', 's', 'S', 's', 'T', 't', 'T', 't', 'T', 't', 'U', 'u', 'U', 'u', 'U', 'u', 'U', 'u', 'U', 'u', 'U', 'u', 'W', 'w', 'Y', 'y', 'Y', 'Z', 'z', 'Z', 'z', 'Z', 'z', 's', 'f', 'O', 'o', 'U', 'u', 'A', 'a', 'I', 'i', 'O', 'o', 'U', 'u', 'U', 'u', 'U', 'u', 'U', 'u', 'U', 'u', 'A', 'a', 'AE', 'ae', 'O', 'o');
return str_replace($a, $b, $str);
}
IMO, this is personal. I'm not putting any prefixes at all. Anyway, if code is meaned to be public, I think it should better has some prefixes, so it can be more readable.
Often large companies are using it's own so called 'developer rules'.
Btw, the funniest yet smartest i saw was DRY KISS (Dont Repeat Yourself. Keep It Simple, Stupid). :-)
Class.cast()
is rarely ever used in Java code. If it is used then usually with types that are only known at runtime (i.e. via their respective Class
objects and by some type parameter). It is only really useful in code that uses generics (that's also the reason it wasn't introduced earlier).
It is not similar to reinterpret_cast
, because it will not allow you to break the type system at runtime any more than a normal cast does (i.e. you can break generic type parameters, but can't break "real" types).
The evils of the C-style cast operator generally don't apply to Java. The Java code that looks like a C-style cast is most similar to a dynamic_cast<>()
with a reference type in Java (remember: Java has runtime type information).
Generally comparing the C++ casting operators with Java casting is pretty hard since in Java you can only ever cast reference and no conversion ever happens to objects (only primitive values can be converted using this syntax).
apparently it's bound to an int, which is 0x7FFFFFFF (2147483647).
Add width:100px, margin:50%.
Now the left side of the button is set to the center.
Finally add half of the width of the button in our case 50px.
The middle of the button is in the center.
<input type='submit' style='width:100px;margin:0 50%;position:relative;left:-50px;'>
You are looking for str.rsplit()
, with a limit:
print x.rsplit('-', 1)[0]
.rsplit()
searches for the splitting string from the end of input string, and the second argument limits how many times it'll split to just once.
Another option is to use str.rpartition()
, which will only ever split just once:
print x.rpartition('-')[0]
For splitting just once, str.rpartition()
is the faster method as well; if you need to split more than once you can only use str.rsplit()
.
Demo:
>>> x = 'http://test.com/lalala-134'
>>> print x.rsplit('-', 1)[0]
http://test.com/lalala
>>> 'something-with-a-lot-of-dashes'.rsplit('-', 1)[0]
'something-with-a-lot-of'
and the same with str.rpartition()
>>> print x.rpartition('-')[0]
http://test.com/lalala
>>> 'something-with-a-lot-of-dashes'.rpartition('-')[0]
'something-with-a-lot-of'
Your code works for me. Here is my test case:
mysql> CREATE TABLE carmake (country ENUM('Canada', 'United States'));
Query OK, 0 rows affected (0.00 sec)
mysql> SHOW CREATE TABLE carmake;
+---------+-------------------------------------------------------------------------------------------------------------------------+
| Table | Create Table |
+---------+-------------------------------------------------------------------------------------------------------------------------+
| carmake | CREATE TABLE `carmake` (
`country` enum('Canada','United States') default NULL
) ENGINE=MyISAM DEFAULT CHARSET=latin1 |
+---------+-------------------------------------------------------------------------------------------------------------------------+
1 row in set (0.00 sec)
mysql> ALTER TABLE carmake CHANGE country country ENUM('Sweden','Malaysia');
Query OK, 0 rows affected (0.53 sec)
Records: 0 Duplicates: 0 Warnings: 0
mysql> SHOW CREATE TABLE carmake;
+---------+--------------------------------------------------------------------------------------------------------------------+
| Table | Create Table |
+---------+--------------------------------------------------------------------------------------------------------------------+
| carmake | CREATE TABLE `carmake` (
`country` enum('Sweden','Malaysia') default NULL
) ENGINE=MyISAM DEFAULT CHARSET=latin1 |
+---------+--------------------------------------------------------------------------------------------------------------------+
1 row in set (0.00 sec)
What error are you seeing?
FWIW this would also work:
ALTER TABLE carmake MODIFY COLUMN country ENUM('Sweden','Malaysia');
I would actually recommend a country table rather than enum column. You may have hundreds of countries which would make for a rather large and awkward enum.
EDIT: Now that I can see your error message:
ERROR 1265 (01000): Data truncated for column 'country' at row 1.
I suspect you have some values in your country column that do not appear in your ENUM
. What is the output of the following command?
SELECT DISTINCT country FROM carmake;
ANOTHER EDIT: What is the output of the following command?
SHOW VARIABLES LIKE 'sql_mode';
Is it STRICT_TRANS_TABLES
or STRICT_ALL_TABLES
? That could lead to an error, rather than the usual warning MySQL would give you in this situation.
YET ANOTHER EDIT: Ok, I now see that you definitely have values in the table that are not in the new ENUM
. The new ENUM
definition only allows 'Sweden'
and 'Malaysia'
. The table has 'USA'
, 'India'
and several others.
LAST EDIT (MAYBE): I think you're trying to do this:
ALTER TABLE carmake CHANGE country country ENUM('Italy', 'Germany', 'England', 'USA', 'France', 'South Korea', 'Australia', 'Spain', 'Czech Republic', 'Sweden', 'Malaysia') DEFAULT NULL;
sleep 6
will sleep for 6 seconds. For a longer duration, you can also use sleep(6.minutes)
or sleep(6.hours)
.
There is Task
exists, It is unnesscery using BackgroundWorker
, Task
is more simple. for example:
ProgressDialog.cs:
public partial class ProgressDialog : Form
{
public System.Windows.Forms.ProgressBar Progressbar { get { return this.progressBar1; } }
public ProgressDialog()
{
InitializeComponent();
}
public void RunAsync(Action action)
{
Task.Run(action);
}
}
Done! Then you can reuse ProgressDialog anywhere:
var progressDialog = new ProgressDialog();
progressDialog.Progressbar.Value = 0;
progressDialog.Progressbar.Maximum = 100;
progressDialog.RunAsync(() =>
{
for (int i = 0; i < 100; i++)
{
Thread.Sleep(1000)
this.progressDialog.Progressbar.BeginInvoke((MethodInvoker)(() => {
this.progressDialog.Progressbar.Value += 1;
}));
}
});
progressDialog.ShowDialog();
You can get the first of the month, by calculating the last_day of the month before and add one day. It is awkward, but I think it is better than formatting a date as string and use that for calculation.
select
*
from
yourtable t
where
/* Greater or equal to the start of last month */
t.date >= DATE_ADD(LAST_DAY(DATE_SUB(NOW(), INTERVAL 2 MONTH)), INTERVAL 1 DAY) and
/* Smaller or equal than one month ago */
t.date <= DATE_SUB(NOW(), INTERVAL 1 MONTH)
What about a basic
your_string.strip("0")
to remove both trailing and leading zeros ? If you're only interested in removing trailing zeros, use .rstrip
instead (and .lstrip
for only the leading ones).
More info in the doc.
You could use some list comprehension to get the sequences you want like so:
trailing_removed = [s.rstrip("0") for s in listOfNum]
leading_removed = [s.lstrip("0") for s in listOfNum]
both_removed = [s.strip("0") for s in listOfNum]
This is common issue with floating points.
Use toFixed
in combination with parseFloat
.
Here is example in JavaScript:
function roundNumber(number, decimals) {
var newnumber = new Number(number+'').toFixed(parseInt(decimals));
return parseFloat(newnumber);
}
0.1 + 0.2; //=> 0.30000000000000004
roundNumber( 0.1 + 0.2, 12 ); //=> 0.3
1)Goto Server tab 2)Right on server -> general -> click on switch location. 3)Double click on the server -> under server location -> select tomcat installation. 4) restart the server.
In s3cmd, simply run the following command (on a Ubuntu system):
s3cmd ls -r s3://mybucket | wc -l
Use
Ctrl + SHIFT + L which will open a list of all major shortcuts for eclipse.
For single line java code comment and uncomment : Ctrl + / (Forward Slash)
For multiple line java code comment : Ctrl + Shift + / (Forward Slash) and
Multiline uncomment : Ctrl + Shift + \ (Backslash)
For single line xhtml code comment/uncomment : Ctrl + Shift + c
For multiple line xhtml code comment : Ctrl + Shift + / (Forward Slash)
For multiple uncomment : Ctrl + Shift + \ (Backward Slash)
For Mac user it will be: ? instead of Ctrl
jQuery has the following signature for the .on()
method: .on( events [, selector ] [, data ], handler )
Events could be anyone of the ones listed on this reference:
https://developer.mozilla.org/en-US/docs/Web/Events
Though, they are not all supported by every browser.
Mozilla states the following about the input event:
The DOM input event is fired synchronously when the value of an or element is changed. Additionally, it fires on contenteditable editors when its contents are changed.
The easiest thing to do is to just change the permissions back. As @kroger noted git only tracks executable bits. So you probably just need to run chmod -x filename
to fix it (or +x
if that's what's needed.
It's a bit late to respond... but there IS a much simpler way to do this. Just change the delimiter (i.e., the character that separates fields). So, instead of s/foo/bar/
you write s|bar|foo
.
And, here's the easy way to do this:
sed 's|/\*!50017 DEFINER=`snafu`@`localhost`\*/||g'
The resulting output is devoid of that nasty DEFINER clause.
function _modulename_getData($field, $table) {
try {
if (empty($field)) {
throw new Exception("The field is undefined.");
}
// rest of code here...
}
catch (Exception $e) {
/*
Here you can either echo the exception message like:
echo $e->getMessage();
Or you can throw the Exception Object $e like:
throw $e;
*/
}
}
Mac OS X doesn't have apt-get
. There is a package manager called Homebrew that is used instead.
This command would be:
brew install python
Use Homebrew to install packages that you would otherwise use apt-get
for.
The page I linked to has an up-to-date way of installing homebrew, but at present, you can install Homebrew as follows:
Type the following in your Mac OS X terminal:
/usr/bin/ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)"
After that, usage of Homebrew is brew install <package>
.
One of the prerequisites for Homebrew are the XCode command line tools.
A package manager (like apt-get
or brew
) just gives your system an easy and automated way to install packages or libraries. Different systems use different programs. apt
and its derivatives are used on Debian based linux systems. Red Hat-ish Linux systems use rpm
(or at least they did many, many, years ago). yum
is also a package manager for RedHat based systems.
Alpine based systems use apk
.
As of 25 April 2016, homebrew opts the user in to sending analytics by default. This can be opted out of in two ways:
Setting an environment variable:
HOMEBREW_NO_ANALYTICS=1
in whereever you keep your environment variables (typically something like ~/.bash_profile
)source ~/.bash_profile
.Running the following command:
brew analytics off
the analytics status can then be checked with the command:
brew analytics
Some (speed) performance tests summarizing the various options, not that it really matters #microoptimization (using a linqpad extension)
void Main()
{
object objValue = null;
test(objValue);
string strValue = null;
test(strValue);
}
// Define other methods and classes here
void test(string value) {
new Perf<string> {
{ "coallesce", n => (value ?? string.Empty).ToString() },
{ "nullcheck", n => value == null ? string.Empty : value.ToString() },
{ "str.Format", n => string.Format("{0}", value) },
{ "str.Concat", n => string.Concat(value) },
{ "string +", n => "" + value },
{ "Convert", n => Convert.ToString(value) },
}.Vs();
}
void test(object value) {
new Perf<string> {
{ "coallesce", n => (value ?? string.Empty).ToString() },
{ "nullcheck", n => value == null ? string.Empty : value.ToString() },
{ "str.Format", n => string.Format("{0}", value) },
{ "str.Concat", n => string.Concat(value) },
{ "string +", n => "" + value },
{ "Convert", n => Convert.ToString(value) },
}.Vs();
}
Probably important to point out that Convert.ToString(...)
will retain a null string.
I was sending console log data from one tab to another and did not really needed the first console. However the error message did bug me so I right clicked and selected "don't show messages from x website". Maybe this is the easiest fix:)
This may not be ideal, but try using "Application.OnTime" to pause execution of the remaining code until enough time has elapsed to assure that all refresh processes have finished.
What if the last table in your refresh list were a faux table consisting of only a flag to indicate that the refresh is complete? This table would be deleted at the beginning of the procedure, then, using "Application.OnTime," a Sub would run every 15 seconds or so checking to see if the faux table had been populated. If populated, cease the "Application.OnTime" checker and proceed with the rest of your procedure.
A little wonky, but it should work.
It is an extremely overused way to check for the success/failure of a command. Typically, the code snippet you give would be refactored as:
if grep -e ERROR ${LOG_DIR_PATH}/${LOG_NAME} > /dev/null; then
...
fi
(Although you can use 'grep -q' in some instances instead of redirecting to /dev/null, doing so is not portable. Many implementations of grep do not support the -q option, so your script may fail if you use it.)
You need to code your html using absolute path for images. By Absolute path means you have to upload the images in a server and in the src
attribute of images you have to give the direct path like this <img src="http://yourdomain.com/images/example.jpg">
.
Below is the PHP code for your refference :- Its taken from http://www.php.net/manual/en/function.mail.php
<?php
// multiple recipients
$to = '[email protected]' . ', '; // note the comma
$to .= '[email protected]';
// subject
$subject = 'Birthday Reminders for August';
// message
$message = '
<p>Here are the birthdays upcoming in August!</p>
';
// To send HTML mail, the Content-type header must be set
$headers = 'MIME-Version: 1.0' . "\r\n";
$headers .= 'Content-type: text/html; charset=UTF-8' . "\r\n";
// Additional headers
$headers .= 'To: Mary <[email protected]>, Kelly <[email protected]>' . "\r\n";
$headers .= 'From: Birthday Reminder <[email protected]>' . "\r\n";
// Mail it
mail($to, $subject, $message, $headers);
?>
I'm running Laravel 6 with Homestead and also ran into this problem. As suggested here in the other answers you can prefix COMPOSER_MEMORY_LIMIT=-1
to a single command and run the command normally. If you'd like to update your PHP config to always allow unlimited memory follow these steps.
vagrant up
vagrant ssh
php --version # 7.4
php --ini # Shows path to the php.ini file that's loaded
cd /etc/php/7.4/cli # your PHP version. Each PHP version has a folder
sudo vi php.ini
Add memory_limit=-1
to your php.ini file. If you're having trouble using Vim or making edits to the php.ini file check this answer about how to edit the php.ini file with Vim. The file should look something like this:
; Maximum amount of memory a script may consume
; http://php.net/memory-limit
memory_limit = -1
Note that this could eat up infinite amount of memory on your machine. Probably not a good idea for production lol. With Laravel Valet had to follow this article and update the memory value here:
sudo vi /usr/local/etc/php/7.4/conf.d/php-memory-limits.ini
Then restart the server with Valet:
valet restart
This answer was also helpful for changing the config with Laravel Valet on Mac so the changes take effect.
You're setting it to not be able to scale (maximum-scale = initial-scale), so it can't scale up when you rotate to landscape mode. Set maximum-scale=1.6 and it will scale properly to fit landscape mode.
Try setting the parameters' "default value" to use the same query as the "available values". In effect it provides every single "available value" as a "default value" and the "Select All" option is automatically checked.
It seems that you have invalid JSON. In that case, that's totally dependent on the data the server sends you which you have not shown. I would suggest running the response through a JSON validator.
Faced with a similar problem sometime ago, I decided to go for a generalized "switch ... case ... break ... default" type solution together with an arm-style instruction set with conditional execution. A custom interpreter using a nesting stack was used to parse these "programs". This solution completely avoids id's or labels. All my XML language elements or "instructions" support a "condition" attribute which if not present or if it evaluates to true then the element's instruction is executed. If there is an "exit" attribute evaluating to true and the condition is also true, then the following group of elements/instructions at the same nesting level will neither be evaluated nor executed and the execution will continue with the next element/instruction at the parent level. If there is no "exit" or it evaluates to false, then the program will proceed with the next element/instruction. For example you can write this type of program (it will be useful to provide a noop "statement" and a mechanism/instruction to assign values and/or expressions to "variables" will prove very handy):
<ins-1>
<ins-11 condition="expr-a" exit="true">
<ins-111 />
...
</ins11>
<ins-12 condition="expr-b" exit="true" />
<ins-13 condition="expr-c" />
<ins-14>
...
</ins14>
</ins-1>
<ins-2>
...
</ins-2>
If expr-a is true then the execution sequence will be:
ins-1
ins-11
ins-111
ins-2
if expr-a is false and expr-b is true then it will be:
ins-1
ins-12
ins-2
If both expr-a and expr-b are false then we'll have:
ins-1
ins-13 (only if expr-c evaluates to true)
ins-14
ins-2
PS. I used "exit" instead of "break" because I used "break" to implement "breakpoints". Such programs are very hard to debug without some kind of breakpointing/tracing mechanism.
PS2. Because I had similar date-time conditions as your example along with the other types of conditions, I also implemented two special attributes: "from" and "until", that also had to evaluate to true if present, just like "condition", and which used special fast date-time checking logic.
You can use customValidity
$(function(){ var elements = document.getElementsByTagName("input"); for (var i = 0; i < elements.length; i++) { elements[i].oninvalid = function(e) { e.target.setCustomValidity("This can't be left blank!"); }; } });
I think that will work on at least Chrome and FF, I'm not sure about other browsers
is an inline element ..but in css you can change it simply by:- img{display:inline-block;} or img{display:inline-block;} or img{display:inliblock;}
I like @Eduardo's answer and I liked the accepted answer. I like to get back a boolean from something like this, so I wrote it up for you guys.
CREATE FUNCTION dbo.DatabaseExists(@dbname nvarchar(128))
RETURNS bit
AS
BEGIN
declare @result bit = 0
SELECT @result = CAST(
CASE WHEN db_id(@dbname) is not null THEN 1
ELSE 0
END
AS BIT)
return @result
END
GO
Now you can use it like this:
select [dbo].[DatabaseExists]('master') --returns 1
select [dbo].[DatabaseExists]('slave') --returns 0
Here is a function that will flatten an object or array. Use this only if you are sure your keys are unique. If you have keys with the same name they will be overwritten. You will need to place this in a class and replace "Functions" with the name of your class. Enjoy...
function flatten($array, $preserve_keys=1, &$out = array(), $isobject=0) {
# Flatten a multidimensional array to one dimension, optionally preserving keys.
#
# $array - the array to flatten
# $preserve_keys - 0 (default) to not preserve keys, 1 to preserve string keys only, 2 to preserve all keys
# $out - internal use argument for recursion
# $isobject - is internally set in order to remember if we're using an object or array
if(is_array($array) || $isobject==1)
foreach($array as $key => $child)
if(is_array($child))
$out = Functions::flatten($child, $preserve_keys, $out, 1); // replace "Functions" with the name of your class
elseif($preserve_keys + is_string($key) > 1)
$out[$key] = $child;
else
$out[] = $child;
if(is_object($array) || $isobject==2)
if(!is_object($out)){$out = new stdClass();}
foreach($array as $key => $child)
if(is_object($child))
$out = Functions::flatten($child, $preserve_keys, $out, 2); // replace "Functions" with the name of your class
elseif($preserve_keys + is_string($key) > 1)
$out->$key = $child;
else
$out = $child;
return $out;
}
I have 1 WorkBook("SOURCE") that contains around 20 Sheets. I want to copy only 1 particular sheet to another Workbook("TARGET") using Excel VBA. Please note that the "TARGET" Workbook doen't exist yet. It should be created at runtime.
Another Way
Sub Sample()
'~~> Change Sheet1 to the relevant sheet
'~~> This will create a new workbook with the relevant sheet
ThisWorkbook.Sheets("Sheet1").Copy
'~~> Save the new workbook
ActiveWorkbook.SaveAs "C:\Target.xlsx", FileFormat:=51
End Sub
This will automatically create a new workbook called Target.xlsx with the relevant sheet
this is the actual regex only match:
/[-!$%^&*()_+|~=`{}[:;<>?,.@#\]]/g
width: 80vmin; height: 80vmin;
CSS does 80% of the smallest view, height or width
I prefer the following to store any number of variables without having to create a separate class.
final public static Map<String, Map<String, Float>> myMap = new HashMap<String, Map<String, Float>>();
Adding following to ansible config worked while using ansible ad-hoc commands:
[ssh_connection]
# ssh arguments to use
ssh_args = -o StrictHostKeyChecking=no
Ansible Version
ansible 2.1.6.0
config file = /etc/ansible/ansible.cfg
UPDATE: I have taken all of your input and came up with the following solution:
In code behind:
protected void Page_Load(object sender, EventArgs e)
{
Page.ClientScript.RegisterOnSubmitStatement(typeof(Page), "closePage", "window.onunload = CloseWindow();");
}
In aspx page:
function CloseWindow() {
window.close();
}
This can be fixed by changing your URL, example bad:
https://raw.githubusercontent.com/svnpenn/bm/master/yt-dl/yt-dl.js
Content-Type: text/plain; charset=utf-8
Example good:
https://cdn.rawgit.com/svnpenn/bm/master/yt-dl/yt-dl.js
content-type: application/javascript;charset=utf-8
rawgit.com is a caching proxy service for github. You can also go there and interactively derive a corresponding URL for your original raw.githubusercontent.com URL. See its FAQ
If it says the API key is listed as a header, more than likely you need to set it in the headers
option of your http request. Normally something like this :
headers: {'Authorization': '[your API key]'}
Here is an example from another Question
$http({method: 'GET', url: '[the-target-url]', headers: {
'Authorization': '[your-api-key]'}
});
Edit : Just saw you wanted to store the response in a variable. In this case I would probably just use AJAX. Something like this :
$.ajax({
type : "GET",
url : "[the-target-url]",
beforeSend: function(xhr){xhr.setRequestHeader('Authorization', '[your-api-key]');},
success : function(result) {
//set your variable to the result
},
error : function(result) {
//handle the error
}
});
I got this from this question and I'm at work so I can't test it at the moment but looks solid
Edit 2: Pretty sure you should be able to use this line :
headers: {'Authorization': '[your API key]'},
instead of the beforeSend
line in the first edit. This may be simpler for you
The problem is that you are attempting to define the elements in lists to multiple lists (not multiple ints as is defined). You should be defining lists like this.
int[,] list = new int[4,4] {
{1,2,3,4},
{5,6,7,8},
{1,3,2,1},
{5,4,3,2}};
You could also do
int[] list1 = new int[4] { 1, 2, 3, 4};
int[] list2 = new int[4] { 5, 6, 7, 8};
int[] list3 = new int[4] { 1, 3, 2, 1 };
int[] list4 = new int[4] { 5, 4, 3, 2 };
int[,] lists = new int[4,4] {
{list1[0],list1[1],list1[2],list1[3]},
{list2[0],list2[1],list2[2],list2[3]},
etc...};
A primary key defines a unique identifier for every row in a table: when a table has a primary key, you have a guranteed way to select any row from it.
A unique constraint does not necessarily identify every row; it just specifies that if a row has values in its columns, then they must be unique. This is not sufficient to uniquely identify every row, which is what a primary key must do.
Well there are lot of answeres already provided and lot are making sense too.
Some mentioned it is just warning and some giving a temp way to disable warnings. All that will work but add risk when number of transactions in your DB is high.
I came across similar situation today and here is the query I came up with...
declare
begin
execute immediate '
create table "TBL" ("ID" number not null)';
exception when others then
if SQLCODE = -955 then null; else raise; end if;
end;
/
This is simple, if exception come while running query it will be suppressed. and you can use same for SQL
or Oracle
.
filter_input(INPUT_POST, 'var_name')
instead of $_POST['var_name']
filter_input_array(INPUT_POST)
instead of $_POST
If you're using Angular's ng-repeat to populate the table hackel's jquery snippet will not work by placing it in the document load event. You'll need to run the snippet after angular has finished rendering the table.
To trigger an event after ng-repeat has rendered try this directive:
var app = angular.module('myapp', [])
.directive('onFinishRender', function ($timeout) {
return {
restrict: 'A',
link: function (scope, element, attr) {
if (scope.$last === true) {
$timeout(function () {
scope.$emit('ngRepeatFinished');
});
}
}
}
});
Complete example in angular: http://jsfiddle.net/ADukg/6880/
I got the directive from here: Use AngularJS just for routing purposes
a.txt
this is line 1
this is line 2
code:
Python 3.4.0 (default, Mar 20 2014, 22:43:40)
[GCC 4.6.3] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> file = open('a.txt').read()
>>> file
>>> file.split('\n')
['this is line 1', 'this is line 2', '']
I'm on Linux, but I guess you just use \r\n
on Windows and it would also work
$(...)
captures the text sent to stdout by the command contained within. return
does not output to stdout. $?
contains the result code of the last command.
fun1 (){
return 34
}
fun2 (){
fun1
local res=$?
echo $res
}
It follows the convention that static methods should be thread-safe, but actually in v2 that static api is a proxy to an instance method on a default instance: in the case protobuf-net, it internally minimises contention points, and synchronises the internal state when necessary. Basically the library goes out of its way to do things right so that you can have simple code.
Use padding to fake it since vertical-align doesn't work on text inputs.
CSS
.date-input {
width: 145px;
padding-top: 80px;
}?
Use string interpolation decimalVar:0.00
key = cv2.waitKey(1)
This is from the openCV package. It detects a keypress without waiting.
Because you tried to access an element in a collection, using a numeric index that exceeds the collection's boundaries.
The first element in a collection is generally located at index 0
. The last element is at index n-1
, where n
is the Size
of the collection (the number of elements it contains). If you attempt to use a negative number as an index, or a number that is larger than Size-1
, you're going to get an error.
When you declare an array like this:
var array = new int[6]
The first and last elements in the array are
var firstElement = array[0];
var lastElement = array[5];
So when you write:
var element = array[5];
you are retrieving the sixth element in the array, not the fifth one.
Typically, you would loop over an array like this:
for (int index = 0; index < array.Length; index++)
{
Console.WriteLine(array[index]);
}
This works, because the loop starts at zero, and ends at Length-1
because index
is no longer less than Length
.
This, however, will throw an exception:
for (int index = 0; index <= array.Length; index++)
{
Console.WriteLine(array[index]);
}
Notice the <=
there? index
will now be out of range in the last loop iteration, because the loop thinks that Length
is a valid index, but it is not.
Lists work the same way, except that you generally use Count
instead of Length
. They still start at zero, and end at Count - 1
.
for (int index = 0; i < list.Count; index++)
{
Console.WriteLine(list[index]);
}
However, you can also iterate through a list using foreach
, avoiding the whole problem of indexing entirely:
foreach (var element in list)
{
Console.WriteLine(element.ToString());
}
You cannot index an element that hasn't been added to a collection yet.
var list = new List<string>();
list.Add("Zero");
list.Add("One");
list.Add("Two");
Console.WriteLine(list[3]); // Throws exception.
For >= iOS8: (Simplified @EliBud's answer).
#define APP_STORE_ID 1108885113
- (void)rateApp{
static NSString *const iOSAppStoreURLFormat = @"itms-apps://itunes.apple.com/WebObjects/MZStore.woa/wa/viewContentsUserReviews?type=Purple+Software&id=%d";
NSURL *appStoreURL = [NSURL URLWithString:[NSString stringWithFormat:iOSAppStoreURLFormat, APP_STORE_ID]];
if ([[UIApplication sharedApplication] canOpenURL:appStoreURL]) {
[[UIApplication sharedApplication] openURL:appStoreURL];
}
}
To move a file you could also use Jakarta Commons IOs FileUtils.moveFile
On error it throws an IOException
, so when no exception is thrown you know that that the file was moved.
The logical OR '||' automatically short circuits if it meets a true condition once.
false || false || true || false = true, stops at second condition.
On the other hand, the logical AND '&&' automatically short circuits if it meets a false condition once.
false && true && true && true = false, stops at first condition.
create a script including the following; (replace the ant and jdk paths with whatever is correct for your machine)
set PATH=%BASEPATH%
set ANT_HOME=c:\tools\apache-ant-1.9-bin
set JAVA_HOME=c:\tools\jdk7x64
set PATH=%ANT_HOME%\bin;%JAVA_HOME%\bin;%PATH%
run it in shell.
Try Base64 encoding/decoding your binary data. Also look into CDATA sections
React-Router 5.1.0+ Answer (using hooks and React >16.8)
You can use the new useHistory
hook on Functional Components and Programmatically navigate:
import { useHistory } from "react-router-dom";
function HomeButton() {
let history = useHistory();
// use history.push('/some/path') here
};
React-Router 4.0.0+ Answer
In 4.0 and above, use the history as a prop of your component.
class Example extends React.Component {
// use `this.props.history.push('/some/path')` here
};
NOTE: this.props.history does not exist in the case your component was not rendered by <Route>
. You should use <Route path="..." component={YourComponent}/>
to have this.props.history in YourComponent
React-Router 3.0.0+ Answer
In 3.0 and above, use the router as a prop of your component.
class Example extends React.Component {
// use `this.props.router.push('/some/path')` here
};
React-Router 2.4.0+ Answer
In 2.4 and above, use a higher order component to get the router as a prop of your component.
import { withRouter } from 'react-router';
class Example extends React.Component {
// use `this.props.router.push('/some/path')` here
};
// Export the decorated class
var DecoratedExample = withRouter(Example);
// PropTypes
Example.propTypes = {
router: React.PropTypes.shape({
push: React.PropTypes.func.isRequired
}).isRequired
};
React-Router 2.0.0+ Answer
This version is backwards compatible with 1.x so there's no need to an Upgrade Guide. Just going through the examples should be good enough.
That said, if you wish to switch to the new pattern, there's a browserHistory module inside the router that you can access with
import { browserHistory } from 'react-router'
Now you have access to your browser history, so you can do things like push, replace, etc... Like:
browserHistory.push('/some/path')
Further reading: Histories and Navigation
React-Router 1.x.x Answer
I will not go into upgrading details. You can read about that in the Upgrade Guide
The main change about the question here is the change from Navigation mixin to History. Now it's using the browser historyAPI to change route so we will use pushState()
from now on.
Here's an exemple using Mixin:
var Example = React.createClass({
mixins: [ History ],
navigateToHelpPage () {
this.history.pushState(null, `/help`);
}
})
Note that this History
comes from rackt/history project. Not from React-Router itself.
If you don't want to use Mixin for some reason (maybe because of ES6 class), then you can access the history that you get from the router from this.props.history
. It will be only accessible for the components rendered by your Router. So, if you want to use it in any child components it needs to be passed down as an attribute via props
.
You can read more about the new release at their 1.0.x documentation
Here is a help page specifically about navigating outside your component
It recommends grabbing a reference history = createHistory()
and calling replaceState
on that.
React-Router 0.13.x Answer
I got into the same problem and could only find the solution with the Navigation mixin that comes with react-router.
Here's how I did it
import React from 'react';
import {Navigation} from 'react-router';
let Authentication = React.createClass({
mixins: [Navigation],
handleClick(e) {
e.preventDefault();
this.transitionTo('/');
},
render(){
return (<div onClick={this.handleClick}>Click me!</div>);
}
});
I was able to call transitionTo()
without the need to access .context
Or you could try the fancy ES6 class
import React from 'react';
export default class Authentication extends React.Component {
constructor(props) {
super(props);
this.handleClick = this.handleClick.bind(this);
}
handleClick(e) {
e.preventDefault();
this.context.router.transitionTo('/');
}
render(){
return (<div onClick={this.handleClick}>Click me!</div>);
}
}
Authentication.contextTypes = {
router: React.PropTypes.func.isRequired
};
React-Router-Redux
Note: if you're using Redux, there is another project called React-Router-Redux that gives you redux bindings for ReactRouter, using somewhat the same approach that React-Redux does
React-Router-Redux has a few methods available that allow for simple navigating from inside action creators. These can be particularly useful for people that have existing architecture in React Native, and they wish to utilize the same patterns in React Web with minimal boilerplate overhead.
Explore the following methods:
push(location)
replace(location)
go(number)
goBack()
goForward()
Here is an example usage, with Redux-Thunk:
./actioncreators.js
import { goBack } from 'react-router-redux'
export const onBackPress = () => (dispatch) => dispatch(goBack())
./viewcomponent.js
<button
disabled={submitting}
className="cancel_button"
onClick={(e) => {
e.preventDefault()
this.props.onBackPress()
}}
>
CANCEL
</button>
You can design a lowpass Butterworth filter in runtime, using butter()
function, and then apply that to the signal.
fc = 300; % Cut off frequency
fs = 1000; % Sampling rate
[b,a] = butter(6,fc/(fs/2)); % Butterworth filter of order 6
x = filter(b,a,signal); % Will be the filtered signal
Highpass and bandpass filters are also possible with this method. See https://www.mathworks.com/help/signal/ref/butter.html