My issue was that eclipse could not find the mvn.bat file within the installation directory. The solution is to create a mvn.bat file with the following code:
"%~dp0\mvn.cmd" %*
Save that file. Place it inside the [Maven Installation Folder]\bin directory.
<button onclick="window.open('http://www.google.com');">Open popup</button>
with jQuery:
$("#playerSource").attr("src", "new_src");
var audio = $("#player");
audio[0].pause();
audio[0].load();//suspends and restores all audio element
if (isAutoplay)
audio[0].play();
Solution : SpreadsheetApp.getActiveSheet().getRange('F2').setValue('hello')
Explanation :
Setting value in a cell in spreadsheet to which script is attached
SpreadsheetApp.getActiveSpreadsheet().getSheetByName(SHEET_NAME).getRange(RANGE).setValue(VALUE);
Setting value in a cell in sheet which is open currently and to which script is attached
SpreadsheetApp.getActiveSpreadsheet().getActiveSheet().getRange(RANGE).setValue(VALUE);
Setting value in a cell in some spreadsheet to which script is NOT attached (Destination sheet name known)
SpreadsheetApp.openById(SHEET_ID).getSheetByName(SHEET_NAME).getRange(RANGE).setValue(VALUE);
Setting value in a cell in some spreadsheet to which script is NOT attached (Destination sheet position known)
SpreadsheetApp.openById(SHEET_ID).getSheets()[POSITION].getRange(RANGE).setValue(VALUE);
These are constants, you must define them yourself
SHEET_ID
SHEET_NAME
POSITION
VALUE
RANGE
By script attached to a sheet I mean that script is residing in the script editor of that sheet. Not attached means not residing in the script editor of that sheet. It can be in any other place.
Here's another way to work around the problem:
std::min(9, int(test::N));
(I think Crazy Eddie's answer correctly describes why the problem exists.)
You need a Flask view that will receive POST data and an HTML form that will send it.
from flask import request
@app.route('/addRegion', methods=['POST'])
def addRegion():
...
return (request.form['projectFilePath'])
<form action="{{ url_for('addRegion') }}" method="post">
Project file path: <input type="text" name="projectFilePath"><br>
<input type="submit" value="Submit">
</form>
Recent versions of VSCode (e.g., Version 1.29 at the time of posting this answer) allow you to change the Tab/Space size to 1
(or any number between 1
and 8
). You may change the Tab/Space size from the bottom-right corner as shown in the below image:
Click on Spaces:4
. Then, select Indent Using Spaces or Indent Using Tabs and choose the size 1.
Hope it helps.
Here is a solution with an stdout redirection:
def elevate():
import ctypes, win32com.shell.shell, win32event, win32process
outpath = r'%s\%s.out' % (os.environ["TEMP"], os.path.basename(__file__))
if ctypes.windll.shell32.IsUserAnAdmin():
if os.path.isfile(outpath):
sys.stderr = sys.stdout = open(outpath, 'w', 0)
return
with open(outpath, 'w+', 0) as outfile:
hProc = win32com.shell.shell.ShellExecuteEx(lpFile=sys.executable, \
lpVerb='runas', lpParameters=' '.join(sys.argv), fMask=64, nShow=0)['hProcess']
while True:
hr = win32event.WaitForSingleObject(hProc, 40)
while True:
line = outfile.readline()
if not line: break
sys.stdout.write(line)
if hr != 0x102: break
os.remove(outpath)
sys.stderr = ''
sys.exit(win32process.GetExitCodeProcess(hProc))
if __name__ == '__main__':
elevate()
main()
This will append all form fields to the JavaScript object "res":
var res = {};
$("#form input, #form select, #form textarea").each(function(i, obj) {
res[obj.name] = $(obj).val();
})
Something like this could work...
mydf.loc['newindex'] = myseries
Here is an example where I used it...
stats = df[['bp_prob', 'ICD9_prob', 'meds_prob', 'regex_prob']].describe()
stats
Out[32]:
bp_prob ICD9_prob meds_prob regex_prob
count 171.000000 171.000000 171.000000 171.000000
mean 0.179946 0.059071 0.067020 0.126812
std 0.271546 0.142681 0.152560 0.207014
min 0.000000 0.000000 0.000000 0.000000
25% 0.000000 0.000000 0.000000 0.000000
50% 0.000000 0.000000 0.000000 0.013116
75% 0.309019 0.065248 0.066667 0.192954
max 1.000000 1.000000 1.000000 1.000000
medians = df[['bp_prob', 'ICD9_prob', 'meds_prob', 'regex_prob']].median()
stats.loc['median'] = medians
stats
Out[36]:
bp_prob ICD9_prob meds_prob regex_prob
count 171.000000 171.000000 171.000000 171.000000
mean 0.179946 0.059071 0.067020 0.126812
std 0.271546 0.142681 0.152560 0.207014
min 0.000000 0.000000 0.000000 0.000000
25% 0.000000 0.000000 0.000000 0.000000
50% 0.000000 0.000000 0.000000 0.013116
75% 0.309019 0.065248 0.066667 0.192954
max 1.000000 1.000000 1.000000 1.000000
median 0.000000 0.000000 0.000000 0.013116
I disable my Instant Run by:
Menu Preference ? Build ? Instant Run "Enable Instant Run to hot swap code"
I guess it is the Instant Run that makes the build slow and creates a large size pidXXX.hprof file which causes the AndroidStudio gc overhead limit exceeded.
(My device SDK is 19.)
use menu Project -> Build Settings ->
then remove armv7s from the"valid architectures". If standard has been chosen then delete that and then add armv7.
html {
position:relative;
top:0px;
left:0px;
overflow:auto;
height:auto
}
add this as default to your css
.class-on-html{
position:fixed;
top:0px;
left:0px;
overflow:hidden;
height:100%;
}
toggleClass this class to to cut page
when you turn off this class first line will call scrolling bar back
I know that two threads can not enter in Synchronize block at the same time
Two thread cannot enter a synchronized block on the same object twice. This means that two threads can enter the same block on different objects. This confusion can lead to code like this.
private Integer i = 0;
synchronized(i) {
i++;
}
This will not behave as expected as it could be locking on a different object each time.
if this is true than How this atomic.incrementAndGet() works without Synchronize ?? and is thread safe ??
yes. It doesn't use locking to achieve thread safety.
If you want to know how they work in more detail, you can read the code for them.
And what is difference between internal reading and writing to Volatile Variable / Atomic Variable ??
Atomic class uses volatile fields. There is no difference in the field. The difference is the operations performed. The Atomic classes use CompareAndSwap or CAS operations.
i read in some article that thread has local copy of variables what is that ??
I can only assume that it referring to the fact that each CPU has its own cached view of memory which can be different from every other CPU. To ensure that your CPU has a consistent view of data, you need to use thread safety techniques.
This is only an issue when memory is shared at least one thread updates it.
I made:
git checkout -- ../.DS_Store
(# Discarding local changes (permanently) to a file) And it worked ok!
Try this
$('.yourchkboxes').change(function(){
$('.yourbutton').toggle($('.yourchkboxes:checked').length > 0);
});
So it will check for at least one checkbox is checked or not.
I had this same problem and it occurred because I had hit the enter key when adding code in a text string.
Because it was a long string of text I wanted to see it all without having to scroll in my text editor, however hitting enter added an invisible character to the string which was illegal. I was using Sublime Text as my editor.
Here you go.
SELECT
[so].[name] AS [trigger_name],
USER_NAME([so].[uid]) AS [trigger_owner],
USER_NAME([so2].[uid]) AS [table_schema],
OBJECT_NAME([so].[parent_obj]) AS [table_name],
OBJECTPROPERTY( [so].[id], 'ExecIsUpdateTrigger') AS [isupdate],
OBJECTPROPERTY( [so].[id], 'ExecIsDeleteTrigger') AS [isdelete],
OBJECTPROPERTY( [so].[id], 'ExecIsInsertTrigger') AS [isinsert],
OBJECTPROPERTY( [so].[id], 'ExecIsAfterTrigger') AS [isafter],
OBJECTPROPERTY( [so].[id], 'ExecIsInsteadOfTrigger') AS [isinsteadof],
OBJECTPROPERTY([so].[id], 'ExecIsTriggerDisabled') AS [disabled]
FROM sysobjects AS [so]
INNER JOIN sysobjects AS so2 ON so.parent_obj = so2.Id
WHERE [so].[type] = 'TR'
A couple of things here...
Also I see that you were attempting to pull the parent tables schema information, I believe in order to do so you would also need to join the sysobjects table on itself so that you can correctly get the schema information for the parent table. the query above does this. Also the sysusers table wasn't needed in the results so that Join has been removed.
tested with SQL 2000, SQL 2005, and SQL 2008 R2
By default, Makefile targets are "file targets" - they are used to build files from other files. Make assumes its target is a file, and this makes writing Makefiles relatively easy:
foo: bar
create_one_from_the_other foo bar
However, sometimes you want your Makefile to run commands that do not represent physical files in the file system. Good examples for this are the common targets "clean" and "all". Chances are this isn't the case, but you may potentially have a file named clean
in your main directory. In such a case Make will be confused because by default the clean
target would be associated with this file and Make will only run it when the file doesn't appear to be up-to-date with regards to its dependencies.
These special targets are called phony and you can explicitly tell Make they're not associated with files, e.g.:
.PHONY: clean
clean:
rm -rf *.o
Now make clean
will run as expected even if you do have a file named clean
.
In terms of Make, a phony target is simply a target that is always out-of-date, so whenever you ask make <phony_target>
, it will run, independent from the state of the file system. Some common make
targets that are often phony are: all
, install
, clean
, distclean
, TAGS
, info
, check
.
Download https://github.com/douglascrockford/JSON-js/blob/master/json2.js
, include it and do
var json_data = JSON.stringify(obj);
In addition to erickson's suggestions, there's also jna, which allows you to call native libraries without using jni. It's shockingly easy to use, and I've used it on a couple of projects with great success.
The only caveat is that it's slower than jni, so if you're doing this to a very large number of files that might be an issue for you.
(Editing to add example)
Here's a complete jna chmod example:
import com.sun.jna.Library;
import com.sun.jna.Native;
public class Main {
private static CLibrary libc = (CLibrary) Native.loadLibrary("c", CLibrary.class);
public static void main(String[] args) {
libc.chmod("/path/to/file", 0755);
}
}
interface CLibrary extends Library {
public int chmod(String path, int mode);
}
Assuming that this is about OAuth 2.0 since it is about JWTs and refresh tokens...:
just like an access token, in principle a refresh token can be anything including all of the options you describe; a JWT could be used when the Authorization Server wants to be stateless or wants to enforce some sort of "proof-of-possession" semantics on to the client presenting it; note that a refresh token differs from an access token in that it is not presented to a Resource Server but only to the Authorization Server that issued it in the first place, so the self-contained validation optimization for JWTs-as-access-tokens does not hold for refresh tokens
that depends on the security/access of the database; if the database can be accessed by other parties/servers/applications/users, then yes (but your mileage may vary with where and how you store the encryption key...)
an Authorization Server may issue both access tokens and refresh tokens at the same time, depending on the grant that is used by the client to obtain them; the spec contains the details and options on each of the standardized grants
tabindex
is a global attribute responsible for two things:
In my mind the second thing is even more important than the first one. There are very few elements that are focusable by default (e.g. <a> and form controls). Developers very often add some JavaScript event handlers (like 'onclick') on not focusable elements (<div>, <span> and so on), and the way to make your interface be responsive not only to mouse events but also to keyboard events (e.g. 'onkeypress') is to make such elements focusable. Lastly, if you don't want to set the order but just make your element focusable use tabindex="0"
on all such elements:
<div tabindex="0"></div>
Also, if you don't want it to be focusable via the tab key then use tabindex="-1"
. For example, the below link will not be focused while using tab keys to traverse.
<a href="#" tabindex="-1">Tab key cannot reach here!</a>
What's your problem with Tx logs? They grow? Then just set truncate on checkpoint option.
From Microsoft documentation:
In SQL Server 2000 or in SQL Server 2005, the "Simple" recovery model is equivalent to "truncate log on checkpoint" in earlier versions of SQL Server. If the transaction log is truncated every time a checkpoint is performed on the server, this prevents you from using the log for database recovery. You can only use full database backups to restore your data. Backups of the transaction log are disabled when the "Simple" recovery model is used.
Define a class to store your data first
public class YourDataClass {
private String messageType;
private Timestamp timestamp;
private int count;
private int version;
// your get/setters
...........
}
And then initialize your map:
Map<Integer, YourDataClass> map = new HashMap<Integer, YourDataClass>();
When you create an implicit intent, the Android system finds the appropriate component to start by comparing the contents of the intent to the intent filters declared in the manifest file of other apps on the device. If the intent matches an intent filter, the system starts that component and delivers it the Intent object. If multiple intent filters are compatible, the system displays a dialog so the user can pick which app to use.
An intent filter is an expression in an app's manifest file that specifies the type of intents that the component would like to receive. For instance, by declaring an intent filter for an activity, you make it possible for other apps to directly start your activity with a certain kind of intent. Likewise, if you do not declare any intent filters for an activity, then it can be started only with an explicit intent.
According: Intents and Intent Filters
When it comes to inserting a picture, r2evans's suggestion of ![Caption for the picture.](/path/to/image.png)
can be problematic if PDF output is required.
The knitr function include_graphics
knitr::include_graphics('/path/to/image.png')
is a more portable alternative
that will generate, on your behalf, the markdown that is most appropriate to the output format that you are generating.
Because of the infinite superiority of Python over Java, Python has not one, but two toString operations.
One is __str__
, the other is __repr__
__str__
will return a human readable string.
__repr__
will return an internal representation.
__repr__
can be invoked on an object by calling repr(obj)
or by using backticks `obj`
.
When printing lists as well as other container classes, the contained elements will be printed using __repr__
.
One option is that you could use system()
to execute cp
. This just re-uses the cp(1)
command to do the work. If you only need to make another link to the file, this can be done with link()
or symlink()
.
You could also use strdup
:
The strdup() function returns a pointer to a new string which is a duplicate of the string s.
Memory for the new string is obtained with malloc(3), and can be freed with free(3).
For you example:
char *a = strdup("stack overflow");
I'm using the Facebook Canvas platform (Unity WebGL) and I don't needed to add the Website platform. The only thing I did was add my website root url in:
Yes. Hit Ctrl-R then ". If you have literal control characters in what you have yanked, use Ctrl-R, Ctrl-O, ".
Here is an explanation of what you can do with registers. What you can do with registers is extraordinary, and once you know how to use them you cannot live without them.
Registers are basically storage locations for strings. Vim has many registers that work in different ways:
0
(yank register: when you use y
in normal mode, without specifying a register, yanked text goes there and also to the default register),1
to 9
(shifting delete registers, when you use commands such as c
or d
, what has been deleted goes to register 1, what was in register 1 goes to register 2, etc.),"
(default register, also known as unnamed register. This is where the " comes in Ctrl-R, "),a
to z
for your own use (capitalized A
to Z
are for appending to corresponding registers)._
(acts like /dev/null
(Unix) or NUL
(Windows), you can write to it but it's discarded and when you read from it, it is always empty),-
(small delete register),/
(search pattern register, updated when you look for text with /
, ?
, *
or #
for instance; you can also write to it to dynamically change the search pattern),:
(stores last VimL typed command via Q
or :
, readonly),+
and *
(system clipboard registers, you can write to them to set the clipboard and read the clipboard contents from them)See :help registers
for the full reference.
You can, at any moment, use :registers
to display the contents of all registers. Synonyms and shorthands for this command are :display
, :reg
and :di
.
In Insert or Command-line mode, Ctrl-R plus a register name, inserts the contents of this register. If you want to insert them literally (no auto-indenting, no conversion of control characters like 0x08
to backspace, etc), you can use Ctrl-R, Ctrl-O, register name.
See :help i_CTRL-R
and following paragraphs for more reference.
But you can also do the following (and I probably forgot many uses for registers).
In normal mode, hit ":p. The last command you used in vim is pasted into your buffer.
Let's decompose: "
is a Normal mode command that lets you select what register is to be used during the next yank, delete or paste operation. So ": selects the colon register (storing last command). Then p is a command you already know, it pastes the contents of the register.
cf. :help "
, :help quote_:
You're editing a VimL file (for instance your .vimrc
) and would like to execute a couple of consecutive lines right now: yj:@"Enter.
Here, yj yanks current and next line (this is because j is a linewise motion but this is out of scope of this answer) into the default register (also known as the unnamed register). Then the :@
Ex command plays Ex commands stored in the register given as argument, and "
is how you refer to the unnamed register. Also see the top of this answer, which is related.
Do not confuse "
used here (which is a register name) with the "
from the previous example, which was a Normal-mode command.
cf. :help :@
and :help quote_quote
Insert the last search pattern into your file in Insert mode, or into the command line, with Ctrl-R, /.
cf. :help quote_/
, help i_CTRL-R
Corollary: Keep your search pattern but add an alternative: /
Ctrl-R, / \|alternative
.
You've selected two words in the middle of a line in visual mode, yanked them with y
, they are in the unnamed register. Now you want to open a new line just below where you are, with those two words: :pu
. This is shorthand for :put "
. The :put
command, like many Ex commands, works only linewise.
cf. :help :put
You could also have done: :call setreg('"', @", 'V')
then p
. The setreg
function sets the register of which the name is given as first argument (as a string), initializes it with the contents of the second argument (and you can use registers as variables with the name @x
where x
is the register name in VimL), and turns it into the mode specified in the third argument, V
for linewise, nothing for characterwise and literal ^V
for blockwise.
cf. :help setreg()
. The reverse functions are getreg()
and getregtype()
.
If you have recorded a macro with qa
...q
, then :echo @a
will tell you what you have typed, and @a
will replay the macro (probably you knew that one, very useful in order to avoid repetitive tasks)
cf. :help q
, help @
Corollary from the previous example: If you have 8go
in the clipboard, then @+
will play the clipboard contents as a macro, and thus go to the 8th byte of your file. Actually this will work with almost every register. If your last inserted string was dd
in Insert mode, then @.
will (because the .
register contains the last inserted string) delete a line. (Vim documentation is wrong in this regard, since it states that the registers #
, %
, :
and .
will only work with p
, P
, :put
and Ctrl-R).
cf. :help @
Don't confuse :@
(command that plays Vim commands from a register) and @
(normal-mode command that plays normal-mode commands from a register).
Notable exception is @:
. The command register does not contain the initial colon neither does it contain the final carriage return. However in Normal mode, @:
will do what you expect, interpreting the register as an Ex command, not trying to play it in Normal mode. So if your last command was :e
, the register contains e
but @:
will reload the file, not go to end of word.
cf. :help @:
Show what you will be doing in Normal mode before running it: @='dd'
Enter. As soon as you hit the =
key, Vim switches to expression evaluation: as you enter an expression and hit Enter, Vim computes it, and the result acts as a register content. Of course the register =
is read-only, and one-shot. Each time you start using it, you will have to enter a new expression.
cf. :help quote_=
Corollary: If you are editing a command, and you realize that you should need to insert into your command line some line from your current buffer: don't press Esc! Use Ctrl-R =getline(58)
Enter. After that you will be back to command line editing, but it has inserted the contents of the 58th line.
Define a search pattern manually: :let @/ = 'foo'
cf. :help :let
Note that doing that, you needn't to escape /
in the pattern. However you need to double all single quotes of course.
Copy all lines beginning with foo
, and afterwards all lines containing bar
to clipboard, chain these commands: qaq
(resets the a register storing an empty macro inside it), :g/^foo/y A
, :g/bar/y A
, :let @+ = @a
.
Using a capital register name makes the register work in append mode
Better, if Q
has not been remapped by mswin.vim
, start Ex mode with Q
, chain those “colon commands” which are actually better called “Ex commands”, and go back to Normal mode by typing visual
.
cf. :help :g
, :help :y
, :help Q
Double-space your file: :g/^/put _
. This puts the contents of the black hole register (empty when reading, but writable, behaving like /dev/null
) linewise, after each line (because every line has a beginning!).
Add a line containing foo
before each line: :g/^/-put ='foo'
. This is a clever use of the expression register. Here, -
is a synonym for .-1
(cf. :help :range
). Since :put
puts the text after the line, you have to explicitly tell it to act on the previous one.
Copy the entire buffer to the system clipboard: :%y+
.
cf. :help :range
(for the %
part) and :help :y
.
If you have misrecorded a macro, you can type :let @a='
Ctrl-R =replace(@a,"'","''",'g')
Enter '
and edit it. This will modify the contents of the macro stored in register a
, and it's shown here how you can use the expression register to do that.
If you did dddd
, you might do uu
in order to undo. With p
you could get the last deleted line. But actually you can also recover up to 9 deletes with the registers @1
through @9
.
Even better, if you do "1P
, then .
in Normal mode will play "2P
, and so on.
cf. :help .
and :help quote_number
If you want to insert the current date in Insert mode: Ctrl-R=strftime('%y%m%d')
Enter.
cf. :help strftime()
Once again, what can be confusing:
:@
is a command-line command that interprets the contents of a register as vimscript and sources it@
in normal mode command that interprets the contents of a register as normal-mode keystrokes (except when you use :
register, that contains last played command without the initial colon: in this case it replays the command as if you also re-typed the colon and the final return key).
"
in normal mode command that helps you select a register for yank, paste, delete, correct, etc.
"
is also a valid register name (the default, or unnamed, register) and therefore can be passed as an arguments for commands that expect register namesYou can try the command
net use \\computername\ipc$ /user:adminname password
to get admin permissions on remote PC before use psexec.
public boolean isAlertPresent() {
try
{
driver.switchTo().alert();
system.out.println(" Alert Present");
}
catch (NoAlertPresentException e)
{
system.out.println("No Alert Present");
}
}
If you wanna call a js function in your html page use onload event. The onload event occurs when the user agent finishes loading a window or all frames within a FRAMESET. This attribute may be used with BODY and FRAMESET elements.
<body onload="callFunction();">
....
</body>
This exact question is answered on mySql workbench-faq:
Hover over an acronym to view a description, and see the Section 8.1.11.2, “The Columns Tab” and MySQL CREATE TABLE documentation for additional details.
That means hover over an acronym in the mySql Workbench table editor.
I wrote a simple script that test the speed and this is what I found out. Actually for loop was fastest in my case. That really suprised me, check out bellow (was calculating sum of squares).
from functools import reduce
import datetime
def time_it(func, numbers, *args):
start_t = datetime.datetime.now()
for i in range(numbers):
func(args[0])
print (datetime.datetime.now()-start_t)
def square_sum1(numbers):
return reduce(lambda sum, next: sum+next**2, numbers, 0)
def square_sum2(numbers):
a = 0
for i in numbers:
i = i**2
a += i
return a
def square_sum3(numbers):
sqrt = lambda x: x**2
return sum(map(sqrt, numbers))
def square_sum4(numbers):
return(sum([int(i)**2 for i in numbers]))
time_it(square_sum1, 100000, [1, 2, 5, 3, 1, 2, 5, 3])
time_it(square_sum2, 100000, [1, 2, 5, 3, 1, 2, 5, 3])
time_it(square_sum3, 100000, [1, 2, 5, 3, 1, 2, 5, 3])
time_it(square_sum4, 100000, [1, 2, 5, 3, 1, 2, 5, 3])
0:00:00.302000 #Reduce
0:00:00.144000 #For loop
0:00:00.318000 #Map
0:00:00.390000 #List comprehension
I posted what I use to solve this very issue efficiently here using a quick Binary Search Algorithm: https://stackoverflow.com/a/52786742/1678210
I didn't want to copy the same answer. Someone else had asked it slightly differently but the answer is the same.
Good practice nowadays is to use CollectionUtils from either Apache Commons or Spring Framework.
CollectionUtils.isEmpty(list))
To put it on one line:
currentLoad = IIf(IsNumeric(oXLSheet2.Cells(4, 6).Value), CInt(oXLSheet2.Cells(4, 6).Value), 0)
This works for me under Specific Page for MVC:
/Home/Index
Update: Currently, I just use a forward slash in the "Specific Page" textbox, and it takes me to the home page as defined in the routing:
/
Standard Python dictionaries are inherently unordered, so what you're asking to do doesn't really make sense.
If you really, really know what you're doing, use
value_at_index = dic.values()[index]
Bear in mind that adding or removing an element can potentially change the index of every other element.
From FormData documention:
XMLHttpRequest Level 2 adds support for the new FormData interface. FormData objects provide a way to easily construct a set of key/value pairs representing form fields and their values, which can then be easily sent using the
XMLHttpRequest
send()
method.
With an XMLHttpRequest
you can set the custom headers and then do the POST
.
if the project is not a big ,
1- change the name of folder project
2- make a new project with the same project (before renaming)
3- add existing files from the old project to the new project (totally same , same folders , same names , ...)
4- open the the new project file (as xml ) and the old project
5- copy the new project file (xml content ) and paste it in the old project file
6- delete the old project
7- rename the old folder project to old name
Try this :
`CREATE TABLE new-table (id INT(11) auto_increment primary key) SELECT old-table.name, old-table.group, old-table.floor, old-table.age from old-table;`
I selected 4 columns from old-table and made a new table.
I can recommend make pre-init of future index value, this is very usefull in a lot of case like multi work, some export e.t.c.
just create additional User_Seq
table:
with two fields: id Uniq index
and SeqVal nvarchar(1)
and create next SP, and generated ID value from this SP and put to new User row!
CREATE procedure [dbo].[User_NextValue]
as
begin
set NOCOUNT ON
declare @existingId int = (select isnull(max(UserId)+1, 0) from dbo.User)
insert into User_Seq (SeqVal) values ('a')
declare @NewSeqValue int = scope_identity()
if @existingId > @NewSeqValue
begin
set identity_insert User_Seq on
insert into User_Seq (SeqID) values (@existingId)
set @NewSeqValue = scope_identity()
end
delete from User_Seq WITH (READPAST)
return @NewSeqValue
end
What I did is first check what are the running processes by
SELECT * FROM pg_stat_activity WHERE state = 'active';
Find the process you want to kill, then type:
SELECT pg_cancel_backend(<pid of the process>)
This basically "starts" a request to terminate gracefully, which may be satisfied after some time, though the query comes back immediately.
If the process cannot be killed, try:
SELECT pg_terminate_backend(<pid of the process>)
I had the same issue, and spent quite a bit of time trying to track down the solution. I had Anonymous Authentication set up at two different levels with two different users. Make sure that you're not overwriting your set up at a lower level.
For Python 3, I'm using this function:
def user_prompt(question: str) -> bool:
""" Prompt the yes/no-*question* to the user. """
from distutils.util import strtobool
while True:
user_input = input(question + " [y/n]: ")
try:
return bool(strtobool(user_input))
except ValueError:
print("Please use y/n or yes/no.\n")
The strtobool()
function converts a string into a bool. If the string cant be parsed it will raise a ValueError.
In Python 3 raw_input()
has been renamed to input()
.
As Geoff said, strtobool actually returns 0 or 1, therefore the result has to be cast to bool.
This is the implementation of strtobool
, if you want special words to be recognized as true
, you can copy the code and add your own cases.
def strtobool (val):
"""Convert a string representation of truth to true (1) or false (0).
True values are 'y', 'yes', 't', 'true', 'on', and '1'; false values
are 'n', 'no', 'f', 'false', 'off', and '0'. Raises ValueError if
'val' is anything else.
"""
val = val.lower()
if val in ('y', 'yes', 't', 'true', 'on', '1'):
return 1
elif val in ('n', 'no', 'f', 'false', 'off', '0'):
return 0
else:
raise ValueError("invalid truth value %r" % (val,))
This essentially requires a range
function. A Django feature ticket was raised (https://code.djangoproject.com/ticket/13088) for this but closed as "won't fix" with the following comment.
My impression of this idea is that it is trying to lead to programming in the template. If you have a list of options that need to be rendered, they should be computed in the view, not in the template. If that's as simple as a range of values, then so be it.
They have a good point - Templates are supposed to be very simple representations of the view. You should create the limited required data in the view and pass to the template in the context.
clsx makes this simple!
"The clsx function can take any number of arguments, each of which can be an Object, Array, Boolean, or String."
-- clsx docs on npmjs.com
Import it:
import clsx from 'clsx'
Use it:
<li key={index} className={clsx(activeClass, data.class, "main-class")}></li>
You can use 9 patch in Android Studio to make borders!
I was looking for a solution but I did not find any so I skipped that part.
Then I went to the Google images of Firebase assets and I accidentally discovered that they use 9patch.
Here's the link: https://developer.android.com/studio/write/draw9patch
You just need to drag where the edges are.
It's just like border edge in Unity.
Typescript: following should work,
export const getTimeBetweenDates = ({
until,
format
}: {
until: number;
format: 'seconds' | 'minutes' | 'hours' | 'days';
}): number => {
const date = new Date();
const remainingTime = new Date(until * 1000);
const getFrom = moment([date.getUTCFullYear(), date.getUTCMonth(), date.getUTCDate()]);
const getUntil = moment([remainingTime.getUTCFullYear(), remainingTime.getUTCMonth(), remainingTime.getUTCDate()]);
const diff = getUntil.diff(getFrom, format);
return !isNaN(diff) ? diff : null;
};
You can try jQuery treegrid (http://maxazan.github.io/jquery-treegrid/) or jQuery treetable (http://ludo.cubicphuse.nl/jquery-treetable/)
Both are using HTML <table>
tag format and styled the as tree.
The jQuery treetable is using data-tt-id
and data-tt-parent-id
for determining the parent and child of the tree. Usage example:
<table id="tree">
<tr data-tt-id="1">
<td>Parent</td>
</tr>
<tr data-tt-id="2" data-tt-parent-id="1">
<td>Child</td>
</tr>
</table>
$("#tree").treetable({ expandable: true });
Meanwhile, jQuery treegrid is using only class for styling the tree. Usage example:
<table class="tree">
<tr class="treegrid-1">
<td>Root node</td><td>Additional info</td>
</tr>
<tr class="treegrid-2 treegrid-parent-1">
<td>Node 1-1</td><td>Additional info</td>
</tr>
<tr class="treegrid-3 treegrid-parent-1">
<td>Node 1-2</td><td>Additional info</td>
</tr>
<tr class="treegrid-4 treegrid-parent-3">
<td>Node 1-2-1</td><td>Additional info</td>
</tr>
</table>
<script type="text/javascript">
$('.tree').treegrid();
</script>
From IEEE floating-point exceptions in C++ :
This page will answer the following questions.
- My program just printed out 1.#IND or 1.#INF (on Windows) or nan or inf (on Linux). What happened?
- How can I tell if a number is really a number and not a NaN or an infinity?
- How can I find out more details at runtime about kinds of NaNs and infinities?
- Do you have any sample code to show how this works?
- Where can I learn more?
These questions have to do with floating point exceptions. If you get some strange non-numeric output where you're expecting a number, you've either exceeded the finite limits of floating point arithmetic or you've asked for some result that is undefined. To keep things simple, I'll stick to working with the double floating point type. Similar remarks hold for float types.
Debugging 1.#IND, 1.#INF, nan, and inf
If your operation would generate a larger positive number than could be stored in a double, the operation will return 1.#INF on Windows or inf on Linux. Similarly your code will return -1.#INF or -inf if the result would be a negative number too large to store in a double. Dividing a positive number by zero produces a positive infinity and dividing a negative number by zero produces a negative infinity. Example code at the end of this page will demonstrate some operations that produce infinities.
Some operations don't make mathematical sense, such as taking the square root of a negative number. (Yes, this operation makes sense in the context of complex numbers, but a double represents a real number and so there is no double to represent the result.) The same is true for logarithms of negative numbers. Both sqrt(-1.0) and log(-1.0) would return a NaN, the generic term for a "number" that is "not a number". Windows displays a NaN as -1.#IND ("IND" for "indeterminate") while Linux displays nan. Other operations that would return a NaN include 0/0, 0*8, and 8/8. See the sample code below for examples.
In short, if you get 1.#INF or inf, look for overflow or division by zero. If you get 1.#IND or nan, look for illegal operations. Maybe you simply have a bug. If it's more subtle and you have something that is difficult to compute, see Avoiding Overflow, Underflow, and Loss of Precision. That article gives tricks for computing results that have intermediate steps overflow if computed directly.
another language meta tag is og:locale and you can define og:locale meta tag for social media
<meta property="og:locale" content="en" />
I typically use function attributes as storage for annotations. Suppose I want to write, in the style of C# (indicating that a certain method should be part of the web service interface)
class Foo(WebService):
@webmethod
def bar(self, arg1, arg2):
...
then I can define
def webmethod(func):
func.is_webmethod = True
return func
Then, when a webservice call arrives, I look up the method, check whether the underlying function has the is_webmethod attribute (the actual value is irrelevant), and refuse the service if the method is absent or not meant to be called over the web.
This is the simplest way to do it if you need multiple lines. Wrap you span
'd text in another span
and specify its height with line-height
. The trick to multiple lines is resetting the inner span
's line-height
.
<span class="textvalignmiddle"><span>YOUR TEXT HERE</span></span>
.textvalignmiddle {
line-height: /* Set height */;
}
.textvalignmiddle > span {
display: inline-block;
vertical-align: middle;
line-height: 1em; /* Set line height back to normal */
}
Of course the outer span
could be a div
or what have you.
The typical answer is this:
In Excel, File/Save As, select CSV, save your current sheet.
transfer to a holding directory on the Pg server the postgres user can access
in PostgreSQL:
COPY mytable FROM '/path/to/csv/file' WITH CSV HEADER; -- must be superuser
But there are other ways to do this too. PostgreSQL is an amazingly programmable database. These include:
Write a module in pl/javaU, pl/perlU, or other untrusted language to access file, parse it, and manage the structure.
Use CSV and the fdw_file to access it as a pseudo-table
Use DBILink and DBD::Excel
Write your own foreign data wrapper for reading Excel files.
The possibilities are literally endless....
I am newbie and most of the code is from google search. I got my pdf download working with the code below (trial and error play). Thank you for code tips (xhrFields) above.
$.ajax({
cache: false,
type: 'POST',
url: 'yourURL',
contentType: false,
processData: false,
data: yourdata,
//xhrFields is what did the trick to read the blob to pdf
xhrFields: {
responseType: 'blob'
},
success: function (response, status, xhr) {
var filename = "";
var disposition = xhr.getResponseHeader('Content-Disposition');
if (disposition) {
var filenameRegex = /filename[^;=\n]*=((['"]).*?\2|[^;\n]*)/;
var matches = filenameRegex.exec(disposition);
if (matches !== null && matches[1]) filename = matches[1].replace(/['"]/g, '');
}
var linkelem = document.createElement('a');
try {
var blob = new Blob([response], { type: 'application/octet-stream' });
if (typeof window.navigator.msSaveBlob !== 'undefined') {
// IE workaround for "HTML7007: One or more blob URLs were revoked by closing the blob for which they were created. These URLs will no longer resolve as the data backing the URL has been freed."
window.navigator.msSaveBlob(blob, filename);
} else {
var URL = window.URL || window.webkitURL;
var downloadUrl = URL.createObjectURL(blob);
if (filename) {
// use HTML5 a[download] attribute to specify filename
var a = document.createElement("a");
// safari doesn't support this yet
if (typeof a.download === 'undefined') {
window.location = downloadUrl;
} else {
a.href = downloadUrl;
a.download = filename;
document.body.appendChild(a);
a.target = "_blank";
a.click();
}
} else {
window.location = downloadUrl;
}
}
} catch (ex) {
console.log(ex);
}
}
});
It basically tells the program when you encounter an error just continue at the next line.
You can find the answer on this other S.O. question:
MySQL - can I limit the maximum time allowed for a query to run?
a cron job that runs every second on your database server, connecting and doing something like this:
- SHOW PROCESSLIST
- Find all connections with a query time larger than your maximum desired time
- Run KILL [process id] for each of those processes
Note that this isn't perfect, since if you had something like, say, <a title=">">
it would break. However, it's about the closest you'd get in non-library Python without a really complex function:
import re
TAG_RE = re.compile(r'<[^>]+>')
def remove_tags(text):
return TAG_RE.sub('', text)
However, as lvc mentions xml.etree
is available in the Python Standard Library, so you could probably just adapt it to serve like your existing lxml
version:
def remove_tags(text):
return ''.join(xml.etree.ElementTree.fromstring(text).itertext())
For me, the fix was to add margin: 0 auto;
onto the element containing the <svg>
.
Like this:
<div style="margin: 0 auto">
<svg ...</svg>
</div>
Your table width is 90% which is relative to it's container.
If you squeeze the page, you are probably squeezing the table width as well. The width of the cells reduce too and the browser compensate by increasing the height.
To have the height untouched, you have to make sure the widths of the cells can hold the intented content. Fixing the table width is probably something you want to try. Or perhaps play around with the min-width of the table.
Just use 'now'
http://www.postgresql.org/docs/8.0/static/datatype-datetime.html
const [text, setText] = useState('');
const onChangeText = (text) => {
if (+text) {
setText(text);
}
};
<TextInput
keyboardType="numeric"
value={text}
onChangeText={onChangeText}
/>
This should save from physical keyboards
You can uninstall WAMP/XAMPP and install it again with default port number. It will work properly.
I have tried everything, and finally deleting the -vm
options worked for me.
Here's what worked for me, here I'm attaching a file to my EmailController under test. Also take a look at the postman screenshot on how I'm posting the data.
@WebAppConfiguration
@RunWith(SpringRunner.class)
@SpringBootTest(
classes = EmailControllerBootApplication.class
)
public class SendEmailTest {
@Autowired
private WebApplicationContext webApplicationContext;
@Test
public void testSend() throws Exception{
String jsonStr = "{\"to\": [\"[email protected]\"],\"subject\": "
+ "\"CDM - Spring Boot email service with attachment\","
+ "\"body\": \"Email body will contain test results, with screenshot\"}";
Resource fileResource = new ClassPathResource(
"screen-shots/HomePage-attachment.png");
assertNotNull(fileResource);
MockMultipartFile firstFile = new MockMultipartFile(
"attachments",fileResource.getFilename(),
MediaType.MULTIPART_FORM_DATA_VALUE,
fileResource.getInputStream());
assertNotNull(firstFile);
MockMvc mockMvc = MockMvcBuilders.
webAppContextSetup(webApplicationContext).build();
mockMvc.perform(MockMvcRequestBuilders
.multipart("/api/v1/email/send")
.file(firstFile)
.param("data", jsonStr))
.andExpect(status().is(200));
}
}
Jelly Bean adds support for this with the ActivityOptions.makeCustomAnimation() method. Of course, since it's only on Jelly Bean, it's pretty much worthless for practical purposes.
example :
df1.iloc[:5]
df1.loc['A','B']
function doParseCSVFile($filesArray)
{
if ((file_exists($filesArray['frmUpload']['name'])) && (is_readable($filesArray['frmUpload']['name']))) {
$strFilePath = $filesArray['frmUpload']['tmp_name'];
$strFileHandle = fopen($strFilePath,"r");
$line_of_text = fgetcsv($strFileHandle,1024,",","'");
$line_of_text = fgetcsv($strFileHandle,1024,",","'");
do {
if ($line_of_text[0]) {
$strInsertSql = "INSERT INTO tbl_employee(employee_name, employee_code, employee_email, employee_designation, employee_number)VALUES('".addslashes($line_of_text[0])."', '".$line_of_text[1]."', '".addslashes($line_of_text[2])."', '".$line_of_text[3]."', '".$line_of_text[4]."')";
ExecuteQry($strInsertSql);
}
} while (($line_of_text = fgetcsv($strFileHandle,1024,",","'"))!== FALSE);
} else {
return FALSE;
}
}
You can use this code for toggle your element var ele = jQuery("yourelementid"); ele.slideToggle('slow'); this will work for you :)
This extension that @Rob suggested works for Swift 3.0.1
I wasn't able to compile the version he included in his post with Xcode 8.1 (8B62)
extension Dictionary {
/// Build string representation of HTTP parameter dictionary of keys and objects
///
/// :returns: String representation in the form of key1=value1&key2=value2 where the keys and values are percent escaped
func stringFromHttpParameters() -> String {
var parametersString = ""
for (key, value) in self {
if let key = key as? String,
let value = value as? String {
parametersString = parametersString + key + "=" + value + "&"
}
}
parametersString = parametersString.substring(to: parametersString.index(before: parametersString.endIndex))
return parametersString.addingPercentEncoding(withAllowedCharacters: .urlHostAllowed)!
}
}
The method getDeviceId()
is deprecated.
There a new method for this getImei(int)
You can also use the matrix
command, to create a matrix with n lines and m columns, filled with zeros.
matrix(0, n, m)
This is an ancient question, but I thought I'd answer it since everyone here has some crazy solutions. It's actually very very simple...
An anchor tag works like this -
<a href="whatever you want"> EVERYTHING IN HERE TURNS INTO A LINK </a>
Sooo...
<a href="whatever you want"> <div id="thediv" /> </a>
Although I'm not sure if this is valid. If that's the reasoning behind spoken solutions, then I apologise...
iPhone:
Mozilla/5.0 (iPhone; CPU iPhone OS 6_0 like Mac OS X) AppleWebKit/536.26 (KHTML, like Gecko) Version/6.0 Mobile/10A5376e Safari/8536.25
iPad:
Mozilla/5.0 (iPad; CPU OS 6_0 like Mac OS X) AppleWebKit/536.26 (KHTML, like Gecko) Version/6.0 Mobile/10A5376e Safari/8536.25
For a complete list and more details about the iOS user agent check out these 2 resources:
Safari User Agent Strings (http://useragentstring.com/pages/Safari/)
Complete List of iOS User-Agent Strings (http://enterpriseios.com/wiki/UserAgent)
I got this error while running the command using pip3
. I have python 3.6 installed on windows. I was trying this-
pip3 install PACKAGENAME
It gave error. The solution in this particular case is simply to run the command as pip
.
pip install PACKAGENAME
Here is another way to do it, if you need something flexible where you want to display help if specific params are passed, none at all or more than 1 conflicting arg:
import argparse
import sys
def main():
parser = argparse.ArgumentParser()
parser.add_argument('-d', '--days', required=False, help="Check mapped inventory that is x days old", default=None)
parser.add_argument('-e', '--event', required=False, action="store", dest="event_id",
help="Check mapped inventory for a specific event", default=None)
parser.add_argument('-b', '--broker', required=False, action="store", dest="broker_id",
help="Check mapped inventory for a broker", default=None)
parser.add_argument('-k', '--keyword', required=False, action="store", dest="event_keyword",
help="Check mapped inventory for a specific event keyword", default=None)
parser.add_argument('-p', '--product', required=False, action="store", dest="product_id",
help="Check mapped inventory for a specific product", default=None)
parser.add_argument('-m', '--metadata', required=False, action="store", dest="metadata",
help="Check mapped inventory for specific metadata, good for debugging past tix", default=None)
parser.add_argument('-u', '--update', required=False, action="store_true", dest="make_updates",
help="Update the event for a product if there is a difference, default No", default=False)
args = parser.parse_args()
days = args.days
event_id = args.event_id
broker_id = args.broker_id
event_keyword = args.event_keyword
product_id = args.product_id
metadata = args.metadata
make_updates = args.make_updates
no_change_counter = 0
change_counter = 0
req_arg = bool(days) + bool(event_id) + bool(broker_id) + bool(product_id) + bool(event_keyword) + bool(metadata)
if not req_arg:
print("Need to specify days, broker id, event id, event keyword or past tickets full metadata")
parser.print_help()
sys.exit()
elif req_arg != 1:
print("More than one option specified. Need to specify only one required option")
parser.print_help()
sys.exit()
# Processing logic here ...
Cheers!
SWIFT 4.x
The Strings in double quotes always confuse me, so I think answer to this question needs some graphical presentation to clear this out.
For a banking app, I have a LoginViewController and a BalanceViewController. Each have their respective screens.
The app starts and shows the Login screen. When login is successful, app opens the Balance screen.
Here is how it looks:
The login success is handled like this:
let storyBoard: UIStoryboard = UIStoryboard(name: "Balance", bundle: nil)
let balanceViewController = storyBoard.instantiateViewController(withIdentifier: "balance") as! BalanceViewController
self.present(balanceViewController, animated: true, completion: nil)
As you can see, the storyboard ID 'balance' in small letters is what goes in the second line of the code, and this is the ID which is defined in the storyboard settings, as in the attached screenshot.
The term 'Balance' with capital 'B' is the name of the storyboard file, which is used in the first line of the code.
We know that using hard coded Strings in code is a very bad practice, but somehow in iOS development it has become a common practice, and Xcode doesn't even warn about them.
gcc 4.5 and 4.6 are not supported with CUDA - code won't compile and the rest of the toolchain, including cuda-gdb, won't work properly. You cannot use them, and the restriction is non-negotiable.
Your only solution is to install a gcc 4.4 version as a second compiler (most distributions will allow that). There is an option to nvcc --compiler-bindir
which can be used to point to an alternative compiler. Create a local directory and then make symbolic links to the supported gcc version executables. Pass that local directory to nvcc via the --compiler-bindir
option, and you should be able to compile CUDA code without affecting the rest of your system.
EDIT:
Note that this question, and answer, pertain to CUDA 4.
Since it was written, NVIDIA has continued to expand support for later gcc versions in newer CUDA toolchain release
There is presently (as of CUDA 11.1) no gcc 10 support in CUDA other than Fedora linux
Note that NVIDIA has recently added a very useful table here which contains the supported compiler and OS matrix for the current CUDA release.
Just in case somebody land here... since 8.1 you can simply use:
SELECT user_id
FROM user_logs
WHERE login_date BETWEEN SYMMETRIC '2014-02-01' AND '2014-02-28'
From the docs:
BETWEEN SYMMETRIC is the same as BETWEEN except there is no requirement that the argument to the left of AND be less than or equal to the argument on the right. If it is not, those two arguments are automatically swapped, so that a nonempty range is always implied.
If you want to do a transformation on the text on a character level, and get the transformed text back at the end, you would do something like this:
var value = "alma";
var new_value = value.split("").map(function(x) { return x+"E" }).join("")
So the steps:
*** Update August 2020 Release *** see https://github.com/microsoft/vscode/pull/104310
"editor.renderWhitespace": "trailing"
// option being added
Add a new option ('trailing') to editor.renderWhitespace that renders only
trailing whitespace (including lines with only whitespace).
*** Update February 2020 Release *** see https://github.com/microsoft/vscode/issues/90386
In v1.43 the default value will be changed to selection
from none
as it was in v1.42.
"editor.renderWhitespace": "selection" // default in v1.43
Update for v1.37: adding the option to render whitespace within selected text only. See v1.37 release notes, render whitespace.
The
editor.renderWhitespace
setting now supports aselection
option. With this option set, whitespace will be shown only on selected text:
"editor.renderWhitespace": "selection"
and
"workbench.colorCustomizations": {
"editorWhitespace.foreground": "#fbff00"
}
If you are using downloading data using url...may need to use
var result = client.DownloadData(url);
There are many toolboxes. Since you mentioned one that is commercially available from MathWorks, I assume you mean how do you get a trial/license
http://www.mathworks.com/products/image/
There is a link for trials, purchase, demos. This will get you in touch with your sales representative. If you know your sales representative, you could just call to get attention faster.
If you mean just a general toolbox that is from a source other than MathWorks, I would check with the producer, as it will vary widely from "Put it on your path." to whatever their purchase and licensing procedure is.
The way the operator works is that it gets incremented at the same time, but if it is before a variable, the expression will evaluate with the incremented/decremented variable:
int x = 0; //x is 0
int y = ++x; //x is 1 and y is 1
If it is after the variable the current statement will get executed with the original variable, as if it had not yet been incremented/decremented:
int x = 0; //x is 0
int y = x++; //'y = x' is evaluated with x=0, but x is still incremented. So, x is 1, but y is 0
I agree with dcp in using pre-increment/decrement (++x) unless necessary. Really the only time I use the post-increment/decrement is in while loops or loops of that sort. These loops are the same:
while (x < 5) //evaluates conditional statement
{
//some code
++x; //increments x
}
or
while (x++ < 5) //evaluates conditional statement with x value before increment, and x is incremented
{
//some code
}
You can also do this while indexing arrays and such:
int i = 0;
int[] MyArray = new int[2];
MyArray[i++] = 1234; //sets array at index 0 to '1234' and i is incremented
MyArray[i] = 5678; //sets array at index 1 to '5678'
int temp = MyArray[--i]; //temp is 1234 (becasue of pre-decrement);
Etc, etc...
I had this error with WAMP 3.0.6 with MySql 5.7.14.
Solution:
change line 70 (if your ini file is untouched) in c:\wamp\bin\mysql\mysql5.7.14\my.ini
file from
sql-mode= "STRICT_ALL_TABLES,ERROR_FOR_DIVISION_BY_ZERO,NO_ZERO_DATE,NO_ZERO_IN_DATE,NO_AUTO_CREATE_USER"
to
sql-mode="ERROR_FOR_DIVISION_BY_ZERO,NO_ZERO_DATE,NO_ZERO_IN_DATE,NO_AUTO_CREATE_USER"
and restart all services.
This will disable strict mode. As per the documentation, “strict mode” means a mode with either or both STRICT_TRANS_TABLES
or STRICT_ALL_TABLES
enabled.
The documentation says:
"The default SQL mode in MySQL 5.7 includes these modes: ONLY_FULL_GROUP_BY, STRICT_TRANS_TABLES, NO_ZERO_IN_DATE, NO_ZERO_DATE, ERROR_FOR_DIVISION_BY_ZERO, NO_AUTO_CREATE_USER, and NO_ENGINE_SUBSTITUTION."
public static update(values: Object, options: Object): Promise>
check documentation once http://docs.sequelizejs.com/class/lib/model.js~Model.html#static-method-update
Project.update(
// Set Attribute values
{ title:'a very different title now' },
// Where clause / criteria
{ _id : 1 }
).then(function(result) {
//it returns an array as [affectedCount, affectedRows]
})
Several answers are here but nobody has posted usefull code.
Here is my code that detects all encodings that Microsoft detects in Framework 4 in the StreamReader class.
Obviously you must call this function immediately after opening the stream before reading anything else from the stream because the BOM are the first bytes in the stream.
This function requires a Stream that can seek (for example a FileStream). If you have a Stream that cannot seek you must write a more complicated code that returns a Byte buffer with the bytes that have already been read but that are not BOM.
/// <summary>
/// UTF8 : EF BB BF
/// UTF16 BE: FE FF
/// UTF16 LE: FF FE
/// UTF32 BE: 00 00 FE FF
/// UTF32 LE: FF FE 00 00
/// </summary>
public static Encoding DetectEncoding(Stream i_Stream)
{
if (!i_Stream.CanSeek || !i_Stream.CanRead)
throw new Exception("DetectEncoding() requires a seekable and readable Stream");
// Try to read 4 bytes. If the stream is shorter, less bytes will be read.
Byte[] u8_Buf = new Byte[4];
int s32_Count = i_Stream.Read(u8_Buf, 0, 4);
if (s32_Count >= 2)
{
if (u8_Buf[0] == 0xFE && u8_Buf[1] == 0xFF)
{
i_Stream.Position = 2;
return new UnicodeEncoding(true, true);
}
if (u8_Buf[0] == 0xFF && u8_Buf[1] == 0xFE)
{
if (s32_Count >= 4 && u8_Buf[2] == 0 && u8_Buf[3] == 0)
{
i_Stream.Position = 4;
return new UTF32Encoding(false, true);
}
else
{
i_Stream.Position = 2;
return new UnicodeEncoding(false, true);
}
}
if (s32_Count >= 3 && u8_Buf[0] == 0xEF && u8_Buf[1] == 0xBB && u8_Buf[2] == 0xBF)
{
i_Stream.Position = 3;
return Encoding.UTF8;
}
if (s32_Count >= 4 && u8_Buf[0] == 0 && u8_Buf[1] == 0 && u8_Buf[2] == 0xFE && u8_Buf[3] == 0xFF)
{
i_Stream.Position = 4;
return new UTF32Encoding(true, true);
}
}
i_Stream.Position = 0;
return Encoding.Default;
}
This will give you all the elements as a list.
mvv_list = list(
mvv_count_df.select('mvv').toPandas()['mvv']
)
$data = DB::table('borrowers')
->join('loans', 'borrowers.id', '=', 'loans.borrower_id')
->select('borrowers.*', 'loans.*')
->where('loan_officers', 'like', '%' . $officerId . '%')
->where('loans.maturity_date', '<', date("Y-m-d"))
->get();
The reason is one servlet container is already running on port 8080 and you are trying to run another one on port 8080.
Check what processes are running at available ports.
For Windows :
netstat -ao |find /i "listening"
OR
netstat -ano | find "8080"
(Note: 8080 is port fail to start)
Now try to reLaunch or stop your application.
Taskkill /F /IM 6592 Note: Mention correct Process Id
right click on the console and select terminate/disconnect all
Task Manager
and end Java(tm) platform se binaryAnother option is :
Go to application.properties
file set server.port=0
. This will cause Spring Boot to use a random free port every time it starts.
A solution I found was to have the <form>
target a hidden iFrame. The iFrame can then run JS to display to the user that it's complete (on page load).
I'm from Brazil and I create my data bases using latin1_spanish_ci
. For the html and everything else I use:
charset=ISO-8859-1
The data goes right with é
,ã
and ç
... Sometimes I have to put the texts of the html using the code of it, such as:
Olá
gives me
Olá
You can find the codes in this page: http://www.ascii.cl/htmlcodes.htm
Hope this helps. I remember it was REALLY annoying.
It happens when common column in both table are of different data type.
Example: In table1, you have date as string whereas in table2 you have date as datetime. so before merging,we need to change date to common data type.
Whilst this is a very old question, it is so important in getting a date of birth input correct, especially in a registration form.
I think no one has done this better than the google accounts sign up:
Select the month first from a select box and manually type in the date and year. Simple.
Easy to validate. Easy for users to get right. No scrolling back the years in a select box from 1900-the present year. No need to update a 'day' select box based on month input. Works great on web. Works great on mobile. Works for all locales eg 01/10/2014 - is that the 1st October or 10th Jan? I expect we'll be seeing this birthday picker format a lot more in future.
A datepicker is just a poor solution all round. So many clicks! In my opinion, a datepicker is only useful when knowing the day of the week is important eg booking tickets.
Update 2/6/2016: I am from UK, so I am more familiar with day/month/year formats, rather than month/day/year. However, users who will use their cursor to select the month, I believe it is much easier having the select box first, rather than going input > select box > input. The comment date is 2nd June, not 6th Feb ;)
The method you are trying to use checks if the button is active:
btnAdd.isEnabled()
When enabled, any component associated with this object is active and able to fire this object's actionPerformed method.
This method does not check if the button is pressed.
If i understand your question correctly, you want to disable your "Add" button after the user clicks "Check out".
Try disabling your button at start: btnAdd.setEnabled(false)
or after the user presses "Check out"
Calling m.check(side), meaning you are running actual code, but you can't run code outside main() - you can only define variables. In C++, code can only appear inside function bodies or in variable initializes.
It might require a relatively recent version of Git, but this works well for me:
git rev-list --count develop..HEAD
This gives me an exact count of commits in the current branch having its base on master.
The command in Peter's answer, git rev-list --count HEAD ^develop
includes many more commits, 678 vs 97 on my current project.
My commit history is linear on this branch, so YMMV, but it gives me the exact answer I wanted, which is "How many commits have I added so far on this feature branch?".
If it's a local development tomcat launched from IDE, then restarting this IDE and rebuild project also helps.
Update:
You could also try to find if there is any running tomcat process in the background and kill it.
I have the same question: PHP Fatal error: Call to undefined function json_decode()
, but I run php under cygwin on Windows. When I run php -m
, I found that there is no json module installed. So I run cygwin setup.exe again, check json package from the configuration interface, and the problem is solved.
I am on Android Studio 0.6 and the apk was generated in
MyApp/myapp/build/outputs/apk/myapp-debug.apk
It included all libraries so I could share it.
Update on Android Studio 0.8.3 Beta. The apk is now in
MyApp/myapp/build/apk/myapp-debug.apk
Update on Android Studio 0.8.6 - 2.0. The apk is now in
MyApp/myapp/build/outputs/apk/myapp-debug.apk
here is the snippet to set token, before that make sure the access type should be set to offline
if (isset($_GET['code'])) {
$client->authenticate();
$_SESSION['access_token'] = $client->getAccessToken();
}
To refresh token
$google_token= json_decode($_SESSION['access_token']);
$client->refreshToken($google_token->refresh_token);
this will refresh your token, you have to update it in session for that you can do
$_SESSION['access_token']= $client->getAccessToken()
Using "List" you can prevent casting errors. It is very useful to avoid a runtime casting error.
Example:
Here (using ArrayList) you can compile this code but you will see an execution error later.
// Create a new ArrayList
System.Collections.ArrayList mixedList = new System.Collections.ArrayList();
// Add some numbers to the list
mixedList.Add(7);
mixedList.Add(21);
// Add some strings to the list
mixedList.Add("Hello");
mixedList.Add("This is going to be a problem");
System.Collections.ArrayList intList = new System.Collections.ArrayList();
System.Collections.ArrayList strList = new System.Collections.ArrayList();
foreach (object obj in mixedList)
{
if (obj.GetType().Equals(typeof(int)))
{
intList.Add(obj);
}
else if (obj.GetType().Equals(typeof(string)))
{
strList.Add(obj);
}
else
{
// error.
}
}
This is my solution with prepared statements and stored procedure is returning several rows not only one value.
<?php
require 'config.php';
header('Content-type:application/json');
$connection->set_charset('utf8');
$mIds = $_GET['ids'];
$stmt = $connection->prepare("CALL sp_takes_string_returns_table(?)");
$stmt->bind_param("s", $mIds);
$stmt->execute();
$result = $stmt->get_result();
$response = $result->fetch_all(MYSQLI_ASSOC);
echo json_encode($response);
$stmt->close();
$connection->close();
In Java:
String regex = "[^-\\s]";
System.out.println("-".matches(regex)); // prints "false"
System.out.println(" ".matches(regex)); // prints "false"
System.out.println("+".matches(regex)); // prints "true"
The regex [^-\s]
works as expected. [^\s-]
also works.
The hyphen can be included right after the opening bracket, or right before the closing bracket, or right after the negating caret.
I had this same issue when trying to handle popping alerts and fading them. I searched around various places and found this to be my solution. Adding and removing the 'in' class fixed my issue.
window.setTimeout(function() { // hide alert message
$("#alert_message").removeClass('in');
}, 5000);
When using .remove() and similarly the .alert('close') solution I seemed to hit an issue with the alert being removed from the document, so if I wanted to use the same alert div again I was unable to. This solution means the alert is reusable without refreshing the page. (I was using aJax to submit a form and present feedback to the user)
$('#Some_Button_Or_Event_Here').click(function () { // Show alert message
$('#alert_message').addClass('in');
});
You have two ways:
Lets start by looking for a specific application in my laptop:
[root@pinky:~]# ps fax | grep mozilla
3358 ? S 0:00 \_ /bin/sh /usr/lib/firefox-3.5/run-mozilla.sh /usr/lib/firefox-3.5/firefox
16198 pts/2 S+ 0:00 \_ grep mozilla
All examples now will look for PID 3358.
First way: Run "ps aux" and grep for the PID in the second column. In this example I look for firefox, and then for it's PID:
[root@pinky:~]# ps aux | awk '{print $2 }' | grep 3358
3358
So your code will be:
if [ ps aux | awk '{print $2 }' | grep -q $PID 2> /dev/null ]; then
kill $PID
fi
Second way: Just look for something in the /proc/$PID
directory. I am using "exe" in this example, but you can use anything else.
[root@pinky:~]# ls -l /proc/3358/exe
lrwxrwxrwx. 1 elcuco elcuco 0 2010-06-15 12:33 /proc/3358/exe -> /bin/bash
So your code will be:
if [ -f /proc/$PID/exe ]; then
kill $PID
fi
BTW: whats wrong with kill -9 $PID || true
?
EDIT:
After thinking about it for a few months.. (about 24...) the original idea I gave here is a nice hack, but highly unportable. While it teaches a few implementation details of Linux, it will fail to work on Mac, Solaris or *BSD. It may even fail on future Linux kernels. Please - use "ps" as described in other responses.
Or you can use what JQuery alreay made for you:
http://jqueryui.com/datepicker/#icon-trigger
It's what you are trying to achieve isn't it?
You can check out this post on SuperUser.
Word starts page numbering over for each new section by default.
I do it slightly differently than the post above that goes through the ribbon menus, but in both methods you have to go through the document to each section's beginning.
My method:
Format Page Numbers
Continue from Previous Section
radio button under Page numbering
I find this right-click method to be a little faster. Also, usually if I insert the page numbers first before I start making any new sections, this problem doesn't happen in the first place.
If you use spring-boot, you don't need to create a DataSource class, just specify the data url/username/password/driver in application.properties
, then you can simply @Autowired
it.
@Repository
public class JdbcRepository {
private final JdbcTemplate jdbcTemplate;
@Autowired
public DynamicRepository(JdbcTemplate jdbcTemplate) {
this.jdbcTemplate = jdbcTemplate;
}
public void insert() {
jdbcTemplate.update("INSERT INTO BOOK (name, description) VALUES ('book name', 'book description')");
}
}
Example of application.properties
:
#Basic Spring Boot Config for Oracle
spring.datasource.url=jdbc:oracle:thin:@(DESCRIPTION=(ADDRESS=(PROTOCOL=TCP)(HOST=YourHostIP)(PORT=YourPort))(CONNECT_DATA=(SERVER=dedicated)(SERVICE_NAME=YourServiceName)))
spring.datasource.username=username
spring.datasource.password=password
spring.datasource.driver-class-name=oracle.jdbc.OracleDriver
#hibernate config
spring.jpa.database-platform=org.hibernate.dialect.Oracle10gDialect
Then add the driver and connection pool dependencies in pom.xml
<dependency>
<groupId>com.oracle</groupId>
<artifactId>ojdbc7</artifactId>
<version>12.1.0.1</version>
</dependency>
<!-- HikariCP connection pool -->
<dependency>
<groupId>com.zaxxer</groupId>
<artifactId>HikariCP</artifactId>
<version>2.6.0</version>
</dependency>
See the official doc for more details.
$limit=5; // for exemple
$query = $this->getDoctrine()->getEntityManager()->createQuery(
'// your request')
->setMaxResults($limit);
$results = $query->getResult();
// Done
I have noticed that your success function has the parameter "html", and you are trying to add "data" to your elements html()
... Change it so these both match:
$.ajax({
type:"POST",
url: "ajax.php",
data:"id="+id ,
success: function(data){
$("#response").html(data);
}
});
I ran into a similar problem while creating a library to handle authentication. I want the app owner using my library to be able to register a callback with the library for checking authorization against LDAP groups the authenticated person is in. The configuration is getting passed in as a config.py file that gets imported and contains a dict with all the config parameters.
I got this to work:
>>> class MyClass(object):
... def target_func(self):
... print "made it!"
...
... def __init__(self,config):
... self.config = config
... self.config['funcname'] = getattr(self,self.config['funcname'])
... self.config['funcname']()
...
>>> instance = MyClass({'funcname':'target_func'})
made it!
Is there a pythonic-er way to do this?
$request->fullUrl()
will also work if you are injecting Illumitate\Http\Request
.
static public string GetCountry()
{
return new WebClient().DownloadString("http://api.hostip.info/country.php");
}
Usage:
Console.WriteLine(GetCountry()); // will return short code for your country
static public string GetInfo()
{
return new WebClient().DownloadString("http://api.hostip.info/get_json.php");
}
Usage:
Console.WriteLine(GetInfo());
// Example:
// {
// "country_name":"COUNTRY NAME",
// "country_code":"COUNTRY CODE",
// "city":"City",
// "ip":"XX.XXX.XX.XXX"
// }
Try this :
fig,axis = plt.subplots(nrows=1,ncols=1,figsize=(13,6),sharex=True)
axis.set_xticklabels(['0', 'testing', '10000', '20000', '30000'],fontsize=22)
You can set executionTimeout
in web.config to support the longer execution time.
executionTimeout
specifies the maximum number of seconds that a request is allowed to execute before being automatically shut down by ASP.NET. MSDN
<httpRuntime executionTimeout = "300" />
This make execution timeout to five minutes.
Optional Int32 attribute.
Specifies the maximum number of seconds that a request is allowed to execute before being automatically shut down by ASP.NET.
This time-out applies only if the debug attribute in the compilation element is False. Therefore, if the debug attribute is True, you do not have to set this attribute to a large value in order to avoid application shutdown while you are debugging. The default is 110 seconds, Reference.
With a help of a small convenience class, you can measure time spent in indented lines like this:
with CodeTimer():
line_to_measure()
another_line()
# etc...
Which will show the following after the indented line(s) finishes executing:
Code block took: x.xxx ms
UPDATE: You can now get the class with pip install linetimer
and then from linetimer import CodeTimer
. See this GitHub project.
The code for above class:
import timeit
class CodeTimer:
def __init__(self, name=None):
self.name = " '" + name + "'" if name else ''
def __enter__(self):
self.start = timeit.default_timer()
def __exit__(self, exc_type, exc_value, traceback):
self.took = (timeit.default_timer() - self.start) * 1000.0
print('Code block' + self.name + ' took: ' + str(self.took) + ' ms')
You could then name the code blocks you want to measure:
with CodeTimer('loop 1'):
for i in range(100000):
pass
with CodeTimer('loop 2'):
for i in range(100000):
pass
Code block 'loop 1' took: 4.991 ms
Code block 'loop 2' took: 3.666 ms
And nest them:
with CodeTimer('Outer'):
for i in range(100000):
pass
with CodeTimer('Inner'):
for i in range(100000):
pass
for i in range(100000):
pass
Code block 'Inner' took: 2.382 ms
Code block 'Outer' took: 10.466 ms
Regarding timeit.default_timer()
, it uses the best timer based on OS and Python version, see this answer.
If you use numpy.multiply
S = [22, 33, 45.6, 21.6, 51.8]
P = 2.45
multiply(S, P)
It gives you as a result
array([53.9 , 80.85, 111.72, 52.92, 126.91])
See this answer https://stackoverflow.com/a/23010605/2760919
For your case, just change the type in snprintf from long ("%ld") to int ("%n").
Are you possibly depending on development versions that obviously change a lot during development?
Instead of incrementing the version of development releases, you could just use a snapshot version that you overwrite when necessary, which means you wouldn't have to change the version tag on every minor change. Something like 1.0-SNAPSHOT...
But maybe you are trying to achieve something else ;)
Depending on the version of Windows you might find the use of the "Choice" option to be helpful. It is not supported in most if not all x64 versions as far as I can tell. A handy substitution called Choice.vbs along with examples of use can be found on SourceForge under the name Choice.zip
You can easily do this using the following command. Any value of 0 will be turned into a 0 (BIT = false), anything else will be turned into 1 (BIT = true).
ALTER TABLE dbo.YourTable
ALTER COLUMN YourColumnName BIT
The other option would be to create a new column of type BIT
, fill it from the old column, and once you're done, drop the old column and rename the new one to the old name. That way, if something during the conversion goes wrong, you can always go back since you still have all the data..
I think I see your problem, you need to use the @
syntax to define parameters you will pass in this way, also I'm not sure what loginID or password are doing you don't seem to define them anywhere and they are not being used as URL parameters so are they being sent as query parameters?
This is what I can suggest based on what I see so far:
.factory('MagComments', function ($resource) {
return $resource('http://localhost/dooleystand/ci/api/magCommenct/:id', {
loginID : organEntity,
password : organCommpassword,
id : '@magId'
});
})
The @magId
string will tell the resource to replace :id
with the property magId
on the object you pass it as parameters.
I'd suggest reading over the documentation here (I know it's a bit opaque) very carefully and looking at the examples towards the end, this should help a lot.
Change the return type of your GetResults to be List<Person>
.
Eliminate the code that you use to serialize the List to a json string - WCF does this for you automatically.
Using your definition for the Person class, this code works for me:
public List<Person> GetPlayers()
{
List<Person> players = new List<Person>();
players.Add(new Person { FirstName="Peyton", LastName="Manning", Age=35 } );
players.Add(new Person { FirstName="Drew", LastName="Brees", Age=31 } );
players.Add(new Person { FirstName="Brett", LastName="Favre", Age=58 } );
return players;
}
results:
[{"Age":35,"FirstName":"Peyton","LastName":"Manning"},
{"Age":31,"FirstName":"Drew","LastName":"Brees"},
{"Age":58,"FirstName":"Brett","LastName":"Favre"}]
(All on one line)
I also used this attribute on the method:
[WebInvoke(Method = "GET",
RequestFormat = WebMessageFormat.Json,
ResponseFormat = WebMessageFormat.Json,
UriTemplate = "players")]
WebInvoke with Method= "GET" is the same as WebGet, but since some of my methods are POST, I use all WebInvoke for consistency.
The UriTemplate sets the URL at which the method is available. So I can do a GET on
http://myserver/myvdir/JsonService.svc/players
and it just works.
Also check out IIRF or another URL rewriter to get rid of the .svc in the URI.
Tablets supports tvdpi and for that scaling factor is 1.33 times dimensions of medium dpi
ldpi | mdpi | tvdpi | hdpi | xhdpi | xxhdpi | xxxhdpi
0.75 | 1 | 1.33 | 1.5 | 2 | 3 | 4
This means that if you generate a 400x400 image for xxxhdpi devices, you should generate the same resource in 300x300 for xxhdpi, 200x200 for xhdpi, 133x133 for tvdpi, 150x150 for hdpi, 100x100 for mdpi, and 75x75 for ldpi devices
You may not get "xuxu p1 p2 p3 p4" as it seems. But when you are in PowerShell and you set
PS > set-executionpolicy Unrestricted -scope currentuser
You can run those scripts like this:
./xuxu p1 p2 p3 p4
or
.\xuxu p1 p2 p3 p4
or
./xuxu.ps1 p1 p2 p3 p4
I hope that makes you a bit more comfortable with PowerShell.
The variable names should be descriptive:
var date = new Date;
date.setTime(result_from_Date_getTime);
var seconds = date.getSeconds();
var minutes = date.getMinutes();
var hour = date.getHours();
var year = date.getFullYear();
var month = date.getMonth(); // beware: January = 0; February = 1, etc.
var day = date.getDate();
var dayOfWeek = date.getDay(); // Sunday = 0, Monday = 1, etc.
var milliSeconds = date.getMilliseconds();
The days of a given month do not change. In a leap year, February has 29 days. Inspired by http://www.javascriptkata.com/2007/05/24/how-to-know-if-its-a-leap-year/ (thanks Peter Bailey!)
Continued from the previous code:
var days_in_months = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
// for leap years, February has 29 days. Check whether
// February, the 29th exists for the given year
if( (new Date(year, 1, 29)).getDate() == 29 ) days_in_month[1] = 29;
There is no straightforward way to get the week of a year. For the answer on that question, see Is there a way in javascript to create a date object using year & ISO week number?
This is a solution that you can see in the vidios of the WWDC. You have to do a Gaussian Blur, so the first thing you have to do is to add a new .m and .h file with the code i'm writing here, then you have to make and screen shoot, use the desired effect and add it to your view, then your UITable UIView or what ever has to be transparent, you can play with applyBlurWithRadius, to archive the desired effect, this call works with any UIImage.
At the end the blured image will be the background and the rest of the controls above has to be transparent.
For this to work you have to add the next libraries:
Acelerate.framework,UIKit.framework,CoreGraphics.framework
I hope you like it.
Happy coding.
//Screen capture.
UIGraphicsBeginImageContext(self.view.bounds.size);
CGContextRef c = UIGraphicsGetCurrentContext();
CGContextTranslateCTM(c, 0, 0);
[self.view.layer renderInContext:c];
UIImage* viewImage = UIGraphicsGetImageFromCurrentImageContext();
viewImage = [viewImage applyLightEffect];
UIGraphicsEndImageContext();
//.h FILE
#import <UIKit/UIKit.h>
@interface UIImage (ImageEffects)
- (UIImage *)applyLightEffect;
- (UIImage *)applyExtraLightEffect;
- (UIImage *)applyDarkEffect;
- (UIImage *)applyTintEffectWithColor:(UIColor *)tintColor;
- (UIImage *)applyBlurWithRadius:(CGFloat)blurRadius tintColor:(UIColor *)tintColor saturationDeltaFactor:(CGFloat)saturationDeltaFactor maskImage:(UIImage *)maskImage;
@end
//.m FILE
#import "cGaussianEffect.h"
#import <Accelerate/Accelerate.h>
#import <float.h>
@implementation UIImage (ImageEffects)
- (UIImage *)applyLightEffect
{
UIColor *tintColor = [UIColor colorWithWhite:1.0 alpha:0.3];
return [self applyBlurWithRadius:1 tintColor:tintColor saturationDeltaFactor:1.8 maskImage:nil];
}
- (UIImage *)applyExtraLightEffect
{
UIColor *tintColor = [UIColor colorWithWhite:0.97 alpha:0.82];
return [self applyBlurWithRadius:1 tintColor:tintColor saturationDeltaFactor:1.8 maskImage:nil];
}
- (UIImage *)applyDarkEffect
{
UIColor *tintColor = [UIColor colorWithWhite:0.11 alpha:0.73];
return [self applyBlurWithRadius:1 tintColor:tintColor saturationDeltaFactor:1.8 maskImage:nil];
}
- (UIImage *)applyTintEffectWithColor:(UIColor *)tintColor
{
const CGFloat EffectColorAlpha = 0.6;
UIColor *effectColor = tintColor;
int componentCount = CGColorGetNumberOfComponents(tintColor.CGColor);
if (componentCount == 2) {
CGFloat b;
if ([tintColor getWhite:&b alpha:NULL]) {
effectColor = [UIColor colorWithWhite:b alpha:EffectColorAlpha];
}
}
else {
CGFloat r, g, b;
if ([tintColor getRed:&r green:&g blue:&b alpha:NULL]) {
effectColor = [UIColor colorWithRed:r green:g blue:b alpha:EffectColorAlpha];
}
}
return [self applyBlurWithRadius:10 tintColor:effectColor saturationDeltaFactor:-1.0 maskImage:nil];
}
- (UIImage *)applyBlurWithRadius:(CGFloat)blurRadius tintColor:(UIColor *)tintColor saturationDeltaFactor:(CGFloat)saturationDeltaFactor maskImage:(UIImage *)maskImage
{
if (self.size.width < 1 || self.size.height < 1) {
NSLog (@"*** error: invalid size: (%.2f x %.2f). Both dimensions must be >= 1: %@", self.size.width, self.size.height, self);
return nil;
}
if (!self.CGImage) {
NSLog (@"*** error: image must be backed by a CGImage: %@", self);
return nil;
}
if (maskImage && !maskImage.CGImage) {
NSLog (@"*** error: maskImage must be backed by a CGImage: %@", maskImage);
return nil;
}
CGRect imageRect = { CGPointZero, self.size };
UIImage *effectImage = self;
BOOL hasBlur = blurRadius > __FLT_EPSILON__;
BOOL hasSaturationChange = fabs(saturationDeltaFactor - 1.) > __FLT_EPSILON__;
if (hasBlur || hasSaturationChange) {
UIGraphicsBeginImageContextWithOptions(self.size, NO, [[UIScreen mainScreen] scale]);
CGContextRef effectInContext = UIGraphicsGetCurrentContext();
CGContextScaleCTM(effectInContext, 1.0, -1.0);
CGContextTranslateCTM(effectInContext, 0, -self.size.height);
CGContextDrawImage(effectInContext, imageRect, self.CGImage);
vImage_Buffer effectInBuffer;
effectInBuffer.data = CGBitmapContextGetData(effectInContext);
effectInBuffer.width = CGBitmapContextGetWidth(effectInContext);
effectInBuffer.height = CGBitmapContextGetHeight(effectInContext);
effectInBuffer.rowBytes = CGBitmapContextGetBytesPerRow(effectInContext);
UIGraphicsBeginImageContextWithOptions(self.size, NO, [[UIScreen mainScreen] scale]);
CGContextRef effectOutContext = UIGraphicsGetCurrentContext();
vImage_Buffer effectOutBuffer;
effectOutBuffer.data = CGBitmapContextGetData(effectOutContext);
effectOutBuffer.width = CGBitmapContextGetWidth(effectOutContext);
effectOutBuffer.height = CGBitmapContextGetHeight(effectOutContext);
effectOutBuffer.rowBytes = CGBitmapContextGetBytesPerRow(effectOutContext);
if (hasBlur) {
CGFloat inputRadius = blurRadius * [[UIScreen mainScreen] scale];
NSUInteger radius = floor(inputRadius * 3. * sqrt(2 * M_PI) / 4 + 0.5);
if (radius % 2 != 1) {
radius += 1;
}
vImageBoxConvolve_ARGB8888(&effectInBuffer, &effectOutBuffer, NULL, 0, 0, radius, radius, 0, kvImageEdgeExtend);
vImageBoxConvolve_ARGB8888(&effectOutBuffer, &effectInBuffer, NULL, 0, 0, radius, radius, 0, kvImageEdgeExtend);
vImageBoxConvolve_ARGB8888(&effectInBuffer, &effectOutBuffer, NULL, 0, 0, radius, radius, 0, kvImageEdgeExtend);
}
BOOL effectImageBuffersAreSwapped = NO;
if (hasSaturationChange) {
CGFloat s = saturationDeltaFactor;
CGFloat floatingPointSaturationMatrix[] = {
0.0722 + 0.9278 * s, 0.0722 - 0.0722 * s, 0.0722 - 0.0722 * s, 0,
0.7152 - 0.7152 * s, 0.7152 + 0.2848 * s, 0.7152 - 0.7152 * s, 0,
0.2126 - 0.2126 * s, 0.2126 - 0.2126 * s, 0.2126 + 0.7873 * s, 0,
0, 0, 0, 1,
};
const int32_t divisor = 256;
NSUInteger matrixSize = sizeof(floatingPointSaturationMatrix)/sizeof(floatingPointSaturationMatrix[0]);
int16_t saturationMatrix[matrixSize];
for (NSUInteger i = 0; i < matrixSize; ++i) {
saturationMatrix[i] = (int16_t)roundf(floatingPointSaturationMatrix[i] * divisor);
}
if (hasBlur) {
vImageMatrixMultiply_ARGB8888(&effectOutBuffer, &effectInBuffer, saturationMatrix, divisor, NULL, NULL, kvImageNoFlags);
effectImageBuffersAreSwapped = YES;
}
else {
vImageMatrixMultiply_ARGB8888(&effectInBuffer, &effectOutBuffer, saturationMatrix, divisor, NULL, NULL, kvImageNoFlags);
}
}
if (!effectImageBuffersAreSwapped)
effectImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
if (effectImageBuffersAreSwapped)
effectImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
}
UIGraphicsBeginImageContextWithOptions(self.size, NO, [[UIScreen mainScreen] scale]);
CGContextRef outputContext = UIGraphicsGetCurrentContext();
CGContextScaleCTM(outputContext, 1.0, -1.0);
CGContextTranslateCTM(outputContext, 0, -self.size.height);
CGContextDrawImage(outputContext, imageRect, self.CGImage);
if (hasBlur) {
CGContextSaveGState(outputContext);
if (maskImage) {
CGContextClipToMask(outputContext, imageRect, maskImage.CGImage);
}
CGContextDrawImage(outputContext, imageRect, effectImage.CGImage);
CGContextRestoreGState(outputContext);
}
if (tintColor) {
CGContextSaveGState(outputContext);
CGContextSetFillColorWithColor(outputContext, tintColor.CGColor);
CGContextFillRect(outputContext, imageRect);
CGContextRestoreGState(outputContext);
}
UIImage *outputImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return outputImage;
}
You don't have to bind parameters if you use query builder or eloquent ORM. However, if you use DB::raw()
, ensure that you binding the parameters.
Try the following:
$array = array(1,2,3); $query = DB::table('offers'); $query->select('id', 'business_id', 'address_id', 'title', 'details', 'value', 'total_available', 'start_date', 'end_date', 'terms', 'type', 'coupon_code', 'is_barcode_available', 'is_exclusive', 'userinformations_id', 'is_used'); $query->leftJoin('user_offer_collection', function ($join) use ($array) { $join->on('user_offer_collection.offers_id', '=', 'offers.id') ->whereIn('user_offer_collection.user_id', $array); }); $query->get();
It is unclear if the local script uses locally set variables, functions, or aliases.
If it does this should work:
myscript.sh:
#!/bin/bash
myalias $myvar
myfunction $myvar
It uses $myvar
, myfunction
, and myalias
. Let us assume they is set locally and not on the remote machine.
Make a bash function that contains the script:
eval "myfun() { `cat myscript.sh`; }"
Set variable, function, and alias:
myvar=works
alias myalias='echo This alias'
myfunction() { echo This function "$@"; }
And "export" myfun
, myfunction
, myvar
, and myalias
to server
using env_parallel
from GNU Parallel:
env_parallel -S server -N0 --nonall myfun ::: dummy
count
is definitely the most concise and efficient way of counting the occurrence of a character in a string but I tried to come up with a solution using lambda
, something like this :
sentence = 'Mary had a little lamb'
sum(map(lambda x : 1 if 'a' in x else 0, sentence))
This will result in :
4
Also, there is one more advantage to this is if the sentence is a list of sub-strings containing same characters as above, then also this gives the correct result because of the use of in
. Have a look :
sentence = ['M', 'ar', 'y', 'had', 'a', 'little', 'l', 'am', 'b']
sum(map(lambda x : 1 if 'a' in x else 0, sentence))
This also results in :
4
But Of-course this will work only when checking occurrence of single character such as 'a'
in this particular case.
Your query should work for synonyms as well as the tables. However, you seem to expect indexes on views where there are not. Maybe is it materialized views ?
Above methods did not work for me. I got the following exception:
Exception : 'System.InvalidOperationException' in System.Windows.Forms.dll
Turns out I needed to call Invoke
on my controls first. See answer here.
change PYTHONHOME to the parent folder of the bin file of python, like /usr,which is the parent folder of /usr/bin.
Another possibility - When you Build for Archive make sure your Archive choice in your scheme is set for Distribution, not Release.
Go to Product -> Edit Scheme This brings up a new dialog.
Select Archive on the left. Make sure the build configuration is Distribution.
none of that needed.... just go to:
now and load your csv file as-is. extra columns and all. it will slice and dice and use just the log & lat columns and plot it for you on google maps.
Just happened to work at this also, use https://www.tutorialspoint.com/java_xml/java_dom_create_document.htm the example from here, and read the explanations. Also I provide you my own example:
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
Document doc = dBuilder.newDocument();
// root element
Element rootElement = doc.createElement("words");
doc.appendChild(rootElement);
while (ptbt.hasNext()) {
CoreLabel label = ptbt.next();
System.out.println(label);
m = r1.matcher(label.toString());
//System.out.println(m.find());
if (m.find() == true) {
Element w = doc.createElement("word");
w.appendChild(doc.createTextNode(label.toString()));
rootElement.appendChild(w);
}
TransformerFactory transformerFactory = TransformerFactory.newInstance();
Transformer transformer = transformerFactory.newTransformer();
DOMSource source = new DOMSource(doc);
StreamResult result = new StreamResult(new File("C:\\Users\\workspace\\Tokenizer\\tokens.xml"));
transformer.transform(source, result);
// Output to console for testing
StreamResult consoleResult = new StreamResult(System.out);
transformer.transform(source, consoleResult);
This is in the context of using the tokenizer from Stanford for Natural Language Processing, just a part of it to make an idea on how to add elements. The output is: Billbuyedapples (I've read the sentence from a file)
This is caused by non-matching Spring Boot dependencies. Check your classpath to find the offending resources. You have explicitly included version 1.1.8.RELEASE, but you have also included 3 other projects. Those likely contain different Spring Boot versions, leading to this error.
override func viewDidLoad() {
super.viewDidLoad()
self.view.backgroundColor = UIColor(patternImage: UIImage(named: "background.png"))
}
You might try searching the internet for ".htaccess Options not allowed here".
A suggestion I found (using google) is:
Check to make sure that your httpd.conf file has AllowOverride All.
A .htaccess file that works for me on Mint Linux (placed in the Laravel /public folder):
# Apache configuration file
# http://httpd.apache.org/docs/2.2/mod/quickreference.html
# Turning on the rewrite engine is necessary for the following rules and
# features. "+FollowSymLinks" must be enabled for this to work symbolically.
<IfModule mod_rewrite.c>
Options +FollowSymLinks
RewriteEngine On
</IfModule>
# For all files not found in the file system, reroute the request to the
# "index.php" front controller, keeping the query string intact
<IfModule mod_rewrite.c>
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php/$1 [L]
</IfModule>
Hope this helps you. Otherwise you could ask a question on the Laravel forum (http://forums.laravel.com/), there are some really helpful people hanging around there.
Implementing Google translate html code is very easy. Use this code on your project, hope it will help you.
<div id="google_translate_element"></div>
<script>
function googleTranslateElementInit() {
new google.translate.TranslateElement({
pageLanguage: 'en'
}, 'google_translate_element');
}
</script>
<script src="http://translate.google.com/translate_a/element.js?cb=googleTranslateElementInit"></script>
In Python 3.x, you need to import urllib.parse.quote
:
>>> import urllib.parse
>>> urllib.parse.quote("châteu", safe='')
'ch%C3%A2teu'
According to Python 2.x urllib
module documentation:
NOTE
The
urllib
module has been split into parts and renamed in Python 3 tourllib.request
,urllib.parse
, andurllib.error
.
In older versions of express, we had to use:
app.use(express.bodyparser());
because body-parser was a middleware between node and express. Now we have to use it like:
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
There is another library called arrow
really great to make manipulation on python date.
import arrow
import datetime
a = arrow.get('24052010', 'DMYYYY').date()
print(isinstance(a, datetime.date)) # True
I agree with @Bloomca. Passing the value needed from the store into the dispatch function as an argument seems simpler than exporting the store. I made an example here:
import React from "react";
import {connect} from "react-redux";
import * as actions from '../actions';
class App extends React.Component {
handleClick(){
const data = this.props.someStateObject.data;
this.props.someDispatchFunction(data);
}
render(){
return (
<div>
<div onClick={ this.handleClick.bind(this)}>Click Me!</div>
</div>
);
}
}
const mapStateToProps = (state) => {
return { someStateObject: state.someStateObject };
};
const mapDispatchToProps = (dispatch) => {
return {
someDispatchFunction:(data) => { dispatch(actions.someDispatchFunction(data))},
};
}
export default connect(mapStateToProps, mapDispatchToProps)(App);
As other said, bubbling and capturing describe in which order some nested elements receive a given event.
I wanted to point out that for the innermost element may appear something strange. Indeed, in this case the order in which the event listeners are added does matter.
In the following example, capturing for div2
will be executed first than bubbling; while bubbling for div4
will be executed first than capturing.
function addClickListener (msg, num, type) {
document.querySelector("#div" + num)
.addEventListener("click", () => alert(msg + num), type);
}
bubble = (num) => addClickListener("bubble ", num, false);
capture = (num) => addClickListener("capture ", num, true);
// first capture then bubble
capture(1);
capture(2);
bubble(2);
bubble(1);
// try reverse order
bubble(3);
bubble(4);
capture(4);
capture(3);
_x000D_
#div1, #div2, #div3, #div4 {
border: solid 1px;
padding: 3px;
margin: 3px;
}
_x000D_
<div id="div1">
div 1
<div id="div2">
div 2
</div>
</div>
<div id="div3">
div 3
<div id="div4">
div 4
</div>
</div>
_x000D_
Try initializing with null value.
private java.util.Date date2 = null;
Also private java.util.Date date2 = "";
will not work as "" is a string.
Marc response is correct. Actually, you can print the memory address for the variables print(hex(id(libvar))
and you can see the addresses are different.
# mylib.py
libvar = None
def lib_method():
global libvar
print(hex(id(libvar)))
# myapp.py
from mylib import libvar, lib_method
import mylib
lib_method()
print(hex(id(libvar)))
print(hex(id(mylib.libvar)))
You need to change the directory permission so that web server process can change the directory.
To change ownership of the directory, use chown
:
chown -R user-id:group-id /path/to/the/directory
To see which user own the web server process (change httpd
accordingly):
ps aux | grep httpd | grep -v grep
OR
ps -efl | grep httpd | grep -v grep
You have some code you want to run. Normally, when you call it you are then waiting for it to be finished before you carry on (which can cause your app to go grey/produce a spinning time for a cursor).
An alternative method is to run this code in parallel and carry on with your own work. But what if your original code needs to do different things depending on the response from the code it called? Well, in that case you can pass in the name/location of the code you want it to call when it's done. This is a "call back".
Normal code: Ask for Information->Process Information->Deal with results of Processing->Continue to do other things.
With callbacks: Ask for Information->Process Information->Continue to do other things. And at some later point->Deal with results of Processing.
Read the Request.Form NameValueCollection and process your logic accordingly:
NameValueCollection nvc = Request.Form;
string userName, password;
if (!string.IsNullOrEmpty(nvc["txtUserName"]))
{
userName = nvc["txtUserName"];
}
if (!string.IsNullOrEmpty(nvc["txtPassword"]))
{
password = nvc["txtPassword"];
}
//Process login
CheckLogin(userName, password);
... where "txtUserName" and "txtPassword" are the Names of the controls on the posting page.
I know this has been answered, but here are a couple of extension methods (for .NET 3.0+) that do the conversion. :)
/// <summary>
/// Converts a <see cref="System.Drawing.Image"/> into a WPF <see cref="BitmapSource"/>.
/// </summary>
/// <param name="source">The source image.</param>
/// <returns>A BitmapSource</returns>
public static BitmapSource ToBitmapSource(this System.Drawing.Image source)
{
System.Drawing.Bitmap bitmap = new System.Drawing.Bitmap(source);
var bitSrc = bitmap.ToBitmapSource();
bitmap.Dispose();
bitmap = null;
return bitSrc;
}
/// <summary>
/// Converts a <see cref="System.Drawing.Bitmap"/> into a WPF <see cref="BitmapSource"/>.
/// </summary>
/// <remarks>Uses GDI to do the conversion. Hence the call to the marshalled DeleteObject.
/// </remarks>
/// <param name="source">The source bitmap.</param>
/// <returns>A BitmapSource</returns>
public static BitmapSource ToBitmapSource(this System.Drawing.Bitmap source)
{
BitmapSource bitSrc = null;
var hBitmap = source.GetHbitmap();
try
{
bitSrc = System.Windows.Interop.Imaging.CreateBitmapSourceFromHBitmap(
hBitmap,
IntPtr.Zero,
Int32Rect.Empty,
BitmapSizeOptions.FromEmptyOptions());
}
catch (Win32Exception)
{
bitSrc = null;
}
finally
{
NativeMethods.DeleteObject(hBitmap);
}
return bitSrc;
}
and the NativeMethods class (to appease FxCop)
/// <summary>
/// FxCop requires all Marshalled functions to be in a class called NativeMethods.
/// </summary>
internal static class NativeMethods
{
[DllImport("gdi32.dll")]
[return: MarshalAs(UnmanagedType.Bool)]
internal static extern bool DeleteObject(IntPtr hObject);
}
Using find
:
find . -maxdepth 1 -type f
Using the -maxdepth 1
option ensures that you only look in the current directory (or, if you replace the .
with some path, that directory). If you want a full recursive listing of all files in that and subdirectories, just remove that option.
Search Results Featured snippet from the web Android | build. gradle. Gradle is a build system (open source) which is used to automate building, testing, deployment etc. ... For example, the simple task to copy some files from one directory to another can be performed by Gradle build script before the actual build process happens.
import requests
img_data = requests.get(image_url).content
with open('image_name.jpg', 'wb') as handler:
handler.write(img_data)
In my case running npm: v6.9.0
&& node: v10.16.1
on Windows
, I had to run my CLI (git bash) as administrator. Then packages were installed without any warnings/errors
The simplest way is:
echo debug_backtrace()[1]['function'];
Solution 1: Remove ONLY_FULL_GROUP_BY from mysql console
mysql > SET GLOBAL sql_mode=(SELECT REPLACE(@@sql_mode,'ONLY_FULL_GROUP_BY',''));
you can read more here
Solution 2: Remove ONLY_FULL_GROUP_BY from phpmyadmin
In addition to the accepted answer from 2009. If you can can target modern browsers, one can make use of the Object.defineProperty.
The Object.defineProperty() method defines a new property directly on an object, or modifies an existing property on an object, and returns the object. Source: Mozilla
var Foo = (function () {
function Foo() {
this._bar = false;
}
Object.defineProperty(Foo.prototype, "bar", {
get: function () {
return this._bar;
},
set: function (theBar) {
this._bar = theBar;
},
enumerable: true,
configurable: true
});
Foo.prototype.toTest = function () {
alert("my value is " + this.bar);
};
return Foo;
}());
// test instance
var test = new Foo();
test.bar = true;
test.toTest();
To see a desktop and mobile compatibility list, see Mozilla's Browser Compatibility list. Yes, IE9+ supports it as well as Safari mobile.
best bet is targeting features not devices unless you have to, bootstrap do well and you can extend on their breakpoints, for instance targeting pixel density and larger screens above 1920
I've made an attempt to implement a pull to refresh component, it's far from complete but demonstrates a possible implementation, https://github.com/johannilsson/android-pulltorefresh.
Main logic is implemented in PullToRefreshListView
that extends ListView
. Internally it controls the scrolling of a header view using The widget is now updated with support for 1.5 and later, please read the README for 1.5 support though.smoothScrollBy
(API Level 8).
In your layouts you simply add it like this.
<com.markupartist.android.widget.PullToRefreshListView
android:id="@+id/android:list"
android:layout_height="fill_parent"
android:layout_width="fill_parent"
/>
Get content with Curl php
request server support Curl function, enable in httpd.conf in folder Apache
function UrlOpener($url)
global $output;
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$output = curl_exec($ch);
curl_close($ch);
echo $output;
If get content by google cache use Curl you can use this url: http://webcache.googleusercontent.com/search?q=cache:Put your url Sample: http://urlopener.mixaz.net/
FullName like 'last' with status==’Pending’ between two dates:
db.orders.find({
createdAt:{$gt:ISODate("2017-04-25T10:08:16.111Z"),
$lt:ISODate("2017-05-05T10:08:16.111Z")},
status:"Pending",
fullName:/last/}).pretty();
status== 'Pending' and orderId LIKE ‘PHA876174’:
db.orders.find({
status:"Pending",
orderId:/PHA876174/
}).pretty();
The current windows installer from nodejs.org as of v0.6.11 (2012-02-20) will install NPM along with NodeJS.
NOTES:
%USERPROFILE%\AppData\Roaming\npm
%USERPROFILE%\AppData\Roaming\npm-cache
npm install
as that user. Some modules/utilities should be installed globally....\npm
directory to your users path yourself.To change the "global" location for all users to a more appropriate shared global location %ALLUSERSPROFILE%\(npm|npm-cache)
(do this as an administrator):
[NODE_INSTALL_PATH]\etc\
directory
npm config --global ...
actionsC:\ProgramData\npm-cache
- npm modules will go hereC:\ProgramData\npm
- binary scripts for globally installed modules will go hereC:\ProgramData\npm\node_modules
- globally installed modules will go herenpm config --global set prefix "C:\ProgramData\npm"
npm config --global set cache "C:\ProgramData\npm-cache"
C:\ProgramData\npm
to your System's Path environment variable If you want to change your user's "global" location to %LOCALAPPDATA%\(npm|npm-cache)
path instead:
C:\Users\YOURNAME\AppData\Local\npm-cache
- npm modules will go hereC:\Users\YOURNAME\AppData\Local\npm
- binary scripts for installed modules will go hereC:\Users\YOURNAME\AppData\Local\npm\node_modules
- globally installed modules will go herenpm config set prefix "C:\Users\YOURNAME\AppData\Local\npm"
npm config set cache "C:\Users\YOURNAME\AppData\Local\npm-cache"
PATH
.
setx PATH "%PATH%;C:\Users\YOURNAME\AppData\Local\npm"
For beginners, some of the npm modules I've made the most use of are as follows.
More advanced JS options...
For testing, I reach for the following tools...
Web tooling.
If you build it...
Globbing uses brackets, hence the need to escape them with a slash \
. Alternatively, the following command-line switch will disable globbing:
--globoff
(or the short-option version: -g
)
Ex:
curl --globoff https://www.google.com?test[]=1
You can set @WeekNum and @YearNum to whatever you want - in this example they are derived from the @datecol variable, which is set to GETDATE() for purposes of illustration. Once you have those values- you can calculate the date range for a week by using the following:
DECLARE @datecol datetime = GETDATE();
DECLARE @WeekNum INT
, @YearNum char(4);
SELECT @WeekNum = DATEPART(WK, @datecol)
, @YearNum = CAST(DATEPART(YY, @datecol) AS CHAR(4));
-- once you have the @WeekNum and @YearNum set, the following calculates the date range.
SELECT DATEADD(wk, DATEDIFF(wk, 6, '1/1/' + @YearNum) + (@WeekNum-1), 6) AS StartOfWeek;
SELECT DATEADD(wk, DATEDIFF(wk, 5, '1/1/' + @YearNum) + (@WeekNum-1), 5) AS EndOfWeek;
it's the css file in the new one doesn't work. Try to include the old 1.7.* css file on your header too, and try again.
Also, did you try to do a .datepicker( "show" ) right after it constructed?
For Windows Server® 2008, Windows 7, Windows Server 2003, Windows Vista®, or Windows XP run "control userpasswords2"
Click the Start button, then click Run (Windows XP, Server 2003 or below)
Type control userpasswords2 and press Enter on your keyboard.
Note: For Windows 7 and Windows Vista, this command will not run by typing it in the Serach box on the Start Menu - it must be run using the Run option. To add the Run command to your Start menu, right-click on it and choose the option to customize it, then go to the Advanced options. Check to option to add the Run command.
You will see a window of user details!
Just change the DropDownStyle
to DropDownList
. Or if you want it completely read only you can set Enabled = false
, or if you don't like the look of that I sometimes have two controls, one readonly textbox and one combobox and then hide the combo and show the textbox if it should be completely readonly and vice versa.
var foo = [ { "a" : "1" }, { "b" : "2" }, { "a" : "1" } ];
var bar = _.map(_.groupBy(foo, function (f) {
return JSON.stringify(f);
}), function (gr) {
return gr[0];
}
);
Lets break this down. First lets group the array items by their stringified value
var grouped = _.groupBy(foo, function (f) {
return JSON.stringify(f);
});
grouped
looks like:
{
'{ "a" : "1" }' = [ { "a" : "1" } { "a" : "1" } ],
'{ "b" : "2" }' = [ { "b" : "2" } ]
}
Then lets grab the first element from each group
var bar = _.map(grouped, function(gr)
return gr[0];
});
bar
looks like:
[ { "a" : "1" }, { "b" : "2" } ]
Put it all together:
var foo = [ { "a" : "1" }, { "b" : "2" }, { "a" : "1" } ];
var bar = _.map(_.groupBy(foo, function (f) {
return JSON.stringify(f);
}), function (gr) {
return gr[0];
}
);
Give this a try:
var map = {"aaa": "rrr", "bbb": "ppp"};
You can do this :
<table id="table_header">
<tr>
<td contenteditable="true">a</td>
<td contenteditable="true">b</td>
<td contenteditable="true">c</td>
</tr>
</table>
From NumberKeyListener source code. This method they use to check if char is contained in defined array of accepted characters:
protected static boolean ok(char[] accept, char c) {
for (int i = accept.length - 1; i >= 0; i--) {
if (accept[i] == c) {
return true;
}
}
return false;
}
It is similar to @ÓscarLópez solution. Might be a bit faster cause of absence of foreach iterator.
No, you can't set them to arbitrary values in one statement (unless done as part of the declaration).
You can either do it with code, something like:
myArray[0] = 1;
myArray[1] = 2;
myArray[2] = 27;
:
myArray[99] = -7;
or (if there's a formula):
for (int i = 0; i < 100; i++) myArray[i] = i + 1;
The other possibility is to keep around some templates that are set at declaration time and use them to initialise your array, something like:
static const int onceArr[] = { 0, 1, 2, 3, 4,..., 99};
static const int twiceArr[] = { 0, 2, 4, 6, 8,...,198};
:
int myArray[7];
:
memcpy (myArray, twiceArr, sizeof (myArray));
This has the advantage of (most likely) being faster and allows you to create smaller arrays than the templates. I've used this method in situations where I have to re-initialise an array fast but to a specific state (if the state were all zeros, I would just use memset
).
You can even localise it to an initialisation function:
void initMyArray (int *arr, size_t sz) {
static const int template[] = {2, 3, 5, 7, 11, 13, 17, 19, 21, ..., 9973};
memcpy (arr, template, sz);
}
:
int myArray[100];
initMyArray (myArray, sizeof(myArray));
The static array will (almost certainly) be created at compile time so there will be no run-time cost for that, and the memcpy
should be blindingly fast, likely faster than 1,229 assignment statements but very definitely less typing on your part :-).
If you are using Typescript you could check using the Date type:
const formatDate( date: Date ) => {}
Just (array)
is missing in your code before the simplexml object:
...
$xml = simplexml_load_string($string, 'SimpleXMLElement', LIBXML_NOCDATA);
$array = json_decode(json_encode((array)$xml), TRUE);
^^^^^^^
...
I looked at these, I was getting it sorted, and then it broke the binding, as above. Came up with this solution, though simpler than most of yours, it appears to do what I want to,,,
public static ObservableCollection<string> OrderThoseGroups( ObservableCollection<string> orderThoseGroups)
{
ObservableCollection<string> temp;
temp = new ObservableCollection<string>(orderThoseGroups.OrderBy(p => p));
orderThoseGroups.Clear();
foreach (string j in temp) orderThoseGroups.Add(j);
return orderThoseGroups;
}
Windows MySQL v5 throws an error but Linux and other versions only raise a warning. This needs to be fixed. WTF?
Also see an attempt to fix this as bug #19498 in the MySQL Bugtracker:
Bryce Nesbitt on April 4 2008 4:36pm:
On MS Windows the "no DEFAULT" rule is an error, while on other platforms it is often a warning. While not a bug, it's possible to get trapped by this if you write code on a lenient platform, and later run it on a strict platform:
Personally, I do view this as a bug. Searching for "BLOB/TEXT column can't have a default value" returns about 2,940 results on Google. Most of them are reports of incompatibilities when trying to install DB scripts that worked on one system but not others.
I am running into the same problem now on a webapp I'm modifying for one of my clients, originally deployed on Linux MySQL v5.0.83-log. I'm running Windows MySQL v5.1.41. Even trying to use the latest version of phpMyAdmin to extract the database, it doesn't report a default for the text column in question. Yet, when I try running an insert on Windows (that works fine on the Linux deployment) I receive an error of no default on ABC column. I try to recreate the table locally with the obvious default (based on a select of unique values for that column) and end up receiving the oh-so-useful BLOB/TEXT column can't have a default value.
Again, not maintaining basic compatability across platforms is unacceptable and is a bug.
How to disable strict mode in MySQL 5 (Windows):
Edit /my.ini and look for line
sql-mode="STRICT_TRANS_TABLES,NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION"
Replace it with
sql_mode='MYSQL40'
Restart the MySQL service (assuming that it is mysql5)
net stop mysql5
net start mysql5
If you have root/admin access you might be able to execute
mysql_query("SET @@global.sql_mode='MYSQL40'");
You can also destroy the old datatable
by using the following code before creating the new datatable
:
$("#example").dataTable().fnDestroy();
It seems that I found a solution to my problem. Very good explanations are given here and here. Here is my example:
pulic class MyActivity extends FragmentActivity{
private ViewPager pager;
private TitlePageIndicator indicator;
private TabsAdapter adapter;
private Bundle savedInstanceState;
@Override
public void onCreate(Bundle savedInstanceState) {
....
this.savedInstanceState = savedInstanceState;
pager = (ViewPager) findViewById(R.id.pager);;
indicator = (TitlePageIndicator) findViewById(R.id.indicator);
adapter = new TabsAdapter(getSupportFragmentManager(), false);
if (savedInstanceState == null){
adapter.addFragment(new FirstFragment());
adapter.addFragment(new SecondFragment());
}else{
Integer count = savedInstanceState.getInt("tabsCount");
String[] titles = savedInstanceState.getStringArray("titles");
for (int i = 0; i < count; i++){
adapter.addFragment(getFragment(i), titles[i]);
}
}
indicator.notifyDataSetChanged();
adapter.notifyDataSetChanged();
// push first task
FirstTask firstTask = new FirstTask(MyActivity.this);
// set first fragment as listener
firstTask.setTaskListener((TaskListener) getFragment(0));
firstTask.execute();
}
private Fragment getFragment(int position){
return savedInstanceState == null ? adapter.getItem(position) : getSupportFragmentManager().findFragmentByTag(getFragmentTag(position));
}
private String getFragmentTag(int position) {
return "android:switcher:" + R.id.pager + ":" + position;
}
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putInt("tabsCount", adapter.getCount());
outState.putStringArray("titles", adapter.getTitles().toArray(new String[0]));
}
indicator.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
@Override
public void onPageSelected(int position) {
Fragment currentFragment = adapter.getItem(position);
((Taskable) currentFragment).executeTask();
}
@Override
public void onPageScrolled(int i, float v, int i1) {}
@Override
public void onPageScrollStateChanged(int i) {}
});
The main idea in this code is that, while running your application normally, you create new fragments and pass them to the adapter. When you are resuming your application fragment manager already has this fragment's instance and you need to get it from fragment manager and pass it to the adapter.
UPDATE
Also, it is a good practice when using fragments to check isAdded before getActivity() is called. This helps avoid a null pointer exception when the fragment is detached from the activity. For example, an activity could contain a fragment that pushes an async task. When the task is finished, the onTaskComplete listener is called.
@Override
public void onTaskComplete(List<Feed> result) {
progress.setVisibility(View.GONE);
progress.setIndeterminate(false);
list.setVisibility(View.VISIBLE);
if (isAdded()) {
adapter = new FeedAdapter(getActivity(), R.layout.feed_item, result);
list.setAdapter(adapter);
adapter.notifyDataSetChanged();
}
}
If we open the fragment, push a task, and then quickly press back to return to a previous activity, when the task is finished, it will try to access the activity in onPostExecute() by calling the getActivity() method. If the activity is already detached and this check is not there:
if (isAdded())
then the application crashes.
MSBuild usually works, but I've run into difficulties before. You may have better luck with
devenv YourSolution.sln /Build
I also ran into this situation and figured out how to do it using FrameLayout. The following output is produced by the code given below.
<FrameLayout
android:layout_width="match_parent"
android:layout_height="wrap_content" >
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/contactbook_icon"
android:layout_gravity="center" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="140"
android:textSize="12dp"
android:textColor="#FFFFFF"
android:layout_gravity="bottom|right"
android:layout_margin="15dp" />
</FrameLayout>
Change the margin value to adjust the text position over the image. Removing margin might make the text to go out of the view sometimes.
First the facts, neither is better. As you already mentioned, Tomcat provides a servlet container that supports the Servlet specification (Tomcat 7 supports Servlet 3.0). JBoss AS, a 'complete' application server supports Java EE 6 (including Servlet 3.0) in its current version.
Tomcat is fairly lightweight and in case you need certain Java EE features beyond the Servlet API, you can easily enhance Tomcat by providing the required libraries as part of your application. For example, if you need JPA features you can include Hibernate or OpenEJB and JPA works nearly out of the box.
How to decide whether to use Tomcat or a full stack Java EE
application server:
When starting your project you should have an idea what it requires. If you're in a large enterprise environment JBoss (or any other Java EE server) might be the right choice as it provides built-in support for e.g:
In my opinion Tomcat is a very good fit if it comes to web centric, user facing applications. If backend integration comes into play, a Java EE application server should be (at least) considered. Last but not least, migrating a WAR developed for Tomcat to JBoss should be a 1 day excercise.
Second, you should also take the usage inside your environment into account. In case your organization already runs say 1,000 JBoss instances, you might always go with that regardless of your concrete requirements (consider aspects like cost for operations or upskilling). Of course, this applies vice versa.
my 2 cent
According to my test,
implements OnItemClickListener -> works.
setOnItemClickListener -> works.
ListView is clickable by default (API 19)
The important thing is, "click" only works to TextView (if you choose simple_list_item_1.xml as item). That means if you provide text data for the ListView, "click" works when you click on text area. Click on empty area does not trigger "click event".
In Angular 8 , ViewChild takes 2 parameters
@ViewChild(ChildDirective, {static: false}) Component
In case you want to add years to specific date besides today's date using either years, or months, or days. You can do the following
var christmas2000 = new Date(2000, 12, 25);
christmas2000.setFullYear(christmas2000.getFullYear() + 5); // using year: next 5 years
christmas2000.setFullYear(christmas2000.getMonth() + 24); // using months: next 24 months
christmas2000.setFullYear(christmas2000.getDay() + 365); // using days: next 365 months
Just use the PHP function array_key_exists()
<?php
$search_array = array('first' => 1, 'second' => 4);
if (array_key_exists('first', $search_array)) {
echo "The 'first' element is in the array";
}
?>
Using python and telethon it's very easy to get chat id. This solution is best for those who work with telegram API.
If you don't have telethon, run this:
pip install telethon
If you don't have a registered app with telegram, register one: The link is this: https://my.telegram.org/
Then run the following code:
from telethon import InteractiveTelegramClient
from telethon.utils.tl_utils import get_display_name
client = InteractiveTelegramClient('session_id', 'YOUR_PHONE_NUMBER', api_id=1234YOURAPI_ID, api_hash='YOUR_API_HASH')
dialog_count = 10
dialogs, entities = client.get_dialogs(dialog_count)
for i, entity in enumerate(entities):
i += 1 # 1-based index
print('{}. {}. id: {}'.format(i, get_display_name(entity), entity.id))
You may want to send a message to your group so the group show up in top of the list.
To specify any additional asset folder I've used this with my Gradle. This adds moreAssets
, a folder in the project root, to the assets.
android {
sourceSets {
main.assets.srcDirs += '../moreAssets'
}
}
One more solution is to use contains which will return true or false
_.contains($(".right-tree").css("background-image"), "stage1")
Hope this helps
For a quick solution, you can use AtomicInteger or any of the atomic variables which will let you change the value inside the method using the inbuilt methods. Here is sample code:
import java.util.concurrent.atomic.AtomicInteger;
public class PrimitivePassByReferenceSample {
/**
* @param args
*/
public static void main(String[] args) {
AtomicInteger myNumber = new AtomicInteger(0);
System.out.println("MyNumber before method Call:" + myNumber.get());
PrimitivePassByReferenceSample temp = new PrimitivePassByReferenceSample() ;
temp.changeMyNumber(myNumber);
System.out.println("MyNumber After method Call:" + myNumber.get());
}
void changeMyNumber(AtomicInteger myNumber) {
myNumber.getAndSet(100);
}
}
Output:
MyNumber before method Call:0
MyNumber After method Call:100
You can find a whole bunch of Linq examples in visual studio.
Just select Help -> Samples
, and then unzip the Linq samples.
Open the linq samples solution and open the LinqSamples.cs of the SampleQueries project.
The answer you are looking for is in method Linq14:
int[] numbersA = { 0, 2, 4, 5, 6, 8, 9 };
int[] numbersB = { 1, 3, 5, 7, 8 };
var pairs =
from a in numbersA
from b in numbersB
where a < b
select new {a, b};
Thanks! Tomer Ben David. it helped me. as I am doing pip install in demo folder as you mentioned npm install
<groupId>org.codehaus.mojo</groupId>
<artifactId>exec-maven-plugin</artifactId>
<version>1.3.2</version>
<executions>
<execution>
<goals>
<goal>exec</goal>
</goals>
</execution>
</executions>
<configuration>
<executable>pip</executable>
<arguments><argument>install</argument></arguments>
<workingDirectory>${project.build.directory}/Demo</workingDirectory>
</configuration>