As other option, you can do something like below
Group Valuation amount
0 BKB Tube 156
1 BKB Tube 143
2 BKB Tube 67
3 BAC Tube 176
4 BAC Tube 39
5 JDK Tube 75
6 JDK Tube 35
7 JDK Tube 155
8 ETH Tube 38
9 ETH Tube 56
Below script, you can use for above data
import pandas as pd
data = pd.read_csv("daata1.csv")
bytreatment = data.groupby('Group')
bytreatment['amount'].sum()
I have prepared a Shell Script to create a Backup of MYSQL database. You can use it so that we have backup of our database(s).
#!/bin/bash
export PATH=/bin:/usr/bin:/usr/local/bin
TODAY=`date +"%d%b%Y_%I:%M:%S%p"`
################################################################
################## Update below values ########################
DB_BACKUP_PATH='/backup/dbbackup'
MYSQL_HOST='localhost'
MYSQL_PORT='3306'
MYSQL_USER='auriga'
MYSQL_PASSWORD='auriga@123'
DATABASE_NAME=( Project_O2 o2)
BACKUP_RETAIN_DAYS=30 ## Number of days to keep local backup copy; Enable script code in end of th script
#################################################################
{ mkdir -p ${DB_BACKUP_PATH}/${TODAY}
echo "
${TODAY}" >> ${DB_BACKUP_PATH}/Backup-Report.txt
} || {
echo "Can not make Directry"
echo "Possibly Path is wrong"
}
{ if ! mysql -u ${MYSQL_USER} -p${MYSQL_PASSWORD} -e 'exit'; then
echo 'Failed! You may have Incorrect PASSWORD/USER ' >> ${DB_BACKUP_PATH}/Backup-Report.txt
exit 1
fi
for DB in "${DATABASE_NAME[@]}"; do
if ! mysql -u ${MYSQL_USER} -p${MYSQL_PASSWORD} -e "use "${DB}; then
echo "Failed! Database ${DB} Not Found on ${TODAY}" >> ${DB_BACKUP_PATH}/Backup-Report.txt
else
# echo "Backup started for database - ${DB}"
# mysqldump -h localhost -P 3306 -u auriga -pauriga@123 Project_O2 # use gzip..
mysqldump -h ${MYSQL_HOST} -P ${MYSQL_PORT} -u ${MYSQL_USER} -p${MYSQL_PASSWORD} \
--databases ${DB} | gzip > ${DB_BACKUP_PATH}/${TODAY}/${DB}-${TODAY}.sql.gz
if [ $? -eq 0 ]; then
touch ${DB_BACKUP_PATH}/Backup-Report.txt
echo "successfully backed-up of ${DB} on ${TODAY}" >> ${DB_BACKUP_PATH}/Backup-Report.txt
# echo "Database backup successfully completed"
else
touch ${DB_BACKUP_PATH}/Backup-Report.txt
echo "Failed to backup of ${DB} on ${TODAY}" >> ${DB_BACKUP_PATH}/Backup-Report.txt
# echo "Error found during backup"
exit 1
fi
fi
done
} || {
echo "Failed during backup"
echo "Failed to backup on ${TODAY}" >> ${DB_BACKUP_PATH}/Backup-Report.txt
# ./myshellsc.sh 2> ${DB_BACKUP_PATH}/Backup-Report.txt
}
##### Remove backups older than {BACKUP_RETAIN_DAYS} days #####
# DBDELDATE=`date +"%d%b%Y" --date="${BACKUP_RETAIN_DAYS} days ago"`
# if [ ! -z ${DB_BACKUP_PATH} ]; then
# cd ${DB_BACKUP_PATH}
# if [ ! -z ${DBDELDATE} ] && [ -d ${DBDELDATE} ]; then
# rm -rf ${DBDELDATE}
# fi
# fi
### End of script ####
In the script we just need to give our Username, Password, Name of Database(or Databases if more than one) also Port number if Different.
To Run the script use Command as:
sudo ./script.sc
I also Suggest that if You want to see the Result in a file Like: Failure Occurs or Successful in backing-up, then Use the Command as Below:
sudo ./myshellsc.sh 2>> Backup-Report.log
Thank You.
To convert array-like to array in efficient way we can make use of the jQuery makeArray
:
makeArray: Convert an array-like object into a true JavaScript array.
Usage:
var domArray = jQuery.makeArray(htmlCollection);
A little extra:
If you do not want to keep reference to the array object (most of the time HTMLCollections are dynamically changes so its better to copy them into another array, This example pay close attention to performance:
var domDataLength = domData.length //Better performance, no need to calculate every iteration the domArray length
var resultArray = new Array(domDataLength) // Since we know the length its improves the performance to declare the result array from the beginning.
for (var i = 0 ; i < domDataLength ; i++) {
resultArray[i] = domArray[i]; //Since we already declared the resultArray we can not make use of the more expensive push method.
}
What is array-like?
HTMLCollection is an "array-like"
object, the array-like objects are similar to array's object but missing a lot of its functionally definition:
Array-like objects look like arrays. They have various numbered elements and a length property. But that’s where the similarity stops. Array-like objects do not have any of Array’s functions, and for-in loops don’t even work!
For anyone coming across this thread, here's a script called thatsNotYoChild.js that I just wrote that solves this problem automatically:
http://www.impressivewebs.com/fixing-parent-child-opacity/
Basically, it separates children from the parent element, but keeps the element in the same physical location on the page.
import numpy as np
def Haversine(lat1,lon1,lat2,lon2, **kwarg):
"""
This uses the ‘haversine’ formula to calculate the great-circle distance between two points – that is,
the shortest distance over the earth’s surface – giving an ‘as-the-crow-flies’ distance between the points
(ignoring any hills they fly over, of course!).
Haversine
formula: a = sin²(?f/2) + cos f1 · cos f2 · sin²(??/2)
c = 2 · atan2( va, v(1-a) )
d = R · c
where f is latitude, ? is longitude, R is earth’s radius (mean radius = 6,371km);
note that angles need to be in radians to pass to trig functions!
"""
R = 6371.0088
lat1,lon1,lat2,lon2 = map(np.radians, [lat1,lon1,lat2,lon2])
dlat = lat2 - lat1
dlon = lon2 - lon1
a = np.sin(dlat/2)**2 + np.cos(lat1) * np.cos(lat2) * np.sin(dlon/2) **2
c = 2 * np.arctan2(a**0.5, (1-a)**0.5)
d = R * c
return round(d,4)
This is an IndexError
in python, which means that we're trying to access an index which isn't there in the tensor. Below is a very simple example to understand this error.
# create an empty array of dimension `0`
In [14]: arr = np.array([], dtype=np.int64)
# check its shape
In [15]: arr.shape
Out[15]: (0,)
with this array arr
in place, if we now try to assign any value to some index, for example to the index 0
as in the case below
In [16]: arr[0] = 23
Then, we will get an IndexError
, as below:
IndexError Traceback (most recent call last) <ipython-input-16-0891244a3c59> in <module> ----> 1 arr[0] = 23 IndexError: index 0 is out of bounds for axis 0 with size 0
The reason is that we are trying to access an index (here at 0th position), which is not there (i.e. it doesn't exist because we have an array of size 0
).
In [19]: arr.size * arr.itemsize
Out[19]: 0
So, in essence, such an array is useless and cannot be used for storing anything. Thus, in your code, you've to follow the traceback and look for the place where you're creating an array/tensor of size 0
and fix that.
It should work, however http://nginx.org/en/docs/http/ngx_http_core_module.html#alias says:
When location matches the last part of the directive’s value: it is better to use the root directive instead:
which would yield:
server {
listen 8080;
server_name www.mysite.com mysite.com;
error_log /home/www-data/logs/nginx_www.error.log;
error_page 404 /404.html;
location /public/doc/ {
autoindex on;
root /home/www-data/mysite;
}
location = /404.html {
root /home/www-data/mysite/static/html;
}
}
in fork(), either child or parent process will execute based on cpu selection.. But in vfork(), surely child will execute first. after child terminated, parent will execute.
I have the solution to this problem enters (Start -> Run -> services.msc) are looking for the postgresql service once you localizas le das Properties---> login and you disable the account you have and what you leave as the local system account , save and restart the programs pgadmin3 and ready should operate.
Greeting from Colombia
Open command prompt and locate your adb.exe(it will be in your android-sdk/platform-tools)
adb logcat -d > <path-where-you-want-to-save-file>/filename.txt
If you omit path, it will save logcat in current working directory
The -d option indicates that you are dumping the current contents and then exiting. Prefer notepad++ to open this file so that you can get everything in a proper readable format.
if you handel this from dataBase try :
<img :src="baseUrl + 'path/path' + obj.key +'.png'">
with Java 8 you can achieve with this way:
public static Verbosity findByAbbr(final String abbr){
return Arrays.stream(values()).filter(value -> value.abbr().equals(abbr)).findFirst().orElse(null);
}
retry-safe.
Is usually the easiest way to understand its meaning in computer science.
Allow the ADB to access the network by opening it on the firewall
If you are using winvista and above, go to Windows Advance Firewall under Administrative tool in Control Panel and enable it from there
I tried the above and adding the registry keys to the LOCALMACHINE was not getting the job done. So in case you are still stuck , try this.
Windows Registry Editor Version 5.00
[HKEY_CURRENT_USER\SOFTWARE\Python]
[HKEY_CURRENT_USER\SOFTWARE\Python\PythonCore]
[HKEY_CURRENT_USER\SOFTWARE\Python\PythonCore\2.7]
[HKEY_CURRENT_USER\SOFTWARE\Python\PythonCore\2.7\Help]
[HKEY_CURRENT_USER\SOFTWARE\Python\PythonCore\2.7\Help\Main Python Documentation] @="C:\Python27\Doc\python272.chm"
[HKEY_CURRENT_USER\SOFTWARE\Python\PythonCore\2.7\InstallPath] @="C:\Python27\"
[HKEY_CURRENT_USER\SOFTWARE\Python\PythonCore\2.7\InstallPath\InstallGroup] @="Python 2.7"
[HKEY_CURRENT_USER\SOFTWARE\Python\PythonCore\2.7\Modules]
[HKEY_CURRENT_USER\SOFTWARE\Python\PythonCore\2.7\PythonPath] @="C:\Python27\Lib;C:\Python27\DLLs;C:\Python27\Lib\lib-tk"
Copy paste the above in notepad and save it as Python27.reg . Now run/merge the file as mentioned in the answers above. (Make sure the paths of Python installation are corrected as per your installation.
It simply does ,what the above answers suggest for a local machine ,to the current user.
Create
trigger `[dbo].[mytrigger]` on `[dbo].[Patients]` after update , insert as
begin
--Sql logic
print 'Hello world'
end
Check this: How to maximize a plt.show() window using Python
The command is different depending on which backend you use. I find that this is the best way to make sure the saved pictures have the same scaling as what I view on my screen.
Since I use Canopy with the QT backend:
pylab.get_current_fig_manager().window.showMaximized()
I then call savefig() as required with an increased DPI per silvado's answer.
x = int(input("Give starting number: "))
y = int(input("Give ending number: "))
P.S. Add function int()
From the paper Deep Dive into Android IPC/Binder Framework atAndroid Builders Summit 2013
link
The intent is understood in some small but effective lines
From this thread a simple answer of android architect Dianne Hackborn states it as a data container
which it actually is.
From android architecture point of view :
Intent is a data container that is used for inter process communication. It is built on top of the Binder
from android architecture point of view.
Easiest method: Alt
+Enter
on
private static final long serialVersionUID = ;
IntelliJ will underline the space after the =
. put your cursor on it and hit alt
+Enter
(Option
+Enter
on Mac). You'll get a popover that says "Randomly Change serialVersionUID Initializer". Just hit enter, and it'll populate that space with a random long.
You could try the following:
import matplotlib.pyplot as plt
import numpy as np
def plot_figures(figures, nrows = 1, ncols=1):
"""Plot a dictionary of figures.
Parameters
----------
figures : <title, figure> dictionary
ncols : number of columns of subplots wanted in the display
nrows : number of rows of subplots wanted in the figure
"""
fig, axeslist = plt.subplots(ncols=ncols, nrows=nrows)
for ind,title in zip(range(len(figures)), figures):
axeslist.ravel()[ind].imshow(figures[title], cmap=plt.jet())
axeslist.ravel()[ind].set_title(title)
axeslist.ravel()[ind].set_axis_off()
plt.tight_layout() # optional
# generation of a dictionary of (title, images)
number_of_im = 20
w=10
h=10
figures = {'im'+str(i): np.random.randint(10, size=(h,w)) for i in range(number_of_im)}
# plot of the images in a figure, with 5 rows and 4 columns
plot_figures(figures, 5, 4)
plt.show()
However, this is basically just copy and paste from here: Multiple figures in a single window for which reason this post should be considered to be a duplicate.
I hope this helps.
gap
property:There is a new gap
CSS property for multi-column, flexbox, and grid layouts that works in some browsers now! (See Can I use link 1; link 2). It is shorthand for row-gap
and column-gap
.
#box {
display: flex;
flex-wrap: wrap;
width: 200px;
background-color: red;
gap: 10px;
}
.item {
background: gray;
width: 50px;
height: 50px;
border: 1px black solid;
}
_x000D_
<div id='box'>
<div class='item'></div>
<div class='item'></div>
<div class='item'></div>
<div class='item'></div>
</div>
_x000D_
As of writing, this works in Firefox, Chrome, and Edge but not Safari.
row-gap
property:The row-gap
CSS property for both flexbox and grid layouts allows you to create a gap between rows. I think Safari doesn't support it yet.
#box {
display: flex;
row-gap: 10px;
}
column-gap
property:The column-gap
CSS property for multi-column, flexbox and grid layouts works allows you to create a gap between columns. I think Safari doesn't support it yet.
#box {
display: flex;
column-gap: 10px;
}
RunOnce is an option and have a few keys that can be used for pointing a command to start on startup (depending if it concerns a user or the whole system):
HKEY_LOCAL_MACHINE\Software\Microsoft\Windows\CurrentVersion\Run
HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Run
HKEY_LOCAL_MACHINE\Software\Microsoft\Windows\CurrentVersion\RunOnce
HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\RunOnce
setting the value:
reg add "HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\RunOnce" /v MyBat /D "!C:\mybat.bat"
With setting and exclamation mark at the beginning and if the script exist with a value different than 0 the registry key wont be deleted and the script will be executed every time on startup
You can use SCHTASKS and a triggering event:
SCHTASKS /Create /SC ONEVENT /MO ONLOGON /TN ON_LOGON /tr "c:\some.bat"
or
SCHTASKS /Create /SC ONEVENT /MO ONSTART/TN ON_START /tr "c:\some.bat"
You also have two startup folders - one for the current user and one global. There you can copy your scripts (or shortcuts) in order to start a file on startup
::the global one
C:\ProgramData\Microsoft\Windows\Start Menu\Programs\StartUp
::for the current user
%USERPROFILE%\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Startup
JQuery uses CSS selectors to select elements, so you just need to use more than one rule by separating them with commas, as so:
a=$('[myc="blue"], [myid="1"], [myid="3"]');
Edit:
Sorry, you wanted blue and 1 or 3. How about:
a=$('[myc="blue"][myid="1"], [myid="3"]');
Putting the two attribute selectors together gives you AND, using a comma gives you OR.
Using javascript I developed a solution. It isn't beautiful but it worked for me:
function drawMultilineText(){
// set context and formatting
var context = document.getElementById("canvas").getContext('2d');
context.font = fontStyleStr;
context.textAlign = "center";
context.textBaseline = "top";
context.fillStyle = "#000000";
// prepare textarea value to be drawn as multiline text.
var textval = document.getElementByID("textarea").value;
var textvalArr = toMultiLine(textval);
var linespacing = 25;
var startX = 0;
var startY = 0;
// draw each line on canvas.
for(var i = 0; i < textvalArr.length; i++){
context.fillText(textvalArr[i], x, y);
y += linespacing;
}
}
// Creates an array where the <br/> tag splits the values.
function toMultiLine(text){
var textArr = new Array();
text = text.replace(/\n\r?/g, '<br/>');
textArr = text.split("<br/>");
return textArr;
}
Hope that helps!
You have a variety of problems. First, why are you using your specific @@FETCH_STATUS values? It should just be @@FETCH_STATUS = 0.
Second, you are not selecting your inner Cursor into anything. And I cannot think of any circumstance where you would select all fields in this way - spell them out!
Here's a sample to go by. Folder has a primary key of "ClientID" that is also a foreign key for Attend. I'm just printing all of the Attend UIDs, broken down by Folder ClientID:
Declare @ClientID int;
Declare @UID int;
DECLARE Cur1 CURSOR FOR
SELECT ClientID From Folder;
OPEN Cur1
FETCH NEXT FROM Cur1 INTO @ClientID;
WHILE @@FETCH_STATUS = 0
BEGIN
PRINT 'Processing ClientID: ' + Cast(@ClientID as Varchar);
DECLARE Cur2 CURSOR FOR
SELECT UID FROM Attend Where ClientID=@ClientID;
OPEN Cur2;
FETCH NEXT FROM Cur2 INTO @UID;
WHILE @@FETCH_STATUS = 0
BEGIN
PRINT 'Found UID: ' + Cast(@UID as Varchar);
FETCH NEXT FROM Cur2 INTO @UID;
END;
CLOSE Cur2;
DEALLOCATE Cur2;
FETCH NEXT FROM Cur1 INTO @ClientID;
END;
PRINT 'DONE';
CLOSE Cur1;
DEALLOCATE Cur1;
Finally, are you SURE you want to be doing something like this in a stored procedure? It is very easy to abuse stored procedures and often reflects problems in characterizing your problem. The sample I gave, for example, could be far more easily accomplished using standard select calls.
I was creating a mp3 player for android, I wanted to update the current time every 500ms so I did it like this
private void update() {
new android.os.Handler().postDelayed(new Runnable() {
@Override
public void run() {
long cur = player.getCurrentPosition();
long dur = player.getDuration();
currentTime = millisecondsToTime(cur);
currentTimeView.setText(currentTime);
if (cur < dur) {
updatePlayer();
}
// update seekbar
seekBar.setProgress( (int) Math.round((float)cur / (float)dur * 100f));
}
}, 500);
}
which calls the same method recursively
None of the above worked for me. I spent too much time clearing other errors that came up. I found this to be the easiest and the best way.
This works for getting JavaFx on Jdk 11, 12 & on OpenJdk12 too!
module thisIsTheNameOfYourProject {
requires javafx.fxml;
requires javafx.controls;
requires javafx.graphics;
opens sample;
}
The entire thing took me only 5mins !!!
I had this issue and found a much simpler solution than using a ByteArrayResource.
Simply do
public void loadInvoices(MultipartFile invoices, String channel) throws IOException {
init();
Resource invoicesResource = invoices.getResource();
LinkedMultiValueMap<String, Object> parts = new LinkedMultiValueMap<>();
parts.add("file", invoicesResource);
HttpHeaders httpHeaders = new HttpHeaders();
httpHeaders.setContentType(MediaType.MULTIPART_FORM_DATA);
httpHeaders.set("channel", channel);
HttpEntity<LinkedMultiValueMap<String, Object>> httpEntity = new HttpEntity<>(parts, httpHeaders);
String url = String.format("%s/rest/inbound/invoices/upload", baseUrl);
restTemplate.postForEntity(url, httpEntity, JobData.class);
}
It works, and no messing around with the file system or byte arrays.
select sum(s) from (select count(Col_name) as s from Tab_name group by Col_name having count(*)>1)c
Use "php -l <filename>" (that's an 'L') from the command line to output the syntax error that could be causing PHP to throw the status 500 error. It'll output something like:
PHP Parse error: syntax error, unexpected '}' in <filename> on line 18
host = socket.gethostname() # Get the local machine name
port = 12397 # Reserve a port for your service
s.bind((host,port)) # Bind to the port
I think this error may related to the DNS resolution.
This sentence host = socket.gethostname()
get the host name, but if the operating system can not resolve the host name to local address, you would get the error.
Linux operating system can modify the /etc/hosts
file, add one line in it. It looks like below( 'hostname' is which socket.gethostname()
got).
127.0.0.1 hostname
Here's a couple of extension methods I've jury-rigged together to convert IQueryables and IEnumerables from one type to another (i.e. DTO). It's mainly used to convert from a larger type (i.e. the type of the row in the database that has unneeded fields) to a smaller one.
The positive sides of this approach are:
<DtoType>
() is all you needLinqHelper.cs:
public static IQueryable<TResult> Transform<TResult>(this IQueryable source)
{
var resultType = typeof(TResult);
var resultProperties = resultType.GetProperties().Where(p => p.CanWrite);
ParameterExpression s = Expression.Parameter(source.ElementType, "s");
var memberBindings =
resultProperties.Select(p =>
Expression.Bind(typeof(TResult).GetMember(p.Name)[0], Expression.Property(s, p.Name))).OfType<MemberBinding>();
Expression memberInit = Expression.MemberInit(
Expression.New(typeof(TResult)),
memberBindings
);
var memberInitLambda = Expression.Lambda(memberInit, s);
var typeArgs = new[]
{
source.ElementType,
memberInit.Type
};
var mc = Expression.Call(typeof(Queryable), "Select", typeArgs, source.Expression, memberInitLambda);
var query = source.Provider.CreateQuery<TResult>(mc);
return query;
}
public static IEnumerable<TResult> Transform<TResult>(this IEnumerable source)
{
return source.AsQueryable().Transform<TResult>();
}
I have put this in my partial view:
@HttpContext.Current.Request.RequestContext.RouteData.Values["controller"].ToString()
in the same kind of situation you describe, and it shows the controller described in the URL (Category for you, Product for me), instead of the actual location of the partial view.
So use this alert instead:
alert('@HttpContext.Current.Request.RequestContext.RouteData.Values["controller"].ToString()');
File -> Project Structure -> Modules (app) -> Open Dependencies Tab -> Remove all then use +
to add from the proposed list.
There is one usage I can see everyone here seems to have forgotten to list...
Rather than doing this:
List("foo", "bar", "baz").map(n => n.toUpperCase())
You could can simply do this:
List("foo", "bar", "baz").map(_.toUpperCase())
When you create an object myObj
as you have, think of it more like a dictionary. In this case, it has two keys, name
, and age
.
You can access these dictionaries in two ways:
myObj[name]
); ormyObj.name
); do note that some properties are reserved, so the first method is preferred.You should be able to access it as a property without any problems. However, to access it as an array, you'll need to treat the key like a string.
myObj["name"]
Otherwise, javascript will assume that name
is a variable, and since you haven't created a variable called name
, it won't be able to access the key you're expecting.
Interestingly virtually all answers revolve around XPath's function contains()
, neglecting the fact it is case sensitive - contrary to the OP's ask.
If you need case insensitivity, that is achievable in XPath 1.0 (the version contemporary browsers support), though it's not pretty - by using the translate()
function. It substitutes a source character to its desired form, by using a translation table.
Constructing a table of all upper case characters will effectively transform the node's text to its lower() form - allowing case-insensitive matching (here's just the prerogative):
[
contains(
translate(text(), 'ABCDEFGHIJKLMNOPQRSTUVWXYZ', 'abcdefghijklmnopqrstuvwxyz'),
'my button'
)
]
# will match a source text like "mY bUTTon"
The full Python call:
driver.find_elements_by_xpath("//*[contains(translate(text(), 'ABCDEFGHIJKLMNOPQRSTUVWXYZ?', 'abcdefghijklmnopqrstuvwxyz?'), 'my button')]")
Naturally this approach has its drawbacks - as given, it'll work only for Latin text; if you want to cover Unicode characters - you'll have to add them to the translation table. I've done that in the sample above - the last character is the Cyrillic symbol "?"
.
And if we lived in a world where browsers supported XPath 2.0 and up (, but not happening any time soon ??), we could having used the functions lower-case()
(yet, not fully locale-aware), and matches
(for regex searches, with the case-insensitive ('i'
) flag).
To disable UIWebView
scrolling you could use the following line of code:
[ObjWebview setUserInteractionEnabled:FALSE];
In this example, ObjWebview
is of type UIWebView
.
Learn from another guy:
<a onclick="window.open(this.href,'_blank');return false;" href="http://www.foracure.org.au">Some Other Site</a>
It makes sense to me.
My preferred approach, which uses data
attributes to hold the state of the number:
<input type='number' step='0.01'/>
// react to stepping in UI
el.addEventListener('onchange', ev => ev.target.dataset.val = ev.target.value * 100)
// react to keys
el.addEventListener('onkeyup', ev => {
// user cleared field
if (!ev.target.value) ev.target.dataset.val = ''
// non num input
if (isNaN(ev.key)) {
// deleting
if (ev.keyCode == 8)
ev.target.dataset.val = ev.target.dataset.val.slice(0, -1)
// num input
} else ev.target.dataset.val += ev.key
ev.target.value = parseFloat(ev.target.dataset.val) / 100
})
If it's the first time for you to save your datatable
Do this (using bulk copy). Assure there are no PK/FK constraint
SqlBulkCopy bulkcopy = new SqlBulkCopy(myConnection);
//I assume you have created the table previously
//Someone else here already showed how
bulkcopy.DestinationTableName = table.TableName;
try
{
bulkcopy.WriteToServer(table);
}
catch(Exception e)
{
messagebox.show(e.message);
}
Now since you already have a basic record. And you just want to check new record with the existing one. You can simply do this.
This will basically take existing table from database
DataTable Table = new DataTable();
SqlConnection Connection = new SqlConnection("ConnectionString");
//I assume you know better what is your connection string
SqlDataAdapter adapter = new SqlDataAdapter("Select * from " + TableName, Connection);
adapter.Fill(Table);
Then pass this table to this function
public DataTable CompareDataTables(DataTable first, DataTable second)
{
first.TableName = "FirstTable";
second.TableName = "SecondTable";
DataTable table = new DataTable("Difference");
try
{
using (DataSet ds = new DataSet())
{
ds.Tables.AddRange(new DataTable[] { first.Copy(), second.Copy() });
DataColumn[] firstcolumns = new DataColumn[ds.Tables[0].Columns.Count];
for (int i = 0; i < firstcolumns.Length; i++)
{
firstcolumns[i] = ds.Tables[0].Columns[i];
}
DataColumn[] secondcolumns = new DataColumn[ds.Table[1].Columns.Count];
for (int i = 0; i < secondcolumns.Length; i++)
{
secondcolumns[i] = ds.Tables[1].Columns[i];
}
DataRelation r = new DataRelation(string.Empty, firstcolumns, secondcolumns, false);
ds.Relations.Add(r);
for (int i = 0; i < first.Columns.Count; i++)
{
table.Columns.Add(first.Columns[i].ColumnName, first.Columns[i].DataType);
}
table.BeginLoadData();
foreach (DataRow parentrow in ds.Tables[0].Rows)
{
DataRow[] childrows = parentrow.GetChildRows(r);
if (childrows == null || childrows.Length == 0)
table.LoadDataRow(parentrow.ItemArray, true);
}
table.EndLoadData();
}
}
catch (Exception ex)
{
throw ex;
}
return table;
}
This will return a new DataTable with the changed rows updated. Please ensure you call the function correctly. The DataTable first is supposed to be the latest.
Then repeat the bulkcopy function all over again with this fresh datatable.
A much neater solution -
$(document).on('keydown', function (e) {
var key = e == null ? event.keyCode : e.keyCode;
if(key == 8 && $(document.activeElement.is(':not(:input)'))) //select, textarea
e.preventDefault();
});
Alternately, you could only check if
$(document.activeElement).is('body')
Try this with your user & pass
keytool -list -v -keystore {path of jks file} -alias {keyname} -storepass {keypassword} -keypass {aliaspassword}
Exe
keytool -list -v -keystore "E:\AndroidStudioProject\ParathaApp\key.jks" -alias key0 -storepass mks@1 -keypass golu@1
Hmm... I think you can use e.clipboardData
to catch the data being pasted. If it doesn't pan out, have a look here.
$(this).live("paste", function(e) {
alert(e.clipboardData); // [object Clipboard]
});
I'm not entirely sure but I think you are probably surprised at how arrays are serialized in JSON. Let's isolate the problem. Consider following code:
var display = Array();
display[0] = "none";
display[1] = "block";
display[2] = "none";
console.log( JSON.stringify(display) );
This will print:
["none","block","none"]
This is how JSON actually serializes array. However what you want to see is something like:
{"0":"none","1":"block","2":"none"}
To get this format you want to serialize object, not array. So let's rewrite above code like this:
var display2 = {};
display2["0"] = "none";
display2["1"] = "block";
display2["2"] = "none";
console.log( JSON.stringify(display2) );
This will print in the format you want.
You can play around with this here: http://jsbin.com/oDuhINAG/1/edit?js,console
I am reading a text file and want to use regex below to pull out numbers with exactly 5 digit, ignoring alphabets.
Try this...
var str = 'f 34 545 323 12345 54321 123456',
matches = str.match(/\b\d{5}\b/g);
console.log(matches); // ["12345", "54321"]
The word boundary \b
is your friend here.
My regex will get a number like this 12345
, but not like a12345
. The other answers provide great regexes if you require the latter.
Consider breaking this problem up into two pieces:
filter
out the items that match
the given regular expression0
matches in itconst sampleStringData = ["frog", "pig", "tiger"];
const matches = sampleStringData.filter((animal) => /any.regex.here/.test(animal));
if (matches.length === 0) {
console.log("No matches");
}
Yes, if bar is not None
is more explicit, and thus better, assuming it is indeed what you want. That's not always the case, there are subtle differences: if not bar:
will execute if bar
is any kind of zero or empty container, or False
.
Many people do use not bar
where they really do mean bar is not None
.
synchronized should only be used when you want your class to be Thread safe. In fact most of the classes should not use synchronized anyways. synchronized method would only provide a lock on this object and only for the duration of its execution. if you really wanna to make your classes thread safe, you should consider making your variables volatile or synchronize the access.
one of the issues of using synchronized method is that all of the members of the class would use the same lock which will make your program slower. In your case synchronized method and block would execute no different. what I'd would recommend is to use a dedicated lock and use a synchronized block something like this.
public class AClass {
private int x;
private final Object lock = new Object(); //it must be final!
public void setX() {
synchronized(lock) {
x++;
}
}
}
Assuming they always exist and are not part of your data, this will work:
declare @string varchar(8000) = '23;chair,red [$3]'
select substring(@string, charindex(';', @string) + 1, charindex(' [', @string) - charindex(';', @string) - 1)
If the following conditions are true, then rewrite the URL:
If the requested filename is not a directory,
RewriteCond %{REQUEST_FILENAME} !-d
and if the requested filename is not a regular file that exists,
RewriteCond %{REQUEST_FILENAME} !-f
and if the requested filename is not a symbolic link,
RewriteCond %{REQUEST_FILENAME} !-l
then rewrite the URL in the following way:
Take the whole request filename and provide it as the value of a "url" query parameter to index.php. Append any query string from the original URL as further query parameters (QSA), and stop processing this .htaccess file (L).
RewriteRule ^(.+)$ index.php?url=$1 [QSA,L]
Another Example:
RewriteRule "/pages/(.+)" "/page.php?page=$1" [QSA]
With the [QSA] flag, a request for
/pages/123?one=two
will be mapped to
/page.php?page=123&one=two
WE had this issue. everything was setup fine in terms of permissions and security.
after MUCH needling around in the haystack. the issue was some sort of heuristics. in the email body , anytime a certain email address was listed, we would get the above error message from our exchange server.
it took 2 days of crazy testing and hair pulling to find this.
so if you have checked everything out, try changing the email body to only the word 'test'. If after that, your email goes out fine, you are having some sort of spam/heuristic filter issue like we were
The thing you will need to do here is use a linear gradient as background and animate the background position. In code:
Use a linear gradient (50% red, 50% blue) and tell the browser that background is 2 times larger than the element's width (width:200%, height:100%), then tell it to position the background left.
background: linear-gradient(to right, red 50%, blue 50%);
background-size: 200% 100%;
background-position:left bottom;
On hover, change the background position to right bottom
and with transition:all 2s ease;
, the position will change gradually (it's nicer with linear
tough)
background-position:right bottom;
As for the -vendor-prefix'es, see the comments to your question
extra If you wish to have a "transition" in the colour, you can make it 300% width and make the transition start at 34% (a bit more than 1/3) and end at 65% (a bit less than 2/3).
background: linear-gradient(to right, red 34%, blue 65%);
background-size: 300% 100%;
div {
font: 22px Arial;
display: inline-block;
padding: 1em 2em;
text-align: center;
color: white;
background: red; /* default color */
/* "to left" / "to right" - affects initial color */
background: linear-gradient(to left, salmon 50%, lightblue 50%) right;
background-size: 200%;
transition: .5s ease-out;
}
div:hover {
background-position: left;
}
_x000D_
<div>Hover me</div>
_x000D_
You can use switch case like this:
$(document).ready(function () {_x000D_
$("#type").change(function () {_x000D_
switch($(this).val()) {_x000D_
case 'item1':_x000D_
$("#size").html("<option value='test'>item1: test 1</option><option value='test2'>item1: test 2</option>");_x000D_
break;_x000D_
case 'item2':_x000D_
$("#size").html("<option value='test'>item2: test 1</option><option value='test2'>item2: test 2</option>");_x000D_
break;_x000D_
case 'item3':_x000D_
$("#size").html("<option value='test'>item3: test 1</option><option value='test2'>item3: test 2</option>");_x000D_
break;_x000D_
default:_x000D_
$("#size").html("<option value=''>--select one--</option>");_x000D_
}_x000D_
});_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<select id="type">_x000D_
<option value="item0">--Select an Item--</option>_x000D_
<option value="item1">item1</option>_x000D_
<option value="item2">item2</option>_x000D_
<option value="item3">item3</option>_x000D_
</select>_x000D_
_x000D_
<select id="size">_x000D_
<option value="">-- select one -- </option>_x000D_
</select>
_x000D_
Very simple: no color, no opacity:
rgba(0, 0, 0, 0);
Just in three steps:
Subscriptions: list -> https://www.googleapis.com/youtube/v3/subscriptions?part=snippet&maxResults=50&mine=true&access_token={oauth_token}
Channels: list -> https://www.googleapis.com/youtube/v3/channels?part=contentDetails&id={channel_id}&key={YOUR_API_KEY}
PlaylistItems: list -> https://www.googleapis.com/youtube/v3/playlistItems?part=snippet&playlistId={playlist_id}&key={YOUR_API_KEY}
if using /bin/sh
you can use:
if [ <condition> ] && [ <condition> ]; then
...
fi
if using /bin/bash
you can use:
if [[ <condition> && <condition> ]]; then
...
fi
The error SQLSTATE[HY000] [1040] Too many connections
is an SQL error, and has to do with the sql server. There could be other applications connecting to the server. The server has a maximum available connections number.
If you have phpmyadmin, you can use the 'variables' tab to check what the setting is.
You can also query the status table like so:
show status like '%onn%';
Or some variance on that. check the manual for what variables there are
(be aware, 'connections' is not the current connections, check that link :) )
This function works for all test cases that i could find. It's also faster than:
function isNumeric (n) {
if (!isNaN(parseFloat(n)) && isFinite(n) && !hasLeading0s(n)) {
return true;
}
var _n = +n;
return _n === Infinity || _n === -Infinity;
}
var isIntegerTest = /^\d+$/;_x000D_
var isDigitArray = [!0, !0, !0, !0, !0, !0, !0, !0, !0, !0];_x000D_
_x000D_
function hasLeading0s(s) {_x000D_
return !(typeof s !== 'string' ||_x000D_
s.length < 2 ||_x000D_
s[0] !== '0' ||_x000D_
!isDigitArray[s[1]] ||_x000D_
isIntegerTest.test(s));_x000D_
}_x000D_
var isWhiteSpaceTest = /\s/;_x000D_
_x000D_
function fIsNaN(n) {_x000D_
return !(n <= 0) && !(n > 0);_x000D_
}_x000D_
_x000D_
function isNumber(s) {_x000D_
var t = typeof s;_x000D_
if (t === 'number') {_x000D_
return (s <= 0) || (s > 0);_x000D_
} else if (t === 'string') {_x000D_
var n = +s;_x000D_
return !(fIsNaN(n) || hasLeading0s(s) || !(n !== 0 || !(s === '' || isWhiteSpaceTest.test(s))));_x000D_
} else if (t === 'object') {_x000D_
return !(!(s instanceof Number) || fIsNaN(+s));_x000D_
}_x000D_
return false;_x000D_
}_x000D_
_x000D_
function testRunner(IsNumeric) {_x000D_
var total = 0;_x000D_
var passed = 0;_x000D_
var failedTests = [];_x000D_
_x000D_
function test(value, result) {_x000D_
total++;_x000D_
if (IsNumeric(value) === result) {_x000D_
passed++;_x000D_
} else {_x000D_
failedTests.push({_x000D_
value: value,_x000D_
expected: result_x000D_
});_x000D_
}_x000D_
}_x000D_
// true_x000D_
test(0, true);_x000D_
test(1, true);_x000D_
test(-1, true);_x000D_
test(Infinity, true);_x000D_
test('Infinity', true);_x000D_
test(-Infinity, true);_x000D_
test('-Infinity', true);_x000D_
test(1.1, true);_x000D_
test(-0.12e-34, true);_x000D_
test(8e5, true);_x000D_
test('1', true);_x000D_
test('0', true);_x000D_
test('-1', true);_x000D_
test('1.1', true);_x000D_
test('11.112', true);_x000D_
test('.1', true);_x000D_
test('.12e34', true);_x000D_
test('-.12e34', true);_x000D_
test('.12e-34', true);_x000D_
test('-.12e-34', true);_x000D_
test('8e5', true);_x000D_
test('0x89f', true);_x000D_
test('00', true);_x000D_
test('01', true);_x000D_
test('10', true);_x000D_
test('0e1', true);_x000D_
test('0e01', true);_x000D_
test('.0', true);_x000D_
test('0.', true);_x000D_
test('.0e1', true);_x000D_
test('0.e1', true);_x000D_
test('0.e00', true);_x000D_
test('0xf', true);_x000D_
test('0Xf', true);_x000D_
test(Date.now(), true);_x000D_
test(new Number(0), true);_x000D_
test(new Number(1e3), true);_x000D_
test(new Number(0.1234), true);_x000D_
test(new Number(Infinity), true);_x000D_
test(new Number(-Infinity), true);_x000D_
// false_x000D_
test('', false);_x000D_
test(' ', false);_x000D_
test(false, false);_x000D_
test('false', false);_x000D_
test(true, false);_x000D_
test('true', false);_x000D_
test('99,999', false);_x000D_
test('#abcdef', false);_x000D_
test('1.2.3', false);_x000D_
test('blah', false);_x000D_
test('\t\t', false);_x000D_
test('\n\r', false);_x000D_
test('\r', false);_x000D_
test(NaN, false);_x000D_
test('NaN', false);_x000D_
test(null, false);_x000D_
test('null', false);_x000D_
test(new Date(), false);_x000D_
test({}, false);_x000D_
test([], false);_x000D_
test(new Int8Array(), false);_x000D_
test(new Uint8Array(), false);_x000D_
test(new Uint8ClampedArray(), false);_x000D_
test(new Int16Array(), false);_x000D_
test(new Uint16Array(), false);_x000D_
test(new Int32Array(), false);_x000D_
test(new Uint32Array(), false);_x000D_
test(new BigInt64Array(), false);_x000D_
test(new BigUint64Array(), false);_x000D_
test(new Float32Array(), false);_x000D_
test(new Float64Array(), false);_x000D_
test('.e0', false);_x000D_
test('.', false);_x000D_
test('00e1', false);_x000D_
test('01e1', false);_x000D_
test('00.0', false);_x000D_
test('01.05', false);_x000D_
test('00x0', false);_x000D_
test(new Number(NaN), false);_x000D_
test(new Number('abc'), false);_x000D_
console.log('Passed ' + passed + ' of ' + total + ' tests.');_x000D_
if (failedTests.length > 0) console.log({_x000D_
failedTests: failedTests_x000D_
});_x000D_
}_x000D_
testRunner(isNumber)
_x000D_
array[0].map((_, colIndex) => array.map(row => row[colIndex]));
map
calls a providedcallback
function once for each element in an array, in order, and constructs a new array from the results.callback
is invoked only for indexes of the array which have assigned values; it is not invoked for indexes which have been deleted or which have never been assigned values.
callback
is invoked with three arguments: the value of the element, the index of the element, and the Array object being traversed. [source]
SELECT * from
(
select m.*, rownum r
from maps006 m
)
where r > 49 and r < 101
You can do it by using the following simple jQuery code.
Tutorial, Demo, and Source code can be found from here - Smooth scroll to div using jQuery
JavaScript:
$(function() {
$('a[href*=#]:not([href=#])').click(function() {
var target = $(this.hash);
target = target.length ? target : $('[name=' + this.hash.substr(1) +']');
if (target.length) {
$('html,body').animate({
scrollTop: target.offset().top
}, 1000);
return false;
}
});
});
HTML:
<a href="#section1">Go Section 1</a>
<div id="section1">
<!-- Content goes here -->
</div>
It seems there is a change in how Application.COUNTA works in VB7 vs VB6. I tried the following in both versions of VB.
ReDim allData(0 To 1, 0 To 15)
Debug.Print Application.WorksheetFunction.CountA(allData)
In VB6 this returns 0.
Inn VB7 it returns 32
Looks like VB7 doesn't consider COUNTA to be COUNTA anymore.
As an alternative to everyone else's answers I've always done something like this:
List<String> toRemove = new ArrayList<String>();
for (String str : myArrayList) {
if (someCondition) {
toRemove.add(str);
}
}
myArrayList.removeAll(toRemove);
This will avoid you having to deal with the iterator directly, but requires another list. I've always preferred this route for whatever reason.
If you're just checking if word
is a number, that's not too hard:
#include <ctype.h>
...
string word;
bool isNumber = true;
for(string::const_iterator k = word.begin(); k != word.end(); ++k)
isNumber &&= isdigit(*k);
Optimize as desired.
To add to the previous answer, an extreme way of "cleaning" your project is to delete it (that is deleting its reference from the workspace, not deleting the actual files), and then re-import it.
Sometimes, it helps...
I use following code, found somewhere in the internet don't remember the source though.
var allText;
var rawFile = new XMLHttpRequest();
rawFile.open("GET", file, false);
rawFile.onreadystatechange = function () {
if (rawFile.readyState === 4) {
if (rawFile.status === 200 || rawFile.status == 0) {
allText = rawFile.responseText;
}
}
}
rawFile.send(null);
return JSON.parse(allText);
You can also use dictionaries that allows you to have more control over the plots:
import matplotlib.pyplot as plt
# plot 0 plot 1 plot 2 plot 3
x=[[1,2,3,4],[1,4,3,4],[1,2,3,4],[9,8,7,4]]
y=[[3,2,3,4],[3,6,3,4],[6,7,8,9],[3,2,2,4]]
plots = zip(x,y)
def loop_plot(plots):
figs={}
axs={}
for idx,plot in enumerate(plots):
figs[idx]=plt.figure()
axs[idx]=figs[idx].add_subplot(111)
axs[idx].plot(plot[0],plot[1])
return figs, axs
figs, axs = loop_plot(plots)
Now you can select the plot that you want to modify easily:
axs[0].set_title("Now I can control it!")
Of course, is up to you to decide what to do with the plots. You can either save them to disk figs[idx].savefig("plot_%s.png" %idx)
or show them plt.show()
. Use the argument block=False
only if you want to pop up all the plots together (this could be quite messy if you have a lot of plots). You can do this inside the loop_plot
function or in a separate loop using the dictionaries that the function provided.
One more addition: if you need to sync files by its extensions in one dir only (without of recursion) you should use a construction like this:
rsync -auzv --include './' --include '*.ext' --exclude '*' /source/dir/ /destination/dir/
Pay your attention to the dot in the first --include
. --no-r
does not work in this construction.
EDIT:
Thanks to gbyte.co for the valuable comment!
Here is a very interesting solution to your problem: http://24ways.org/2005/have-your-dom-and-script-it-too
So use this instead of script tags:
<img src="empty.gif" onload="alert('test');this.parentNode.removeChild(this);" />
Or the KISS answer for short lists:
[(i, j) for i in list1 for j in list2]
Not as performant as itertools but you're using python so performance is already not your top concern...
I like all the other answers too!
pip install -r requirements.txt
for python 2.x
pip3 install -r requirements.txt
for python 3.x
(in case multiple versions are installed)
Threaded:
/// <summary>
/// Usage: var timer = SetIntervalThread(DoThis, 1000);
/// UI Usage: BeginInvoke((Action)(() =>{ SetIntervalThread(DoThis, 1000); }));
/// </summary>
/// <returns>Returns a timer object which can be disposed.</returns>
public static System.Threading.Timer SetIntervalThread(Action Act, int Interval)
{
TimerStateManager state = new TimerStateManager();
System.Threading.Timer tmr = new System.Threading.Timer(new TimerCallback(_ => Act()), state, Interval, Interval);
state.TimerObject = tmr;
return tmr;
}
Regular
/// <summary>
/// Usage: var timer = SetInterval(DoThis, 1000);
/// UI Usage: BeginInvoke((Action)(() =>{ SetInterval(DoThis, 1000); }));
/// </summary>
/// <returns>Returns a timer object which can be stopped and disposed.</returns>
public static System.Timers.Timer SetInterval(Action Act, int Interval)
{
System.Timers.Timer tmr = new System.Timers.Timer();
tmr.Elapsed += (sender, args) => Act();
tmr.AutoReset = true;
tmr.Interval = Interval;
tmr.Start();
return tmr;
}
In python, it's called slicing. Here is an example of python's slice notation:
>>> list1 = ['a','b','c','d','e','f','g','h', 'i', 'j', 'k', 'l']
>>> print list1[:5]
['a', 'b', 'c', 'd', 'e']
>>> print list1[-7:]
['f', 'g', 'h', 'i', 'j', 'k', 'l']
Note how you can slice either positively or negatively. When you use a negative number, it means we slice from right to left.
You can use like this...
<div id="rot">hello</div>
#rot
{
-webkit-transform: rotate(-90deg);
-moz-transform: rotate(-90deg);
width:100px;
}
Have a look at this fiddle:http://jsfiddle.net/anish/MAN4g/
From man ping
:
-D Print timestamp (unix time + microseconds as in gettimeofday) before each line.
It will produce something like this:
[1337577886.346622] 64 bytes from 4.2.2.2: icmp_req=1 ttl=243 time=47.1 ms
Then timestamp could be parsed out from the ping
response and converted to the required format with date
.
For those who do not want to include the whole of jQuery UI, you can use jQuery.pulse.js instead.
To have looping animation of changing opacity, do this:
$('#target').pulse({opacity: 0.8}, {duration : 100, pulses : 5});
It is light (less than 1kb), and allows you to loop any kind of animations.
you could try by using a function like that :
<div ng-class='whatClassIsIt(call.State)'>
Then put your logic in the function itself :
$scope.whatClassIsIt= function(someValue){
if(someValue=="first")
return "ClassA"
else if(someValue=="second")
return "ClassB";
else
return "ClassC";
}
I made a fiddle with an example : http://jsfiddle.net/DotDotDot/nMk6M/
This will list all certificates:
keytool -list -keystore "$JAVA_HOME/jre/lib/security/cacerts"
To squash your local branch before pushing it:
checkout the branch in question to work on if it is not already checked out.
Find the sha of the oldest commit you wish to keep.
Create/checkout a new branch (tmp1) from that commit.
git checkout -b tmp1 <sha1-of-commit>
Merge the original branch into the new one squashing.
git merge --squash <original branch>
Commit the changes which have been created by the merge, with a summary commit message.
git commit -m <msg>
Checkout the original branch you want to squash.
git checkout <branch>
Reset to the original commit sha you wish to keep.
git reset --soft <sha1>
Rebase this branch based on the new tmp1 branch.
git rebase tmp1
That's it - now delete the temporary tmp1 branch once you're sure everything is ok.
Just as string.gmatch
will find patterns in a string, this function will find the things between patterns:
function string:split(pat)
pat = pat or '%s+'
local st, g = 1, self:gmatch("()("..pat..")")
local function getter(segs, seps, sep, cap1, ...)
st = sep and seps + #sep
return self:sub(segs, (seps or 0) - 1), cap1 or sep, ...
end
return function() if st then return getter(st, g()) end end
end
By default it returns whatever is separated by whitespace.
I know this is a little bit of necromancy, but you should use the Android AccountManager. It's purpose-built for this scenario. It's a little bit cumbersome but one of the things it does is invalidate the local credentials if the SIM card changes, so if somebody swipes your phone and throws a new SIM in it, your credentials won't be compromised.
This also gives the user a quick and easy way to access (and potentially delete) the stored credentials for any account they have on the device, all from one place.
SampleSyncAdapter is an example that makes use of stored account credentials.
I found the solution here:
http://xinyustudio.wordpress.com/2014/07/02/gradle-sdk-location-not-found-the-problem-and-solution/
Just create a file local.properties and add a line with sdk.dir=SDK_LOCATION
Subtract datetime.timedelta(days=1)
have a look at this snippet of code
nameMap := make(map[string]int)
nameMap["river"] = 33
v ,exist := nameMap["river"]
if exist {
fmt.Println("exist ",v)
}
Html.TextBox amd Html.DropDownList are not strongly typed and hence they doesn't require a strongly typed view. This means that we can hardcode whatever name we want. On the other hand, Html.TextBoxFor and Html.DropDownListFor are strongly typed and requires a strongly typed view, and the name is inferred from the lambda expression.
Strongly typed HTML helpers also provide compile time checking.
Since, in real time, we mostly use strongly typed views, prefer to use Html.TextBoxFor and Html.DropDownListFor over their counterparts.
Whether, we use Html.TextBox & Html.DropDownList OR Html.TextBoxFor & Html.DropDownListFor, the end result is the same, that is they produce the same HTML.
Strongly typed HTML helpers are added in MVC2.
os.system()
returns the (encoded) process exit value. 0
means success:
On Unix, the return value is the exit status of the process encoded in the format specified for
wait()
. Note that POSIX does not specify the meaning of the return value of the C system() function, so the return value of the Python function is system-dependent.
The output you see is written to stdout
, so your console or terminal, and not returned to the Python caller.
If you wanted to capture stdout
, use subprocess.check_output()
instead:
x = subprocess.check_output(['whoami'])
Or you can use the command line below from version 4.4.x.
conda config --set proxy_servers.http http://id:pw@address:port
conda config --set proxy_servers.https https://id:pw@address:port
The different between getTextBounds
and measureText
is described with the image below.
In short,
getTextBounds
is to get the RECT of the exact text. The measureText
is the length of the text, including the extra gap on the left and right.
If there are spaces between the text, it is measured in measureText
but not including in the length of the TextBounds, although the coordinate get shifted.
The text could be tilted (Skew) left. In this case, the bounding box left side would exceed outside the measurement of the measureText, and the overall length of the text bound would be bigger than measureText
The text could be tilted (Skew) right. In this case, the bounding box right side would exceed outside the measurement of the measureText, and the overall length of the text bound would be bigger than measureText
<html>
<head>
<script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$('#test').keypress(allowOnlyTwoPositiveDigts);
});
function allowOnlyTwoPositiveDigts(e){
var test = /^[\-]?[0-9]{1,2}?$/
return test.test(this.value+String.fromCharCode(e.which))
}
</script>
</head>
<body>
<input id="test" type="text" />
</body>
</html>
A simpler way is to use windows powershell instead of cmd. itworks fine with texter.
Pros
%1
, %2
, ... %*
in tact/arg
and -arg
styleCons
setlocal
for local scoping or write an accompanying :CLEAR-ARGS
routine!--force
to -f
)""
argument supportHere is an example how the following arguments relate to .bat variables:
>> testargs.bat /b 3 -c /d /e /f /g /h /i /j /k /bar 5 /foo "c:\"
echo %* | /b 3 -c /d /e /f /g /h /i /j /k /bar 5 /foo "c:\"
echo %ARG_FOO% | c:\
echo %ARG_A% |
echo %ARG_B% | 3
echo %ARG_C% | 1
echo %ARG_D% | 1
@echo off
setlocal
CALL :ARG-PARSER %*
::Print examples
echo: ALL: %*
echo: FOO: %ARG_FOO%
echo: A: %ARG_A%
echo: B: %ARG_B%
echo: C: %ARG_C%
echo: D: %ARG_D%
::*********************************************************
:: Parse commandline arguments into sane variables
:: See the following scenario as usage example:
:: >> thisfile.bat /a /b "c:\" /c /foo 5
:: >> CALL :ARG-PARSER %*
:: ARG_a=1
:: ARG_b=c:\
:: ARG_c=1
:: ARG_foo=5
::*********************************************************
:ARG-PARSER
::Loop until two consecutive empty args
:loopargs
IF "%~1%~2" EQU "" GOTO :EOF
set "arg1=%~1"
set "arg2=%~2"
shift
::Allow either / or -
set "tst1=%arg1:-=/%"
if "%arg1%" NEQ "" (
set "tst1=%tst1:~0,1%"
) ELSE (
set "tst1="
)
set "tst2=%arg2:-=/%"
if "%arg2%" NEQ "" (
set "tst2=%tst2:~0,1%"
) ELSE (
set "tst2="
)
::Capture assignments (eg. /foo bar)
IF "%tst1%" EQU "/" IF "%tst2%" NEQ "/" IF "%tst2%" NEQ "" (
set "ARG_%arg1:~1%=%arg2%"
GOTO loopargs
)
::Capture flags (eg. /foo)
IF "%tst1%" EQU "/" (
set "ARG_%arg1:~1%=1"
GOTO loopargs
)
goto loopargs
GOTO :EOF
According to this link:
http://code.neenbedankt.com/how-to-render-an-android-view-to-a-bitmap
You can render any View to a bitmap. It's probably worth assuming that you can layout a view as you require (including text, images etc.) and then render it to a Bitmap.
Using JVitela's code above you should be able to use that Bitmap as an OpenGL texture.
You could use shallow clones (git > 1.9):
git clone --depth depth remote-url
Further reading: http://blogs.atlassian.com/2014/05/handle-big-repositories-git/
You can also declare class variables as None which will prevent propagation. This is useful when you need a well defined class and want to prevent AttributeErrors. For example:
>>> class TestClass(object):
... t = None
...
>>> test = TestClass()
>>> test.t
>>> test2 = TestClass()
>>> test.t = 'test'
>>> test.t
'test'
>>> test2.t
>>>
Also if you need defaults:
>>> class TestClassDefaults(object):
... t = None
... def __init__(self, t=None):
... self.t = t
...
>>> test = TestClassDefaults()
>>> test.t
>>> test2 = TestClassDefaults([])
>>> test2.t
[]
>>> test.t
>>>
Of course still follow the info in the other answers about using mutable vs immutable types as the default in __init__
.
If you specify the disabled
attribute then the value you give it must be disabled
. (In HTML 5 you may leave off everything except the attribute value. In HTML 4 you may leave off everything except the attribute name.)
If you do not want the control to be disabled then do not specify the attribute at all.
Disabled:
<input type="checkbox" disabled>
<input type="checkbox" disabled="disabled">
Enabled:
<input type="checkbox">
Invalid (but usually error recovered to be treated as disabled):
<input type="checkbox" disabled="1">
<input type="checkbox" disabled="true">
<input type="checkbox" disabled="false">
So, without knowing your template language, I guess you are looking for:
<td><input type="checkbox" name="repriseCheckBox" {checkStat == 1 ? disabled : }/></td>
There is no space allocated for the strings. use array (or) pointers with malloc()
and free()
Other than that
#import <stdio.h>
#import <string.h>
should be
#include <stdio.h>
#include <string.h>
NOTE:
malloc()
ed must be free()
'edn + 1
bytes for a string which is of length n
(the last byte is for \0
)Please you the following code as a reference
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(int argc, char *argv[])
{
//char *str1 = "First string";
char *str1 = "First string is a big string";
char *str2 = NULL;
if ((str2 = (char *) malloc(sizeof(char) * strlen(str1) + 1)) == NULL) {
printf("unable to allocate memory \n");
return -1;
}
strcpy(str2, str1);
printf("str1 : %s \n", str1);
printf("str2 : %s \n", str2);
free(str2);
return 0;
}
Changing your deployment target is not a good idea to solve this problem (it will change which iOS versions you support on the app store).
What I did is restart just Xcode and it was fixed.
I just committed my code to a branch and pushed it to github, like this:
git branch SimonLowMemoryExperiments
git checkout SimonLowMemoryExperiments
git add .
git commit -a -m "Lots of experimentation with identifying the memory problems"
git push origin SimonLowMemoryExperiments
I've seen this style being used:
if (when || who || format || data || len);
Javascript code
// IE doesn't allow using a blob object directly as link href
// instead it is necessary to use msSaveOrOpenBlob
if (window.navigator && window.navigator.msSaveOrOpenBlob) {
window.navigator.msSaveOrOpenBlob(doc.output("blob"), "Name.pdf");
} else {
// For other browsers:
// Create a link pointing to the ObjectURL containing the blob.
doc.autoPrint();
window.open(
URL.createObjectURL(doc.output("blob")),
"_blank",
"height=650,width=500,scrollbars=yes,location=yes"
);
// For Firefox it is necessary to delay revoking the ObjectURL
setTimeout(() => {
window.URL.revokeObjectURL(doc.output("bloburl"));
}, 100);
}
From the SQL Server 2017 official documentation:
SELECT DATEADD(day, 360, GETDATE());
If you would like to remove the time part of the GETDATE
function, you can do:
SELECT DATEADD(day, 360, CAST(GETDATE() AS DATE));
Put your ScrollViewer in a DockPanel and set the DockPanel MaxHeight property
[...]
<DockPanel MaxHeight="700">
<ScrollViewer VerticalScrollBarVisibility="Auto">
<ItemsControl ItemSource ="{Binding ...}">
[...]
</ItemsControl>
</ScrollViewer>
</DockPanel>
[...]
There are two ways to fix this:
Execute the following in the MySQL console:
SET GLOBAL log_bin_trust_function_creators = 1;
Add the following to the mysql.ini configuration file:
log_bin_trust_function_creators = 1;
The setting relaxes the checking for non-deterministic functions. Non-deterministic functions are functions that modify data (i.e. have update, insert or delete statement(s)). For more info, see here.
Please note, if binary logging is NOT enabled, this setting does not apply.
Binary Logging of Stored Programs
If binary logging is not enabled, log_bin_trust_function_creators does not apply.
log_bin_trust_function_creators
This variable applies when binary logging is enabled.
The best approach is a better understanding and use of deterministic declarations for stored functions. These declarations are used by MySQL to optimize the replication and it is a good thing to choose them carefully to have a healthy replication.
DETERMINISTIC A routine is considered “deterministic” if it always produces the same result for the same input parameters and NOT DETERMINISTIC otherwise. This is mostly used with string or math processing, but not limited to that.
NOT DETERMINISTIC Opposite of "DETERMINISTIC". "If neither DETERMINISTIC nor NOT DETERMINISTIC is given in the routine definition, the default is NOT DETERMINISTIC. To declare that a function is deterministic, you must specify DETERMINISTIC explicitly.". So it seems that if no statement is made, MySQl will treat the function as "NOT DETERMINISTIC". This statement from manual is in contradiction with other statement from another area of manual which tells that: " When you create a stored function, you must declare either that it is deterministic or that it does not modify data. Otherwise, it may be unsafe for data recovery or replication. By default, for a CREATE FUNCTION statement to be accepted, at least one of DETERMINISTIC, NO SQL, or READS SQL DATA must be specified explicitly. Otherwise an error occurs"
I personally got error in MySQL 5.5 if there is no declaration, so i always put at least one declaration of "DETERMINISTIC", "NOT DETERMINISTIC", "NO SQL" or "READS SQL DATA" regardless other declarations i may have.
READS SQL DATA This explicitly tells to MySQL that the function will ONLY read data from databases, thus, it does not contain instructions that modify data, but it contains SQL instructions that read data (e.q. SELECT).
MODIFIES SQL DATA This indicates that the routine contains statements that may write data (for example, it contain UPDATE, INSERT, DELETE or ALTER instructions).
NO SQL This indicates that the routine contains no SQL statements.
CONTAINS SQL This indicates that the routine contains SQL instructions, but does not contain statements that read or write data. This is the default if none of these characteristics is given explicitly. Examples of such statements are SELECT NOW(), SELECT 10+@b, SET @x = 1 or DO RELEASE_LOCK('abc'), which execute but neither read nor write data.
Note that there are MySQL functions that are not deterministic safe, such as: NOW(), UUID(), etc, which are likely to produce different results on different machines, so a user function that contains such instructions must be declared as NOT DETERMINISTIC. Also, a function that reads data from an unreplicated schema is clearly NONDETERMINISTIC. *
Assessment of the nature of a routine is based on the “honesty” of the creator: MySQL does not check that a routine declared DETERMINISTIC is free of statements that produce nondeterministic results. However, misdeclaring a routine might affect results or affect performance. Declaring a nondeterministic routine as DETERMINISTIC might lead to unexpected results by causing the optimizer to make incorrect execution plan choices. Declaring a deterministic routine as NONDETERMINISTIC might diminish performance by causing available optimizations not to be used.
Perhaps you try this solution:
#define QUANTIDISCHI 6
#define QUDI(x) #x
#define QUdi(x) QUDI(x)
. . .
. . .
unsigned char TheNumber[] = "QUANTIDISCHI = " QUdi(QUANTIDISCHI) "\n";
I use an enum with no instances
public enum MyUtils {
; // no instances
// class is final and the constructor is private
public static int myUtilityMethod(int x) {
return x * x;
}
}
you can call this using
int y = MyUtils.myUtilityMethod(5); // returns 25.
As a general way to handle error in a loop like your sample code, I would rather use:
on error resume next
for each...
'do something that might raise an error, then
if err.number <> 0 then
...
end if
next ....
You are implicitly returning undefined
. You need to return the element.
this.state.data.map(function(item, i){
console.log('test');
return <li>Test</li>
})
There may be other ways to get your desired result.
Declare @a int
Declare @b int
SET @a = 3
SET @b=2
SELECT cast((cast(@a as float)/ cast(@b as float)) as float)
Request class doesn't offer a method that would return exactly what you need. But you can easily get it by concatenating results of 2 other methods:
echo (Request::getPathInfo() . (Request::getQueryString() ? ('?' . Request::getQueryString()) : '');
Try this:
string filename = @"C:/folder1/folder2/file.txt";
string FolderName = new DirectoryInfo(System.IO.Path.GetDirectoryName(filename)).Name;
Complete instruction is as follow:
openssl pkcs12 -in myfile.pfx -nocerts -out private-key.pem -nodes
openssl pkcs12 -in myfile.pfx -nokeys -out certificate.pem
yum install -y ca-certificates
,
cp your-cert.pem /etc/pki/ca-trust/source/anchors/your-cert.pem
,
update-ca-trust
,
update-ca-trust force-enable
Hope to be useful
Now a days, the easiest way I found to have a more updated version of Python is to install it via conda into a conda environment.
Install conda(you may need a virtualenv for this)
pip install conda
I'm adding this answer here because no manual download is needed. conda
will do that for you.
Now create an environment for the Python version you want. In this example I will use 3.5.2
, because it it the latest version at this time of writing (Aug 2016).
conda create -n py35 python=3.5.2
Will create a environment for conda to install packages
To activate this environment(I'm assuming linux otherwise check the conda docs):
source activate py35
Now install what you need either via pip or conda in the environemnt(conda has better binary package support).
conda install <package_name>
WHERE MyColumn = COALESCE(@value,MyColumn)
If @value
is NULL
, it will compare MyColumn
to itself, ignoring
@value = no where
clause.
IF @value
has a value (NOT NULL
) it will compare MyColumn
to
@value
.
Reference: COALESCE (Transact-SQL).
You can import them like this:
In [7]: import scipy, numpy, math
In [8]: scipy.math.factorial, numpy.math.factorial, math.factorial
Out[8]:
(<function math.factorial>,
<function math.factorial>,
<function math.factorial>)
scipy.math.factorial
and numpy.math.factorial
seem to simply be aliases/references for/to math.factorial
, that is scipy.math.factorial is math.factorial
and numpy.math.factorial is math.factorial
should both give True
.
Highlight a single null character, goto find replace - it usually automatically inserts the highlighted text into the find box. Enter a space into or leave blank the replace box.
For the sake of completeness: the previous answers tell how to set the upstream branch, but not how to see it.
There are a few ways to do this:
git branch -vv
shows that info for all branches. (formatted in blue in most terminals)
cat .git/config
shows this also.
For reference:
Strings aren't value types since they can be huge, and need to be stored on the heap. Value types are (in all implementations of the CLR as of yet) stored on the stack. Stack allocating strings would break all sorts of things: the stack is only 1MB for 32-bit and 4MB for 64-bit, you'd have to box each string, incurring a copy penalty, you couldn't intern strings, and memory usage would balloon, etc...
(Edit: Added clarification about value type storage being an implementation detail, which leads to this situation where we have a type with value sematics not inheriting from System.ValueType. Thanks Ben.)
Late to the game, but you can do it without @string/xyz
by using ?android:attr
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="?android:attr/versionName"
/>
<!-- or -->
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="?android:attr/versionCode"
/>
go to specific directory then run below command
# du -sh *
4.0K 1
4.0K anadb.sh --> Shell file
4.0K db.sh/ --> shell file
24K backup4/ --> Directory
8.0K backup6/ --> Directory
1.9G backup.sql.gz --> sql file
You can transform logical implication A => B
to NOT A or B
. This is one of the most basic laws of logic. In your case it is something like this:
SELECT *
FROM logs
WHERE pw='correct' AND (id>=800 OR success=1)
AND YEAR(timestamp)=2011
I also transformed NOT id<800
to id>=800
, which is also pretty basic.
As a newbie in React world, I came across a similar issues where I could not edit
the textarea and struggled
with binding. It's worth knowing about controlled
and uncontrolled
elements when it comes to react.
The value of the following uncontrolled textarea
cannot be changed because of value
<textarea type="text" value="some value"
onChange={(event) => this.handleOnChange(event)}></textarea>
The value of the following uncontrolled textarea
can be changed because of use of defaultValue
or no value attribute
<textarea type="text" defaultValue="sample"
onChange={(event) => this.handleOnChange(event)}></textarea>
<textarea type="text"
onChange={(event) => this.handleOnChange(event)}></textarea>
The value of the following controlled textarea
can be changed because of how
value is mapped to a state as well as the onChange
event listener
<textarea value={this.state.textareaValue}
onChange={(event) => this.handleOnChange(event)}></textarea>
Here is my solution using different syntax. I prefer the auto-bind
than manual binding however, if I were to not use {(event) => this.onXXXX(event)}
then that would cause the content of textarea
to be not editable OR the event.preventDefault()
does not work as expected. Still a lot to learn I suppose.
class Editor extends React.Component {
constructor(props) {
super(props)
this.state = {
textareaValue: ''
}
}
handleOnChange(event) {
this.setState({
textareaValue: event.target.value
})
}
handleOnSubmit(event) {
event.preventDefault();
this.setState({
textareaValue: this.state.textareaValue + ' [Saved on ' + (new Date()).toLocaleString() + ']'
})
}
render() {
return <div>
<form onSubmit={(event) => this.handleOnSubmit(event)}>
<textarea rows={10} cols={30} value={this.state.textareaValue}
onChange={(event) => this.handleOnChange(event)}></textarea>
<br/>
<input type="submit" value="Save"/>
</form>
</div>
}
}
ReactDOM.render(<Editor />, document.getElementById("content"));
The versions of libraries are
"babel-cli": "6.24.1",
"babel-preset-react": "6.24.1"
"React & ReactDOM v15.5.4"
Definitely use a service to share data between controllers, here is a working example. $broadcast is not the way to go, you should avoid using the eventing system when there is a more appropriate way. Use a 'service', 'value' or 'constant' (for global constants).
http://plnkr.co/edit/ETWU7d0O8Kaz6qpFP5Hp
Here is an example with an input so you can see the data mirror on the page: http://plnkr.co/edit/DbBp60AgfbmGpgvwtnpU
var testModule = angular.module('testmodule', []);
testModule
.controller('QuestionsStatusController1',
['$rootScope', '$scope', 'myservice',
function ($rootScope, $scope, myservice) {
$scope.myservice = myservice;
}]);
testModule
.controller('QuestionsStatusController2',
['$rootScope', '$scope', 'myservice',
function ($rootScope, $scope, myservice) {
$scope.myservice = myservice;
}]);
testModule
.service('myservice', function() {
this.xxx = "yyy";
});
If you get a model instance from the database, then calling the save method will always update that instance. For example:
t = TemperatureData.objects.get(id=1)
t.value = 999 # change field
t.save() # this will update only
If your goal is prevent any INSERTs, then you can override the save
method, test if the primary key exists and raise an exception. See the following for more detail:
You can use the OFFSET FETCH clause.
SELECT COUNT(1) FROM COHORT; --Number of results to expect
SELECT * FROM COHORT
ORDER BY ID
OFFSET 900 ROWS --Assuming you expect 1000 rows
FETCH NEXT 100 ROWS ONLY;
(This is for Microsoft SQL Server)
Official documentation: https://www.sqlservertutorial.net/sql-server-basics/sql-server-offset-fetch/
Use RowCounter in HBase RowCounter is a mapreduce job to count all the rows of a table. This is a good utility to use as a sanity check to ensure that HBase can read all the blocks of a table if there are any concerns of metadata inconsistency. It will run the mapreduce all in a single process but it will run faster if you have a MapReduce cluster in place for it to exploit.
$ hbase org.apache.hadoop.hbase.mapreduce.RowCounter <tablename>
Usage: RowCounter [options]
<tablename> [
--starttime=[start]
--endtime=[end]
[--range=[startKey],[endKey]]
[<column1> <column2>...]
]
You want to use two keys independently, so you have two choices:
Store the data redundantly with two dicts as {'banana' : {'blue' : 4, ...}, .... }
and {'blue': {'banana':4, ...} ...}
. Then, searching and sorting is easy but you have to make sure you modify the dicts together.
Store it just one dict, and then write functions that iterate over them eg.:
d = {'banana' : {'blue' : 4, 'yellow':6}, 'apple':{'red':1} }
blueFruit = [(fruit,d[fruit]['blue']) if d[fruit].has_key('blue') for fruit in d.keys()]
If I'm reading your question correctly, objects in general are agnostic about where they are contained. They don't know who their parents are. To find that information, you have to parse the parent data structure. The DOM has ways of doing this for us when you're talking about element objects in a document, but it looks like you're talking about vanilla objects.
In Vue.js 2 Inside a Vue Instance or Component:
this.$el
to get the HTMLElement the instance/component was mounted toFrom an HTMLElement
:
.__vue__
from the HTMLElement
var vueInstance = document.getElementById('app').__vue__;
Having a VNode
in a variable called vnode
you can:
vnode.elm
to get the element that VNode was rendered tovnode.context
to get the VueComponent instance that VNode's component was declared (this usually returns the parent component, but may surprise you when using slots.vnode.componentInstance
to get the Actual VueComponent instance that VNode is aboutSource, literally: vue/flow/vnode.js.
Vue.config.productionTip = false; // disable developer version warning
console.log('-------------------')
Vue.component('my-component', {
template: `<input>`,
mounted: function() {
console.log('[my-component] is mounted at element:', this.$el);
}
});
Vue.directive('customdirective', {
bind: function (el, binding, vnode) {
console.log('[DIRECTIVE] My Element is:', vnode.elm);
console.log('[DIRECTIVE] My componentInstance is:', vnode.componentInstance);
console.log('[DIRECTIVE] My context is:', vnode.context);
// some properties, such as $el, may take an extra tick to be set, thus you need to...
Vue.nextTick(() => console.log('[DIRECTIVE][AFTER TICK] My context is:', vnode.context.$el))
}
})
new Vue({
el: '#app',
mounted: function() {
console.log('[ROOT] This Vue instance is mounted at element:', this.$el);
console.log('[ROOT] From the element to the Vue instance:', document.getElementById('app').__vue__);
console.log('[ROOT] Vue component instance of my-component:', document.querySelector('input').__vue__);
}
})
_x000D_
<script src="https://unpkg.com/[email protected]/dist/vue.min.js"></script>
<h1>Open the browser's console</h1>
<div id="app">
<my-component v-customdirective=""></my-component>
</div>
_x000D_
You can have many java versions in your system.
I think you should add the java 8 in yours JREs installed or edit.
Take a look my screen:
If you click in edit (check your java 8 path):
RewriteEngine on
RewriteCond %{HTTP_HOST} ^(www\.)?olddomain\.com$ [NC]
RewriteRule ^(.*)$ "http://www.thenewdomain.com/" [R=301,L]
You can use the "filter" filter in your controller to get all the "C" grades. Getting the first element of the result array will give you the title of the subject that has grade "C".
$scope.gradeC = $filter('filter')($scope.results.subjects, {grade: 'C'})[0];
http://jsbin.com/ewitun/1/edit
The same with plain ES6:
$scope.gradeC = $scope.results.subjects.filter((subject) => subject.grade === 'C')[0]
You are binding the click
event to anchors with an href attribute with value sign_new
.
Either bind anchors with class sign_new
or bind anchors with href value #sign_up
. I would prefer the former.
Jersey needs to be unpacked jars.
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<configuration>
<requiresUnpack>
<dependency>
<groupId>com.myapp</groupId>
<artifactId>rest-api</artifactId>
</dependency>
</requiresUnpack>
</configuration>
</plugin>
</plugins>
</build>
In your template, you have access to all the variables that are members of the current $scope
. So, tobedone
should be $scope.tobedone
, and then you can display it with {{tobedone}}
, or [[tobedone]]
in your case.
It's very simple to get SelectList and SelectedValue working together, even if your property isn't a simple object like a Int, String or a Double value.
Example:
Assuming our Region object is something like this:
public class Region {
public Guid ID { get; set; }
public Guid Name { get; set; }
}
And your view model is something like:
public class ContactViewModel {
public DateTime Date { get; set; }
public Region Region { get; set; }
public List<Region> Regions { get; set; }
}
You can have the code below:
@Html.DropDownListFor(x => x.Region, new SelectList(Model.Regions, "ID", "Name"))
Only if you override the ToString method of Region object to something like:
public class Region {
public Guid ID { get; set; }
public Guid Name { get; set; }
public override string ToString()
{
return ID.ToString();
}
}
This have 100% garantee to work.
But I really believe the best way to get SelectList 100% working in all circustances is by using the Equals method to test DropDownList or ListBox property value against each item on items collection.
if ($done)
{
header("Location: /url/to/the/other/page");
exit;
}
The only benefit in using the newInstance()
that I see are the following:
You will have a single place where all the arguments used by the fragment could be bundled up and you don't have to write the code below everytime you instantiate a fragment.
Bundle args = new Bundle();
args.putInt("someInt", someInt);
args.putString("someString", someString);
// Put any other arguments
myFragment.setArguments(args);
Its a good way to tell other classes what arguments it expects to work faithfully(though you should be able to handle cases if no arguments are bundled in the fragment instance).
So, my take is that using a static newInstance()
to instantiate a fragment is a good practice.
It’s about time someone provides the modern answer. The modern solution uses java.time, the modern Java date and time API. The classes SimpleDateFormat
and Date
used in the question and in a couple of the other answers are poorly designed and long outdated, the former in particular notoriously troublesome. TimeZone
is poorly designed to. I recommend you avoid those.
ZoneId utc = ZoneId.of("Etc/UTC");
DateTimeFormatter targetFormatter = DateTimeFormatter.ofPattern(
"MM/dd/yyyy hh:mm:ss a zzz", Locale.ENGLISH);
String itsAlarmDttm = "2013-10-22T01:37:56";
ZonedDateTime utcDateTime = LocalDateTime.parse(itsAlarmDttm)
.atZone(ZoneId.systemDefault())
.withZoneSameInstant(utc);
String formatterUtcDateTime = utcDateTime.format(targetFormatter);
System.out.println(formatterUtcDateTime);
When running in my time zone, Europe/Copenhagen, the output is:
10/21/2013 11:37:56 PM UTC
I have assumed that the string you got was in the default time zone of your JVM, a fragile assumption since that default setting can be changed at any time from another part of your program or another programming running in the same JVM. If you can, instead specify time zone explicitly, for example ZoneId.of("Europe/Podgorica")
or ZoneId.of("Asia/Kolkata")
.
I am exploiting the fact that you string is in ISO 8601 format, the format the the modern classes parse as their default, that is, without any explicit formatter.
I am using a ZonedDateTime
for the result date-time because it allows us to format it with UTC
in the formatted string to eliminate any and all doubt. For other purposes one would typically have wanted an OffsetDateTime
or an Instant
instead.
For Perfect DateTime
Match in SQL Server
SELECT ID FROM [Table Name] WHERE (DateLog between '2017-02-16 **00:00:00.000**' and '2017-12-16 **23:59:00.999**') ORDER BY DateLog DESC
This message is the __str__
attribute of exit
look at these examples :
1
>>> print exit
Use exit() or Ctrl-D (i.e. EOF) to exit
2
>>> exit.__str__()
'Use exit() or Ctrl-D (i.e. EOF) to exit'
3
>>> getattr(exit, '__str__')()
'Use exit() or Ctrl-D (i.e. EOF) to exit'
With a default option having selected attribute
<select>
<option value="" selected>Choose your city</option>
<option value ="sydney">Sydney</option>
<option value ="melbourne">Melbourne</option>
<option value ="cromwell">Cromwell</option>
<option value ="queenstown">Queenstown</option>
</select>
There are many answers here but I couldn't find something simple that covers all cases so allow me to suggest my solution too:
import pathlib_x000D_
import os_x000D_
_x000D_
def get_project_root():_x000D_
"""_x000D_
There is no way in python to get project root. This function uses a trick._x000D_
We know that the function that is currently running is in the project._x000D_
We know that the root project path is in the list of PYTHONPATH_x000D_
look for any path in PYTHONPATH list that is contained in this function's path_x000D_
Lastly we filter and take the shortest path because we are looking for the root._x000D_
:return: path to project root_x000D_
"""_x000D_
apth = str(pathlib.Path().absolute())_x000D_
ppth = os.environ['PYTHONPATH'].split(':')_x000D_
matches = [x for x in ppth if x in apth]_x000D_
project_root = min(matches, key=len)_x000D_
return project_root
_x000D_
dataset <- matrix(sample(c(NA, 1:5), 25, replace = TRUE), 5);
data <- as.data.frame(dataset)
[,1] [,2] [,3] [,4] [,5] [1,] 2 3 5 5 4 [2,] 2 4 3 2 4 [3,] 2 NA NA NA 2 [4,] 2 3 NA 5 5 [5,] 2 3 2 2 3
data[is.na(data)] <- 0
If you use an other server as reverse proxy all of the mentioned fields will contain localhost. The easiest workaround is to add headers for ip/port in the proxy server.
Example for nginx:
add this after your proxy_pass
:
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Real-Port $remote_port;
This will make the headers available in the socket.io node server:
var ip = socket.handshake.headers["x-real-ip"];
var port = socket.handshake.headers["x-real-port"];
Note that the header is internally converted to lower case.
If you are connecting the node server directly to the client,
var ip = socket.conn.remoteAddress;
works with socket.io version 1.4.6 for me.
This works without changing the validation mode.
You have to use a System.Web.Helpers.Validation.Unvalidated
helper from System.Web.WebPages.dll
. It is going to return a UnvalidatedRequestValues
object which allows to access the form and QueryString without validation.
For example,
var queryValue = Server.UrlDecode(Request.Unvalidated("MyQueryKey"));
Works for me for MVC3 and .NET 4.
This is another option:
export default function Counter() {
}
I wrote a function that passes a function when wrapped in any resize event. It uses an interval so that the resize even isn't constantly creating timeout events. This allows it to perform independently of the resize event other than a log entry that should be removed in production.
https://github.com/UniWrighte/resizeOnEnd/blob/master/resizeOnEnd.js
$(window).resize(function(){
//call to resizeEnd function to execute function on resize end.
//can be passed as function name or anonymous function
resizeEnd(function(){
});
});
//global variables for reference outside of interval
var interval = null;
var width = $(window).width();
var numi = 0; //can be removed in production
function resizeEnd(functionCall){
//check for null interval
if(!interval){
//set to new interval
interval = setInterval(function(){
//get width to compare
width2 = $(window).width();
//if stored width equals new width
if(width === width2){
//clear interval, set to null, and call passed function
clearInterval(interval);
interval = null; //precaution
functionCall();
}
//set width to compare on next interval after half a second
width = $(window).width();
}, 500);
}else{
//logging that should be removed in production
console.log("function call " + numi++ + " and inteval set skipped");
}
}
I've written this Codesandbox for a roundtrip from UTC to local time and from local time to UTC. You can change the timezone and the format. Enjoy!
Full Example on Codesandbox (DEMO):
https://codesandbox.io/s/momentjs-utc-to-local-roundtrip-foj57?file=/src/App.js
Its because of wrong path provided. It may be that the url contains space and if the case url has to be properly constructed.
The correct url should be in the format with file name included like "http://server name/document library name/new file name"
So if report.xlsx is the file that has to be uploaded at "http://server name/Team/Dev Team" then path comes out to be is "http://server name/Team/Dev Team/report.xlsx". It contains space so it should be reconstructed as "http://server name/Team/Dev%20Team/report.xlsx" and should be used.
You can use %~dp0
to get the path of the currently running batch file.
Edited to change directory to the VBS location before running
If you want the VBS to synchronously run in the same window, then
@echo off
pushd %~dp0
cscript necdaily.vbs
If you want the VBS to synchronously run in a new window, then
@echo off
pushd %~dp0
start /wait "" cmd /c cscript necdaily.vbs
If you want the VBS to asynchronously run in the same window, then
@echo off
pushd %~dp0
start /b "" cscript necdaily.vbs
If you want the VBS to asynchronously run in a new window, then
@echo off
pushd %~dp0
start "" cmd /c cscript necdaily.vbs
Use this in your batch file:
%~dp0\bin\Iris.exe
%~dp0
resolves to the full path of the folder in which the batch script resides.
It was giving 415 Http response Code as error,
So I added
httppost.addHeader("Content-Type", "text/xml; charset=utf-8");
Everything alright now, Http: 200
As already mentioned, you can get a performance increase from having your python code compiled into bytecode. This is usually handled by python itself, for imported scripts only.
Another reason you might want to compile your python code, could be to protect your intellectual property from being copied and/or modified.
You can read more about this in the Python documentation.
For security code, please don't generate your tokens this way: $token = md5(uniqid(rand(), TRUE));
rand()
is predictableuniqid()
only adds up to 29 bits of entropymd5()
doesn't add entropy, it just mixes it deterministicallyTry this out:
session_start();
if (empty($_SESSION['token'])) {
$_SESSION['token'] = bin2hex(random_bytes(32));
}
$token = $_SESSION['token'];
Sidenote: One of my employer's open source projects is an initiative to backport random_bytes()
and random_int()
into PHP 5 projects. It's MIT licensed and available on Github and Composer as paragonie/random_compat.
session_start();
if (empty($_SESSION['token'])) {
if (function_exists('mcrypt_create_iv')) {
$_SESSION['token'] = bin2hex(mcrypt_create_iv(32, MCRYPT_DEV_URANDOM));
} else {
$_SESSION['token'] = bin2hex(openssl_random_pseudo_bytes(32));
}
}
$token = $_SESSION['token'];
Don't just use ==
or even ===
, use hash_equals()
(PHP 5.6+ only, but available to earlier versions with the hash-compat library).
if (!empty($_POST['token'])) {
if (hash_equals($_SESSION['token'], $_POST['token'])) {
// Proceed to process the form data
} else {
// Log this as a warning and keep an eye on these attempts
}
}
You can further restrict tokens to only be available for a particular form by using hash_hmac()
. HMAC is a particular keyed hash function that is safe to use, even with weaker hash functions (e.g. MD5). However, I recommend using the SHA-2 family of hash functions instead.
First, generate a second token for use as an HMAC key, then use logic like this to render it:
<input type="hidden" name="token" value="<?php
echo hash_hmac('sha256', '/my_form.php', $_SESSION['second_token']);
?>" />
And then using a congruent operation when verifying the token:
$calc = hash_hmac('sha256', '/my_form.php', $_SESSION['second_token']);
if (hash_equals($calc, $_POST['token'])) {
// Continue...
}
The tokens generated for one form cannot be reused in another context without knowing $_SESSION['second_token']
. It is important that you use a separate token as an HMAC key than the one you just drop on the page.
Anyone who uses the Twig templating engine can benefit from a simplified dual strategy by adding this filter to their Twig environment:
$twigEnv->addFunction(
new \Twig_SimpleFunction(
'form_token',
function($lock_to = null) {
if (empty($_SESSION['token'])) {
$_SESSION['token'] = bin2hex(random_bytes(32));
}
if (empty($_SESSION['token2'])) {
$_SESSION['token2'] = random_bytes(32);
}
if (empty($lock_to)) {
return $_SESSION['token'];
}
return hash_hmac('sha256', $lock_to, $_SESSION['token2']);
}
)
);
With this Twig function, you can use both the general purpose tokens like so:
<input type="hidden" name="token" value="{{ form_token() }}" />
Or the locked down variant:
<input type="hidden" name="token" value="{{ form_token('/my_form.php') }}" />
Twig is only concerned with template rendering; you still must validate the tokens properly. In my opinion, the Twig strategy offers greater flexibility and simplicity, while maintaining the possibility for maximum security.
If you have a security requirement that each CSRF token is allowed to be usable exactly once, the simplest strategy regenerate it after each successful validation. However, doing so will invalidate every previous token which doesn't mix well with people who browse multiple tabs at once.
Paragon Initiative Enterprises maintains an Anti-CSRF library for these corner cases. It works with one-use per-form tokens, exclusively. When enough tokens are stored in the session data (default configuration: 65535), it will cycle out the oldest unredeemed tokens first.
I don't think we can compare them side by side like who is better. That won't be a fair comparison simply because they are solving two different problems. Their requirements are different. It will be like comparing apples to oranges. They are different.
HTTP is a request-response protocol. The client (browser) wants something, the server gives it. That is. If the data client wants is big, the server might send streaming data to void unwanted buffer problems. Here the main requirement or problem is how to make the request from clients and how to response the resources(hypertext) they request. That is where HTTP shine.
In HTTP, only client requests. The server only responds.
WebSocket is not a request-response protocol where only the client can request. It is a socket(very similar to TCP socket). Mean once the connection is open, either side can send data until the underlining TCP connection is closed. It is just like a normal socket. The only difference with TCP socket is WebSocket can be used on the web. On the web, we have many restrictions on a normal socket. Most firewalls will block other ports than 80 and 433 that HTTP used. Proxies and intermediaries will be problematic as well. So to make the protocol easier to deploy to existing infrastructures WebSocket use HTTP handshake to upgrade. That means when the first time connection is going to open, the client sent an HTTP request to tell the server saying "That is not HTTP request, please upgrade to WebSocket protocol".
Upgrade: websocket
Connection: Upgrade
Sec-WebSocket-Key: x3JJHMbDL1EzLkh9GBhXDw==
Sec-WebSocket-Protocol: chat, superchat
Sec-WebSocket-Version: 13
Once the server understands the request and upgraded to WebSocket protocol, none of the HTTP protocols applied anymore.
So my answer is Neither one is better than each other. They are completely different.
Well, we can make everything under the name called HTTP as well. But shall we? If they are two different things, I will prefer two different names. So do Hickson and Michael Carter .
The format for new RegExp is
RegExp(something, 'modifiers');
So you would want
accentsTidy = function(s){
var r=s.toLowerCase();
r = r.replace(new RegExp("\\s", 'g'),"");
r = r.replace(new RegExp("[àáâãäå]", 'g'),"a");
r = r.replace(new RegExp("æ", 'g'),"ae");
r = r.replace(new RegExp("ç", 'g'),"c");
r = r.replace(new RegExp("[èéêë]", 'g'),"e");
r = r.replace(new RegExp("[ìíîï]", 'g'),"i");
r = r.replace(new RegExp("ñ", 'g'),"n");
r = r.replace(new RegExp("[òóôõö]", 'g'),"o");
r = r.replace(new RegExp("œ", 'g'),"oe");
r = r.replace(new RegExp("[ùúûü]", 'g'),"u");
r = r.replace(new RegExp("[ýÿ]", 'g'),"y");
r = r.replace(new RegExp("\\W", 'g'),"");
return r;
};
The RestTemplate getForObject()
method does not support setting headers. The solution is to use the exchange()
method.
So instead of restTemplate.getForObject(url, String.class, param)
(which has no headers), use
HttpHeaders headers = new HttpHeaders();
headers.set("Header", "value");
headers.set("Other-Header", "othervalue");
...
HttpEntity entity = new HttpEntity(headers);
ResponseEntity<String> response = restTemplate.exchange(
url, HttpMethod.GET, entity, String.class, param);
Finally, use response.getBody()
to get your result.
This question is similar to this question.
Try this out to execute a command on 30th March 2011 at midnight:
0 0 30 3 ? 2011 /command
WARNING: As noted in comments, the year column is not supported in standard/default implementations of cron. Please refer to TomOnTime answer below, for a proper way to run a script at a specific time in the future in standard implementations of cron.
They are several ways to run python script:
Each of these ways can run a different version of python (¤)
Check which python version is run by cmd: Type in cmd:
python --version
Check which python version is run when clicking on .py:
option 1:
create a test.py containing this:
import sys print (sys.version)
input("exit")
Option 2:
type in cmd:
assoc .py
ftype Python.File
Check the path and if the module (ex: win32clipboard) is recognized in the cmd:
create a test.py containing this:
python
import sys
sys.executable
sys.path
import win32clipboard
win32clipboard.__file__
Check the path and if module is recognized in the .py
create a test.py containing this:
import sys
print(sys.executable)
print(sys.path)
import win32clipboard
print(win32clipboard.__file__)
If the version in cmd is ok but not in .py it's because the default program associated with .py isn't the right one. Change python version for .py
To change the python version associated with cmd:
Control Panel\All Control Panel Items\System\Advanced system setting\Environnement variable
In SYSTEM variable set the path
variable to you python version (the path are separated by ;
: cmd use the FIRST path eg: C:\path\to\Python27;C:\path\to\Python35 ? cmd will use python27)
To change the python version associated with .py extension:
Run cmd as admin:
Write: ftype Python.File="C:\Python35\python.exe" "%1" %*
It will set the last python version (eg. python3.6). If your last version is 3.6 but you want 3.5 just add some xxx in your folder (xxxpython36) so it will take the last recognized version which is python3.5 (after the cmd remove the xxx).
Other:
"No modul error" could also come from a syntax error btw python et 3 (eg. missing parenthesis for print function...)
¤ Thus each of them has it's own pip version
The following code snippet enables/disables a button depending on whether at least one checkbox on the page has been checked.
$('input[type=checkbox]').change(function () {
$('#test > tbody tr').each(function () {
if ($('input[type=checkbox]').is(':checked')) {
$('#btnexcellSelect').removeAttr('disabled');
} else {
$('#btnexcellSelect').attr('disabled', 'disabled');
}
if ($(this).is(':checked')){
console.log( $(this).attr('id'));
}else{
console.log($(this).attr('id'));
}
});
});
Here is demo in JSFiddle.
cleanText = strInputCode.replace(/<\/?[^>]+(>|$)/g, "");
Distilled from this website (web.achive).
This regex looks for <
, an optional slash /
, one or more characters that are not >
, then either >
or $
(the end of the line)
Examples:
'<div>Hello</div>' ==> 'Hello'
^^^^^ ^^^^^^
'Unterminated Tag <b' ==> 'Unterminated Tag '
^^
But it is not bulletproof:
'If you are < 13 you cannot register' ==> 'If you are '
^^^^^^^^^^^^^^^^^^^^^^^^
'<div data="score > 42">Hello</div>' ==> ' 42">Hello'
^^^^^^^^^^^^^^^^^^ ^^^^^^
If someone is trying to break your application, this regex will not protect you. It should only be used if you already know the format of your input. As other knowledgable and mostly sane people have pointed out, to safely strip tags, you must use a parser.
If you do not have acccess to a convenient parser like the DOM, and you cannot trust your input to be in the right format, you may be better off using a package like sanitize-html, and also other sanitizers are available.
$(this).closest('ul').attr('id');
To add to add to the previous answer, there is even a fourth way that can be used
import codecs
encoded4 = codecs.encode(original, 'utf-8')
print(encoded4)
>>> d = {}
>>> D = set()
>>> type(d)
<type 'dict'>
>>> type(D)
<type 'set'>
What you've made is a dictionary and not a Set.
The update
method in dictionary is used to update the new dictionary from a previous one, like so,
>>> abc = {1: 2}
>>> d.update(abc)
>>> d
{1: 2}
Whereas in sets, it is used to add elements to the set.
>>> D.update([1, 2])
>>> D
set([1, 2])
>
selects immediate childrenFor example, if you have nested divs like such:
<div class='outer'>
<div class="middle">
<div class="inner">...</div>
</div>
<div class="middle">
<div class="inner">...</div>
</div>
</div>
and you declare a css rule in your stylesheet like such:
.outer > div {
...
}
your rules will apply only to those divs that have a class of "middle" since those divs are direct descendants (immediate children) of elements with class "outer" (unless, of course, you declare other, more specific rules overriding these rules). See fiddle.
div {_x000D_
border: 1px solid black;_x000D_
padding: 10px;_x000D_
}_x000D_
.outer > div {_x000D_
border: 1px solid orange;_x000D_
}
_x000D_
<div class='outer'>_x000D_
div.outer - This is the parent._x000D_
<div class="middle">_x000D_
div.middle - This is an immediate child of "outer". This will receive the orange border._x000D_
<div class="inner">div.inner - This is an immediate child of "middle". This will not receive the orange border.</div>_x000D_
</div>_x000D_
<div class="middle">_x000D_
div.middle - This is an immediate child of "outer". This will receive the orange border._x000D_
<div class="inner">div.inner - This is an immediate child of "middle". This will not receive the orange border.</div>_x000D_
</div>_x000D_
</div>_x000D_
_x000D_
<p>Without Words</p>_x000D_
_x000D_
<div class='outer'>_x000D_
<div class="middle">_x000D_
<div class="inner">...</div>_x000D_
</div>_x000D_
<div class="middle">_x000D_
<div class="inner">...</div>_x000D_
</div>_x000D_
</div>
_x000D_
If you, instead, had a space between selectors instead of
>
, your rules would apply to both of the nested divs. The space is much more commonly used and defines a "descendant selector", which means it looks for any matching element down the tree rather than just immediate children as the >
does.
NOTE: The >
selector is not supported by IE6. It does work in all other current browsers though, including IE7 and IE8.
If you're looking into less-well-used CSS selectors, you may also want to look at +
, ~
, and [attr]
selectors, all of which can be very useful.
This page has a full list of all available selectors, along with details of their support in various browsers (its mainly IE that has problems), and good examples of their usage.
You should append to the container, not the last element:
$("#content ul").append('<li><a href="/user/messages"><span class="tab">Message Center</span></a></li>');
The append() function should've probably been called add() in jQuery because it sometimes confuses people. You would think it appends something after the given element, while it actually adds it to the element.
Here's another answer that has an option to append decimal ONLY IF decimal was not zero.
/**
* Example: (isDecimalRequired = true)
* d = 12345
* returns 12,345.00
*
* d = 12345.12345
* returns 12,345.12
*
* ==================================================
* Example: (isDecimalRequired = false)
* d = 12345
* returns 12,345 (notice that there's no decimal since it's zero)
*
* d = 12345.12345
* returns 12,345.12
*
* @param d float to format
* @param zeroCount number decimal places
* @param isDecimalRequired true if it will put decimal even zero,
* false will remove the last decimal(s) if zero.
*/
fun formatDecimal(d: Float? = 0f, zeroCount: Int, isDecimalRequired: Boolean = true): String {
val zeros = StringBuilder()
for (i in 0 until zeroCount) {
zeros.append("0")
}
var pattern = "#,##0"
if (zeros.isNotEmpty()) {
pattern += ".$zeros"
}
val numberFormat = DecimalFormat(pattern)
var formattedNumber = if (d != null) numberFormat.format(d) else "0"
if (!isDecimalRequired) {
for (i in formattedNumber.length downTo formattedNumber.length - zeroCount) {
val number = formattedNumber[i - 1]
if (number == '0' || number == '.') {
formattedNumber = formattedNumber.substring(0, formattedNumber.length - 1)
} else {
break
}
}
}
return formattedNumber
}
Since the author did not specify whether they require a solution for Java versions that have been EoL'd (by both Sun and IBM, and these are technically the most widespread JVMs), and due to the fact that most people seem to have answered the author's question before it was specified that it is a text (non-binary) file, I have decided to provide my answer.
First of all, Java 6 has generally reached end of life, and since the author did not specify he needs legacy compatibility, I guess it automatically means Java 7 or above (Java 7 is not yet EoL'd by IBM). So, we can look right at the file I/O tutorial: https://docs.oracle.com/javase/tutorial/essential/io/legacy.html
Prior to the Java SE 7 release, the java.io.File class was the mechanism used for file I/O, but it had several drawbacks.
- Many methods didn't throw exceptions when they failed, so it was impossible to obtain a useful error message. For example, if a file deletion failed, the program would receive a "delete fail" but wouldn't know if it was because the file didn't exist, the user didn't have permissions, or there was some other problem.
- The rename method didn't work consistently across platforms.
- There was no real support for symbolic links.
- More support for metadata was desired, such as file permissions, file owner, and other security attributes. Accessing file metadata was inefficient.
- Many of the File methods didn't scale. Requesting a large directory listing over a server could result in a hang. Large directories could also cause memory resource problems, resulting in a denial of service.
- It was not possible to write reliable code that could recursively walk a file tree and respond appropriately if there were circular symbolic links.
Oh well, that rules out java.io.File. If a file cannot be written/appended, you may not be able to even know why.
We can continue looking at the tutorial: https://docs.oracle.com/javase/tutorial/essential/io/file.html#common
If you have all lines you will write (append) to the text file in advance, the recommended approach is https://docs.oracle.com/javase/8/docs/api/java/nio/file/Files.html#write-java.nio.file.Path-java.lang.Iterable-java.nio.charset.Charset-java.nio.file.OpenOption...-
Here's an example (simplified):
Path file = ...;
List<String> linesInMemory = ...;
Files.write(file, linesInMemory, StandardCharsets.UTF_8);
Another example (append):
Path file = ...;
List<String> linesInMemory = ...;
Files.write(file, linesInMemory, Charset.forName("desired charset"), StandardOpenOption.CREATE, StandardOpenOption.APPEND, StandardOpenOption.WRITE);
If you want to write file content as you go: https://docs.oracle.com/javase/8/docs/api/java/nio/file/Files.html#newBufferedWriter-java.nio.file.Path-java.nio.charset.Charset-java.nio.file.OpenOption...-
Simplified example (Java 8 or up):
Path file = ...;
try (BufferedWriter writer = Files.newBufferedWriter(file)) {
writer.append("Zero header: ").append('0').write("\r\n");
[...]
}
Another example (append):
Path file = ...;
try (BufferedWriter writer = Files.newBufferedWriter(file, Charset.forName("desired charset"), StandardOpenOption.CREATE, StandardOpenOption.APPEND, StandardOpenOption.WRITE)) {
writer.write("----------");
[...]
}
These methods require minimal effort on the author's part and should be preferred to all others when writing to [text] files.
Since PHP 5.6, you can declare an array constant with const
:
<?php
const DEFAULT_ROLES = array('guy', 'development team');
The short syntax works too, as you'd expect:
<?php
const DEFAULT_ROLES = ['guy', 'development team'];
If you have PHP 7, you can finally use define()
, just as you had first tried:
<?php
define('DEFAULT_ROLES', array('guy', 'development team'));
I did something really stupid (and maybe you did too).
I was trying to call System.Web.Mvc.Html.Partial("<Partial Page>")
System.Web.Mvc.Html is a namespace and not a class and I didn't read my error message so well, so I interpreted my error as the class Html
does not exist in the namespace System.Web.Mvc and that's how I ended up here (stupid I know).
All I needed to do was add a using statement @using System.Web.Mvc.Html
to my page and then @Html.Partial
worked as expected.
Add a Resource File to your project (Right Click Project->Properties->Resources). Where it says "strings", you can switch to be "files". Choose "Add Resource" and select your file.
You can now reference your file through the Properties.Resources
collection.
I'd use RestSharp - https://github.com/restsharp/RestSharp
Create class to deserialize to:
public class MyObject {
public string Id { get; set; }
public string Text { get; set; }
...
}
And the code to get that object:
RestClient client = new RestClient("http://whatever.com");
RestRequest request = new RestRequest("path/to/object");
request.AddParameter("id", "123");
// The above code will make a request URL of
// "http://whatever.com/path/to/object?id=123"
// You can pick and choose what you need
var response = client.Execute<MyObject>(request);
MyObject obj = response.Data;
Check out http://restsharp.org/ to get started.
Example:
SELECT TRIM(' Sample ');
Result: 'Sample'
UPDATE TableName SET ColumnName = TRIM(ColumnName)
You want this:
AAPL:
- shares: -75.088
date: 11/27/2015
- shares: 75.088
date: 11/26/2015
The YAML equivalent of a JSON object is a mapping, which looks like these:
# flow style
{ foo: 1, bar: 2 }
# block style
foo: 1
bar: 2
Note that the first characters of the keys in a block mapping must be in the same column. To demonstrate:
# OK
foo: 1
bar: 2
# Parse error
foo: 1
bar: 2
The equivalent of a JSON array in YAML is a sequence, which looks like either of these (which are equivalent):
# flow style
[ foo bar, baz ]
# block style
- foo bar
- baz
In a block sequence the -
s must be in the same column.
Let's turn your JSON into YAML. Here's your JSON:
{"AAPL": [
{
"shares": -75.088,
"date": "11/27/2015"
},
{
"shares": 75.088,
"date": "11/26/2015"
},
]}
As a point of trivia, YAML is a superset of JSON, so the above is already valid YAML—but let's actually use YAML's features to make this prettier.
Starting from the inside out, we have objects that look like this:
{
"shares": -75.088,
"date": "11/27/2015"
}
The equivalent YAML mapping is:
shares: -75.088
date: 11/27/2015
We have two of these in an array (sequence):
- shares: -75.088
date: 11/27/2015
- shares: 75.088
date: 11/26/2015
Note how the -
s line up and the first characters of the mapping keys line up.
Finally, this sequence is itself a value in a mapping with the key AAPL
:
AAPL:
- shares: -75.088
date: 11/27/2015
- shares: 75.088
date: 11/26/2015
Parsing this and converting it back to JSON yields the expected result:
{
"AAPL": [
{
"date": "11/27/2015",
"shares": -75.088
},
{
"date": "11/26/2015",
"shares": 75.088
}
]
}
You can see it (and edit it interactively) here.
The answer is right in the MYSQL manual itself.
"DELETE FROM `table_name` WHERE `time_col` < ADDDATE(NOW(), INTERVAL -1 HOUR)"
Gutch's code is close, but it'll only work right if:
The Approved Method is to do it the other way around. Open the existing document with a PdfStamper, and use the returned PdfContentByte from getOverContent() to write text (and whatever else you might need) directly to the page. No second document needed.
And you can use a ColumnText to handle layout and such for you... no need to get down and dirty with beginText(),setFontAndSize(),drawText(),drawText()...,endText().
While this is usefull in rare cases (if that was not the case, the language would've allowed it directly), take a look at the Base from Member idiom. It's not a code free solution, you'd have to add an extra layer of inheritance, but it gets the job done. To avoid boilerplate code you could use boost's implementation
This might serve as a good starting point for moving/rotating/zooming a camera with mouse/trackpad (in typescript):
class CameraControl {
zoomMode: boolean = false
press: boolean = false
sensitivity: number = 0.02
constructor(renderer: Three.Renderer, public camera: Three.PerspectiveCamera, updateCallback:() => void){
renderer.domElement.addEventListener('mousemove', event => {
if(!this.press){ return }
if(event.button == 0){
camera.position.y -= event.movementY * this.sensitivity
camera.position.x -= event.movementX * this.sensitivity
} else if(event.button == 2){
camera.quaternion.y -= event.movementX * this.sensitivity/10
camera.quaternion.x -= event.movementY * this.sensitivity/10
}
updateCallback()
})
renderer.domElement.addEventListener('mousedown', () => { this.press = true })
renderer.domElement.addEventListener('mouseup', () => { this.press = false })
renderer.domElement.addEventListener('mouseleave', () => { this.press = false })
document.addEventListener('keydown', event => {
if(event.key == 'Shift'){
this.zoomMode = true
}
})
document.addEventListener('keyup', event => {
if(event.key == 'Shift'){
this.zoomMode = false
}
})
renderer.domElement.addEventListener('mousewheel', event => {
if(this.zoomMode){
camera.fov += event.wheelDelta * this.sensitivity
camera.updateProjectionMatrix()
} else {
camera.position.z += event.wheelDelta * this.sensitivity
}
updateCallback()
})
}
}
drop it in like:
this.cameraControl = new CameraControl(renderer, camera, () => {
// you might want to rerender on camera update if you are not rerendering all the time
window.requestAnimationFrame(() => renderer.render(scene, camera))
})
Controls:
Additionally:
If you want to kinda zoom by changing the 'distance' (along yz) instead of changing field-of-view you can bump up/down camera's position y and z while keeping the ratio of position's y and z unchanged like:
// in mousewheel event listener in zoom mode
const ratio = camera.position.y / camera.position.z
camera.position.y += (event.wheelDelta * this.sensitivity * ratio)
camera.position.z += (event.wheelDelta * this.sensitivity)
This could be as simple as a template conflict. Revert to default template in System/Configuration/Design/Themes.
To hide and show div on button click in angular 6.
Html Code
<button (click)=" isShow=!isShow">FormatCell</button>
<div class="ruleOptionsPanel" *ngIf=" isShow">
<table>
<tr>
<td>Name</td>
<td>Ram</td>
</tr>
</table>
</div>
Component .ts Code
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent{
isShow=false;
}
this works for me and it is way to replace ng-hide and ng-show in angular6.
enjoy...
Thanks
I've used ng-change:
Date.prototype.addDays = function(days) {_x000D_
var dat = new Date(this.valueOf());_x000D_
dat.setDate(dat.getDate() + days);_x000D_
return dat;_x000D_
}_x000D_
_x000D_
var app = angular.module('myApp', []);_x000D_
_x000D_
app.controller('DateController', ['$rootScope', '$scope',_x000D_
function($rootScope, $scope) {_x000D_
function init() {_x000D_
$scope.startDate = new Date();_x000D_
$scope.endDate = $scope.startDate.addDays(14);_x000D_
}_x000D_
_x000D_
_x000D_
function load() {_x000D_
alert($scope.startDate);_x000D_
alert($scope.endDate);_x000D_
}_x000D_
_x000D_
init();_x000D_
// public methods_x000D_
$scope.load = load;_x000D_
$scope.setStart = function(date) {_x000D_
$scope.startDate = date;_x000D_
};_x000D_
$scope.setEnd = function(date) {_x000D_
$scope.endDate = date;_x000D_
};_x000D_
_x000D_
}_x000D_
]);
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>_x000D_
<div data-ng-controller="DateController">_x000D_
<label class="item-input"> <span class="input-label">Start</span>_x000D_
<input type="date" data-ng-model="startDate" ng-change="setStart(startDate)" required validatedateformat calendar>_x000D_
</label>_x000D_
<label class="item-input"> <span class="input-label">End</span>_x000D_
<input type="date" data-ng-model="endDate" ng-change="setEnd(endDate)" required validatedateformat calendar>_x000D_
</label>_x000D_
<button button="button" ng-disabled="planningForm.$invalid" ng-click="load()" class="button button-positive">_x000D_
Run_x000D_
</button>_x000D_
</div <label class="item-input"> <span class="input-label">Start</span>_x000D_
<input type="date" data-ng-model="startDate" ng-change="setStart(startDate)" required validatedateformat calendar>_x000D_
</label>_x000D_
<label class="item-input"> <span class="input-label">End</span>_x000D_
<input type="date" data-ng-model="endDate" ng-change="setEnd(endDate)" required validatedateformat calendar>_x000D_
</label>
_x000D_
If whitespace becomes that important, it may be better to use preformatted text and the <pre> tag.
You got half of the answer! Now that you created the event handler, you need to hook it to the form so that it actually gets called when the form is loading. You can achieve that by doing the following:
public class ProgramViwer : Form{
public ProgramViwer()
{
InitializeComponent();
Load += new EventHandler(ProgramViwer_Load);
}
private void ProgramViwer_Load(object sender, System.EventArgs e)
{
formPanel.Controls.Clear();
formPanel.Controls.Add(wel);
}
}
-ArgumentList
is based on use with scriptblock commands, like:
Invoke-Command -Cn (gc Servers.txt) {param($Debug=$False, $Clear=$False) C:\Scripts\ArchiveEventLogs\ver5\ArchiveEventLogs.ps1 } -ArgumentList $False,$True
When you call it with a -File
it still passes the parameters like a dumb splatted array. I've submitted a feature request to have that added to the command (please vote that up).
So, you have two options:
If you have a script that looked like this, in a network location accessible from the remote machine (note that -Debug
is implied because when I use the Parameter
attribute, the script gets CmdletBinding implicitly, and thus, all of the common parameters):
param(
[Parameter(Position=0)]
$one
,
[Parameter(Position=1)]
$two
,
[Parameter()]
[Switch]$Clear
)
"The test is for '$one' and '$two' ... and we $(if($DebugPreference -ne 'SilentlyContinue'){"will"}else{"won't"}) run in debug mode, and we $(if($Clear){"will"}else{"won't"}) clear the logs after."
Without getting hung up on the meaning of $Clear
... if you wanted to invoke that you could use either of the following Invoke-Command
syntaxes:
icm -cn (gc Servers.txt) {
param($one,$two,$Debug=$False,$Clear=$False)
C:\Scripts\ArchiveEventLogs\ver5\ArchiveEventLogs.ps1 @PSBoundParameters
} -ArgumentList "uno", "dos", $false, $true
In that one, I'm duplicating ALL the parameters I care about in the scriptblock so I can pass values. If I can hard-code them (which is what I actually did), there's no need to do that and use PSBoundParameters
, I can just pass the ones I need to. In the second example below I'm going to pass the $Clear one, just to demonstrate how to pass switch parameters:
icm -cn $Env:ComputerName {
param([bool]$Clear)
C:\Scripts\ArchiveEventLogs\ver5\ArchiveEventLogs.ps1 "uno" "dos" -Debug -Clear:$Clear
} -ArgumentList $(Test-Path $Profile)
If the script is on your local machine, and you don't want to change the parameters to be positional, or you want to specify parameters that are common parameters (so you can't control them) you will want to get the content of that script and embed it in your scriptblock:
$script = [scriptblock]::create( @"
param(`$one,`$two,`$Debug=`$False,`$Clear=`$False)
&{ $(Get-Content C:\Scripts\ArchiveEventLogs\ver5\ArchiveEventLogs.ps1 -delimiter ([char]0)) } @PSBoundParameters
"@ )
Invoke-Command -Script $script -Args "uno", "dos", $false, $true
If you really need to pass in a variable for the script name, what you'd do will depend on whether the variable is defined locally or remotely. In general, if you have a variable $Script
or an environment variable $Env:Script
with the name of a script, you can execute it with the call operator (&): &$Script
or &$Env:Script
If it's an environment variable that's already defined on the remote computer, that's all there is to it. If it's a local variable, then you'll have to pass it to the remote script block:
Invoke-Command -cn $Env:ComputerName {
param([String]$Script, [bool]$Clear)
& $ScriptPath "uno" "dos" -Debug -Clear:$Clear
} -ArgumentList $ScriptPath, (Test-Path $Profile)
MyClass
and YourClass
could both be derived from SomeonesClass
which has an abstract (virtual) Callback
method. Your addHandler
would accept objects of type SomeonesClass
and MyClass
and YourClass
can override Callback
to provide their specific implementation of callback behavior.
There are a number of "is methods" on strings. islower()
and isupper()
should meet your needs:
>>> 'hello'.islower()
True
>>> [m for m in dir(str) if m.startswith('is')]
['isalnum', 'isalpha', 'isdigit', 'islower', 'isspace', 'istitle', 'isupper']
Here's an example of how to use those methods to classify a list of strings:
>>> words = ['The', 'quick', 'BROWN', 'Fox', 'jumped', 'OVER', 'the', 'Lazy', 'DOG']
>>> [word for word in words if word.islower()]
['quick', 'jumped', 'the']
>>> [word for word in words if word.isupper()]
['BROWN', 'OVER', 'DOG']
>>> [word for word in words if not word.islower() and not word.isupper()]
['The', 'Fox', 'Lazy']
Function pointers can be passed as template parameters, and this is part of standard C++ . However in the template they are declared and used as functions rather than pointer-to-function. At template instantiation one passes the address of the function rather than just the name.
For example:
int i;
void add1(int& i) { i += 1; }
template<void op(int&)>
void do_op_fn_ptr_tpl(int& i) { op(i); }
i = 0;
do_op_fn_ptr_tpl<&add1>(i);
If you want to pass a functor type as a template argument:
struct add2_t {
void operator()(int& i) { i += 2; }
};
template<typename op>
void do_op_fntr_tpl(int& i) {
op o;
o(i);
}
i = 0;
do_op_fntr_tpl<add2_t>(i);
Several answers pass a functor instance as an argument:
template<typename op>
void do_op_fntr_arg(int& i, op o) { o(i); }
i = 0;
add2_t add2;
// This has the advantage of looking identical whether
// you pass a functor or a free function:
do_op_fntr_arg(i, add1);
do_op_fntr_arg(i, add2);
The closest you can get to this uniform appearance with a template argument is to define do_op
twice- once with a non-type parameter and once with a type parameter.
// non-type (function pointer) template parameter
template<void op(int&)>
void do_op(int& i) { op(i); }
// type (functor class) template parameter
template<typename op>
void do_op(int& i) {
op o;
o(i);
}
i = 0;
do_op<&add1>(i); // still need address-of operator in the function pointer case.
do_op<add2_t>(i);
Honestly, I really expected this not to compile, but it worked for me with gcc-4.8 and Visual Studio 2013.
#Server Connection to MySQL:
import MySQLdb
conn = MySQLdb.connect(host= "localhost",
user="root",
passwd="newpassword",
db="engy1")
x = conn.cursor()
try:
x.execute("""INSERT INTO anooog1 VALUES (%s,%s)""",(188,90))
conn.commit()
except:
conn.rollback()
conn.close()
edit working for me:
>>> import MySQLdb
>>> #connect to db
... db = MySQLdb.connect("localhost","root","password","testdb" )
>>>
>>> #setup cursor
... cursor = db.cursor()
>>>
>>> #create anooog1 table
... cursor.execute("DROP TABLE IF EXISTS anooog1")
__main__:2: Warning: Unknown table 'anooog1'
0L
>>>
>>> sql = """CREATE TABLE anooog1 (
... COL1 INT,
... COL2 INT )"""
>>> cursor.execute(sql)
0L
>>>
>>> #insert to table
... try:
... cursor.execute("""INSERT INTO anooog1 VALUES (%s,%s)""",(188,90))
... db.commit()
... except:
... db.rollback()
...
1L
>>> #show table
... cursor.execute("""SELECT * FROM anooog1;""")
1L
>>> print cursor.fetchall()
((188L, 90L),)
>>>
>>> db.close()
table in mysql;
mysql> use testdb;
Reading table information for completion of table and column names
You can turn off this feature to get a quicker startup with -A
Database changed
mysql> SELECT * FROM anooog1;
+------+------+
| COL1 | COL2 |
+------+------+
| 188 | 90 |
+------+------+
1 row in set (0.00 sec)
mysql>
STRING=(one two three four)
echo "${STRING[n]}"
In the MongoDB Client, type:
db.Collection.updateMany({}, $set: {field1: 'field1', field2: 'field2'})
New in version 3.2
Params::
{}: select all records updated
Keyword argument multi
not taken
Solution
Use this code
jQuery.nl2br = function(varTest){
return varTest.replace(/(\r\n|\n\r|\r|\n)/g, "<br>");
};
I fixed this issue. As I'm using UpdatePanel
, I added below code in the Page_Load
event of the page and it worked for me:
protected void Page_Load(object sender, EventArgs e) {
ScriptManager scriptManager = ScriptManager.GetCurrent(this.Page);
scriptManager.RegisterPostBackControl(this.btnExcelExport);
//Further code goes here....
}
Set Jquery in scope
$scope.$ = $;
and call in html
ng-click="$('#novoModelo').modal('show')"
In the context definition, define only two DbSet contexts per context class.
You can create a extension function as :
public static List<T> ToListof<T>(this DataTable dt)
{
const BindingFlags flags = BindingFlags.Public | BindingFlags.Instance;
var columnNames = dt.Columns.Cast<DataColumn>()
.Select(c => c.ColumnName)
.ToList();
var objectProperties = typeof(T).GetProperties(flags);
var targetList = dt.AsEnumerable().Select(dataRow =>
{
var instanceOfT = Activator.CreateInstance<T>();
foreach (var properties in objectProperties.Where(properties => columnNames.Contains(properties.Name) && dataRow[properties.Name] != DBNull.Value))
{
properties.SetValue(instanceOfT, dataRow[properties.Name], null);
}
return instanceOfT;
}).ToList();
return targetList;
}
var output = yourDataInstance.ToListof<targetModelType>();
You should call the element's native .click()
method or use the createEvent
API.
For more info, please visit: https://learn.jquery.com/events/triggering-event-handlers/