There are lots of explanation of Jmeter Summary, I have been using this tool from quite some time for generating performance testing report with relevant data. The explanation available on below link is right from the field experience:
Jmeter:Understanding Summary Report
This is one of the most useful report generated by Jmeter to undertstand the load test result.
# Label: Name of HTTP sample request send to server
# Samples : This Captures the total number of samples pushed to server. Suppose you put a Loop Controller to run it 5 times this particular request and then 2 iteration(Called Loop Count in Thread Group)is set and load test is run for 100 users, then the count that will be displayed here .... 1*5*2 * 100 =1000. Total = total number of samples send to server during entire run.
# Average : It's an average response time for a particular http request. This response time is in millisecond, and an average for 5 loops in two iteration for 100 users. Total = Average of total average of samples, means add all averages for all samples and divide by number of samples
# Min : Minmum time spend by sample requests send for this label. The total equals to the minimum time across all samples.
# Max : Maximum tie spend by sample requests send for this label The total equals to the maxmimum time across all samples.
# Std. Dev. : Knowing the standard deviation of your data set tells you how densely the data points are clustered around the mean. The smaller the standard deviation, the more consistent the data. Standard deviation should be less than or equal to half of the average time for a label. If it is more than that, then it means that something is wrong. you need to figure out the problem and fix it. https://en.wikipedia.org/wiki/Standard_deviation Total is euqals to highest deviation across all samples.
# Error: Total percentage of erros found for a particular sample request. 0.0% shows that all requests completed successfully. Total equals to percentage of errors samples in all samples (Total Samples)
# Throughput: Hits/sec, or total number of request per unit of time(sec, mins, hr) send to server during test.
endTime = lastSampleStartTime + lastSampleLoadTime startTime = firstSampleStartTime converstion = unit time conversion value Throughput = Numrequests / ((endTime - startTime)*conversion)
# KB/sec : Its mesuring throughput rate in Kilobytes per second.
# Avg. Bytes: Avegare of total bytes of data downloaded from server. Totals is average bytes across all samples.
It's explained in great detail in the docs, but I'll try to summarize:
matching
means git push
will push all your local branches to the ones with the same name on the remote. This makes it easy to accidentally push a branch you didn't intend to.
simple
means git push
will push only the current branch to the one that git pull
would pull from, and also checks that their names match. This is a more intuitive behavior, which is why the default is getting changed to this.
This setting only affects the behavior of your local client, and can be overridden by explicitly specifying which branches you want to push on the command line. Other clients can have different settings, it only affects what happens when you don't specify which branches you want to push.
If it's just a true/false test, have your function return 0
for success, and return 1
for failure. The test would then be:
if function_name; then
do something
else
error condition
fi
You cannot really maintain state in a filter
/lambda
expression (unless abusing the global namespace). You can however achieve something similar using the accumulated result being passed around in a reduce()
expression:
>>> f = lambda a, b: (a.append(b) or a) if (b not in a) else a
>>> input = ["foo", u"", "bar", "", "", "x"]
>>> reduce(f, input, [])
['foo', u'', 'bar', 'x']
>>>
You can, of course, tweak the condition a bit. In this case it filters out duplicates, but you can also use a.count("")
, for example, to only restrict empty strings.
Needless to say, you can do this but you really shouldn't. :)
Lastly, you can do anything in pure Python lambda
: http://vanderwijk.info/blog/pure-lambda-calculus-python/
Use Math.floor()
:
var f = 20.536;
var i = Math.floor(f); // 20
I wondered if it would be possible to avoid some of the disadvantages of using global variables (see e.g. http://wiki.c2.com/?GlobalVariablesAreBad) by using a class namespace rather than a global/module namespace to pass values of variables. The following code indicates that the two methods are essentially identical. There is a slight advantage in using class namespaces as explained below.
The following code fragments also show that attributes or variables may be dynamically created and deleted in both global/module namespaces and class namespaces.
wall.py
# Note no definition of global variables
class router:
""" Empty class """
I call this module 'wall' since it is used to bounce variables off of. It will act as a space to temporarily define global variables and class-wide attributes of the empty class 'router'.
source.py
import wall
def sourcefn():
msg = 'Hello world!'
wall.msg = msg
wall.router.msg = msg
This module imports wall and defines a single function sourcefn
which defines a message and emits it by two different mechanisms, one via globals and one via the router function. Note that the variables wall.msg
and wall.router.message
are defined here for the first time in their respective namespaces.
dest.py
import wall
def destfn():
if hasattr(wall, 'msg'):
print 'global: ' + wall.msg
del wall.msg
else:
print 'global: ' + 'no message'
if hasattr(wall.router, 'msg'):
print 'router: ' + wall.router.msg
del wall.router.msg
else:
print 'router: ' + 'no message'
This module defines a function destfn
which uses the two different mechanisms to receive the messages emitted by source. It allows for the possibility that the variable 'msg' may not exist. destfn
also deletes the variables once they have been displayed.
main.py
import source, dest
source.sourcefn()
dest.destfn() # variables deleted after this call
dest.destfn()
This module calls the previously defined functions in sequence. After the first call to dest.destfn
the variables wall.msg
and wall.router.msg
no longer exist.
The output from the program is:
global: Hello world!
router: Hello world!
global: no message
router: no message
The above code fragments show that the module/global and the class/class variable mechanisms are essentially identical.
If a lot of variables are to be shared, namespace pollution can be managed either by using several wall-type modules, e.g. wall1, wall2 etc. or by defining several router-type classes in a single file. The latter is slightly tidier, so perhaps represents a marginal advantage for use of the class-variable mechanism.
What about something like :
angle = angle % 360;
Just add to a variable encode('utf-8')
agent_contact.encode('utf-8')
Remove existing origin and add new origin to your project directory
>$ git remote show origin
>$ git remote rm origin
>$ git add .
>$ git commit -m "First commit"
>$ git remote add origin Copied_origin_url
>$ git remote show origin
>$ git push origin master
Divide and Conquer
Divide and Conquer works by dividing the problem into sub-problems, conquer each sub-problem recursively and combine these solutions.
Dynamic Programming
Dynamic Programming is a technique for solving problems with overlapping subproblems. Each sub-problem is solved only once and the result of each sub-problem is stored in a table ( generally implemented as an array or a hash table) for future references. These sub-solutions may be used to obtain the original solution and the technique of storing the sub-problem solutions is known as memoization.
You may think of DP = recursion + re-use
A classic example to understand the difference would be to see both these approaches towards obtaining the nth fibonacci number. Check this material from MIT.
Divide and Conquer approach
Dynamic Programming Approach
This may be a little too short, but for my own private use, it works great
read -n 1 -p "Push master upstream? [Y/n] " reply;
if [ "$reply" != "" ]; then echo; fi
if [ "$reply" = "${reply#[Nn]}" ]; then
git push upstream master
fi
The read -n 1
just reads one character. No need to hit enter. If it's not a 'n' or 'N', it is assumed to be a 'Y'. Just pressing enter means Y too.
(as for the real question: make that a bash script and change your alias to point to that script instead of what is was pointing to before)
Jon's answer didn't work for me as I got a compiler error CS0453 C# The type must be a non-nullable value type in order to use it as parameter 'T' in the generic type or method
This worked for me though:
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<SomeObject>().HasOptional(m => m.somefield);
base.OnModelCreating(modelBuilder);
}
I use
barbeque
, it's great, and supports a very wide range of different barcode formats.
See if you like
its API
.
Sample API:
public static Barcode createCode128(java.lang.String data) throws BarcodeException
Creates a Code 128 barcode that dynamically switches between character sets to give the smallest possible encoding. This will encode all numeric characters, upper and lower case alpha characters and control characters from the standard ASCII character set. The size of the barcode created will be the smallest possible for the given data, and use of this "optimal" encoding will generally give smaller barcodes than any of the other 3 "vanilla" encodings.
I'm not sure anyone else actually addressed your question directly which is code being viewed from the browser's View Source command.
As other have said, there is no way to protect javascript intended to run in a browser from a determined viewer. If the browser can run it, then any determined person can view/run it also.
But, if you put your javascript in an external javascript file that is included with:
<script type="text/javascript" src="http://mydomain.com/xxxx.js"></script>
tags, then the javascript code won't be immediately visible with the View Source command - only the script tag itself will be visible that way. That doesn't mean that someone can't just load that external javascript file to see it, but you did ask how to keep it out of the browser's View Source command and this will do it.
If you wanted to really make it more work to view the source, you would do all of the following:
With all that said, I think you should focus on performance, reliability and making your app great. If you absolutely have to protect some algorithm, put it on the server, but other than that, compete on being the best at you do, not by having secrets. That's ultimately how success works on the web anyway.
Booting from CD to rescue the installation and editing /etc/selinux/config: changed SELINUX from enforcing to permissive. Rebooted and system booted
/etc/selinux/config
before change:
SELINUX=enforcing and SELINUXTYPE=permissive
/etc/selinux/config
after change:
SELINUX=permissive and SELINUXTYPE=permissive
I'm posting this answer to give insights into multiple ways available for you to change the project on GCP. I will also explain when to use each of the following options.
Option 1: Cloud CLI - Set Project Property on Cloud SDK on CLI
Use this option, if you want to run all Cloud CLI commands on a specific project.
gcloud config set project <Project-ID>
With this, the selected project on Cloud CLI
will change, and the currently selected project is highlighted in yellow.
Option 2: Cloud CLI - Set Project ID flag with most Commands
Use this command if you want to execute commands on multiple projects. Eg: create clusters in one project, and use the same configs to create on another project. Use the following flag for each command.
--project <Project-ID>
Option 3: Cloud CLI - Initialize the Configurations in CLI
This option can be used if you need separate configurations for different projects/accounts. With this, you can easily switch between configurations by using the activate
command. Eg: gcloud config configurations activate <congif-name>
.
gcloud init
Option 4: Open new Cloud Shell with your preferred project
This is preferred if you don't like to work with CLI commands. Press the PLUS +
button for a new tab.
Next, select your preferred project.
LayoutParams lparams = new LayoutParams(
LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
TextView tv=new TextView(this);
tv.setLayoutParams(lparams);
tv.setText("test");
this.m_vwJokeLayout.addView(tv);
You can change lparams according to your needs
The EntityManager doesn't flush change automatically by default. You should use the following option with your statement of query:
@Modifying(clearAutomatically = true)
@Query("update RssFeedEntry feedEntry set feedEntry.read =:isRead where feedEntry.id =:entryId")
void markEntryAsRead(@Param("entryId") Long rssFeedEntryId, @Param("isRead") boolean isRead);
if the other div is sibling/child, or any combination of, of the parent yes
.showme{ _x000D_
display: none;_x000D_
}_x000D_
.showhim:hover .showme{_x000D_
display : block;_x000D_
}_x000D_
.showhim:hover .hideme{_x000D_
display : none;_x000D_
}_x000D_
.showhim:hover ~ .hideme2{ _x000D_
display:none;_x000D_
}
_x000D_
<div class="showhim">_x000D_
HOVER ME_x000D_
<div class="showme">hai</div> _x000D_
<div class="hideme">bye</div>_x000D_
</div>_x000D_
<div class="hideme2">bye bye</div>
_x000D_
I am not sure what you are trying to do. You can implement a do-while loop like this:
while True:
stuff()
if fail_condition:
break
Or:
stuff()
while not fail_condition:
stuff()
What are you doing trying to use a do while loop to print the stuff in the list? Why not just use:
for i in l:
print i
print "done"
Update:
So do you have a list of lines? And you want to keep iterating through it? How about:
for s in l:
while True:
stuff()
# use a "break" instead of s = i.next()
Does that seem like something close to what you would want? With your code example, it would be:
for s in some_list:
while True:
if state is STATE_CODE:
if "//" in s:
tokens.add( TOKEN_COMMENT, s.split( "//" )[1] )
state = STATE_COMMENT
else :
tokens.add( TOKEN_CODE, s )
if state is STATE_COMMENT:
if "//" in s:
tokens.append( TOKEN_COMMENT, s.split( "//" )[1] )
break # get next s
else:
state = STATE_CODE
# re-evaluate same line
# continues automatically
if(name.getText().hashCode() != 0){
JOptionPane.showMessageDialog(null, "not empty");
}
else{
JOptionPane.showMessageDialog(null, "empty");
}
There looks to be an issue when the time of the phone/emulator is different to the one of the server (where react-native packager is running). In my case there was a 1 minute difference between the time of the phone and the computer. After synchronizing them (didn't do anything fancy, the phone was set on manual time, and I just set it to use the network(sim) provided time), everything worked fine. This github issue helped me find the problem.
wget -r ftp://url
Work perfectly for Redhat and Ubuntu
If you call it the way you had it...
$('.leadtoscore').click(add_event('shot'));
...you would need to have add_event()
return a function, like...
function add_event(param) {
return function() {
// your code that does something with param
alert( param );
};
}
The function is returned and used as the argument for .click()
.
Requirements:
moment().fromNow()
functionality."today"
, "yesterday"
, "tomorrow"
, etc.Solution:
// call this function, passing-in your date
function dateToFromNowDaily( myDate ) {
// get from-now for this date
var fromNow = moment( myDate ).fromNow();
// ensure the date is displayed with today and yesterday
return moment( myDate ).calendar( null, {
// when the date is closer, specify custom values
lastWeek: '[Last] dddd',
lastDay: '[Yesterday]',
sameDay: '[Today]',
nextDay: '[Tomorrow]',
nextWeek: 'dddd',
// when the date is further away, use from-now functionality
sameElse: function () {
return "[" + fromNow + "]";
}
});
}
NB: From version 2.14.0, the formats argument to the calendar function can be a callback, see http://momentjs.com/docs/#/displaying/calendar-time/.
I've written a simple jQuery plugin - alterClass, that does wildcard class removal. Will optionally add classes too.
$( '#foo' ).alterClass( 'foo-* bar-*', 'foobar' )
The correct options are (in increasing order of recommendation):
# Single POSIX test command with -o operator (not recommended anymore).
# Quotes strongly recommended to guard against empty or undefined variables.
while [ "$stats" -gt 300 -o "$stats" -eq 0 ]
# Two POSIX test commands joined in a list with ||.
# Quotes strongly recommended to guard against empty or undefined variables.
while [ "$stats" -gt 300 ] || [ "$stats" -eq 0 ]
# Two bash conditional expressions joined in a list with ||.
while [[ $stats -gt 300 ]] || [[ $stats -eq 0 ]]
# A single bash conditional expression with the || operator.
while [[ $stats -gt 300 || $stats -eq 0 ]]
# Two bash arithmetic expressions joined in a list with ||.
# $ optional, as a string can only be interpreted as a variable
while (( stats > 300 )) || (( stats == 0 ))
# And finally, a single bash arithmetic expression with the || operator.
# $ optional, as a string can only be interpreted as a variable
while (( stats > 300 || stats == 0 ))
Some notes:
Quoting the parameter expansions inside [[ ... ]]
and ((...))
is optional; if the variable is not set, -gt
and -eq
will assume a value of 0.
Using $
is optional inside (( ... ))
, but using it can help avoid unintentional errors. If stats
isn't set, then (( stats > 300 ))
will assume stats == 0
, but (( $stats > 300 ))
will produce a syntax error.
As far as I know there is no option to create global configuration for java applications. You always create a duplicate of the configuration.
Also, if you are using PDE (for plugin development), you can create target platform using windows -> Preferences -> Plug-in development -> Target Platform. Edit has options for program/vm arguments.
Hope this helps
npm ws was the answer for me. I found it less intrusive and more straight forward. With it was also trivial to mix websockets with rest services. Shared simple code on this post.
var WebSocketServer = require("ws").Server;
var http = require("http");
var express = require("express");
var port = process.env.PORT || 5000;
var app = express();
app.use(express.static(__dirname+ "/../"));
app.get('/someGetRequest', function(req, res, next) {
console.log('receiving get request');
});
app.post('/somePostRequest', function(req, res, next) {
console.log('receiving post request');
});
app.listen(80); //port 80 need to run as root
console.log("app listening on %d ", 80);
var server = http.createServer(app);
server.listen(port);
console.log("http server listening on %d", port);
var userId;
var wss = new WebSocketServer({server: server});
wss.on("connection", function (ws) {
console.info("websocket connection open");
var timestamp = new Date().getTime();
userId = timestamp;
ws.send(JSON.stringify({msgType:"onOpenConnection", msg:{connectionId:timestamp}}));
ws.on("message", function (data, flags) {
console.log("websocket received a message");
var clientMsg = data;
ws.send(JSON.stringify({msg:{connectionId:userId}}));
});
ws.on("close", function () {
console.log("websocket connection close");
});
});
console.log("websocket server created");
Depending on your definition of shortly, you could use one of the following options:
try: int(your_input); except ValueError: # ...
your_input.isdigit()
parse
which is kind of the opposite of format
In my case I am running 3 nodes in VM's by using Hyper-V. By using the following steps I was able to "restart" the cluster after restarting all VM's.
(Optional) Swap off
$ swapoff -a
You have to restart all Docker containers
$ docker restart $(docker ps -a -q)
Check the nodes status after you performed step 1 and 2 on all nodes (the status is NotReady)
$ kubectl get nodes
Restart the node
$ systemctl restart kubelet
Check again the status (now should be in Ready status)
Note: I do not know if it does metter the order of nodes restarting, but I choose to start with the k8s master node and after with the minions. Also it will take a little bit to change the node state from NotReady to Ready
Old tread...? Well, someone may bump into this...
Please check out http://telamenta.com/techarticle/php-explode-newlines-and-you
Rather than using:
$values = explode("\n", $value_string);
Use a safer method like:
$values = preg_split('/[\n\r]+/', $value_string);
you don't need to use *ngIf if you use ng-container
<ng-container [ngTemplateOutlet]="myTemplate === 'first' ? first : myTemplate ===
'second' ? second : third"></ng-container>
<ng-template #first>first</ng-template>
<ng-template #second>second</ng-template>
<ng-template #third>third</ng-template>
The documentation on CREATE EVENT is quite good, but it takes a while to get it right.
You have two problems, first, making the event recur, second, making it run at 13:00 daily.
This example creates a recurring event.
CREATE EVENT e_hourly
ON SCHEDULE
EVERY 1 HOUR
COMMENT 'Clears out sessions table each hour.'
DO
DELETE FROM site_activity.sessions;
When in the command-line MySQL client, you can:
SHOW EVENTS;
This lists each event with its metadata, like if it should run once only, or be recurring.
The second problem: pointing the recurring event to a specific schedule item.
By trying out different kinds of expression, we can come up with something like:
CREATE EVENT IF NOT EXISTS `session_cleaner_event`
ON SCHEDULE
EVERY 13 DAY_HOUR
COMMENT 'Clean up sessions at 13:00 daily!'
DO
DELETE FROM site_activity.sessions;
Check out the jQuery dimensions plugin
If dgv(11, dgv.CurrentRow.Index).Selected = True Then
dgv.Rows.RemoveAt(dgv.CurrentRow.Index)
Else
Exit Sub
End If
In java there is a length
field that you can use on any array to find out it's size:
String[] s = new String[10];
System.out.println(s.length);
This expression (inspired from Mike, above) seems to catch all duplicates, triplicates, etc, including the ones at the end of the string, which most of the others don't:
/(^|\s+)(\S+)(($|\s+)\2)+/g, "$1$2")
I know the question asked to match duplicates only, but a triplicate is just 2 duplicates next to each other :)
First, I put (^|\s+)
to make sure it starts with a full word, otherwise "child's steak" would go to "child'steak" (the "s"'s would match). Then, it matches all full words ((\b\S+\b)
), followed by an end of string ($
) or a number of spaces (\s+
), the whole repeated more than once.
I tried it like this and it worked well:
var s = "here here here here is ahi-ahi ahi-ahi ahi-ahi joe's joe's joe's joe's joe's the result result result";
print( s.replace( /(\b\S+\b)(($|\s+)\1)+/g, "$1"))
--> here is ahi-ahi joe's the result
Update: This answer is very old. gridExtra::grid.arrange()
is now the recommended approach.
I leave this here in case it might be useful.
Stephen Turner posted the arrange()
function on Getting Genetics Done blog (see post for application instructions)
vp.layout <- function(x, y) viewport(layout.pos.row=x, layout.pos.col=y)
arrange <- function(..., nrow=NULL, ncol=NULL, as.table=FALSE) {
dots <- list(...)
n <- length(dots)
if(is.null(nrow) & is.null(ncol)) { nrow = floor(n/2) ; ncol = ceiling(n/nrow)}
if(is.null(nrow)) { nrow = ceiling(n/ncol)}
if(is.null(ncol)) { ncol = ceiling(n/nrow)}
## NOTE see n2mfrow in grDevices for possible alternative
grid.newpage()
pushViewport(viewport(layout=grid.layout(nrow,ncol) ) )
ii.p <- 1
for(ii.row in seq(1, nrow)){
ii.table.row <- ii.row
if(as.table) {ii.table.row <- nrow - ii.table.row + 1}
for(ii.col in seq(1, ncol)){
ii.table <- ii.p
if(ii.p > n) break
print(dots[[ii.table]], vp=vp.layout(ii.table.row, ii.col))
ii.p <- ii.p + 1
}
}
}
SELECT (to_date('02-JAN-2013') - to_date('02-JAN-2012')) days_between
FROM dual
/
Zsh comes with colored prompts builtin. Try
autoload -U promptinit && promptinit
and then prompt -l
lists available prompts, -p fire
previews the "fire" prompt, -s fire
sets it.
When you are ready to add a prompt add something like this below the autoload line above:
prompt fade red
http://jsfiddle.net/Bq6eK/215/
I did not modify your code for this solution, I wrote my own instead. My solution isn't quite what you asked for, but maybe you could build on it with existing knowledge. I commented the code as well so you know what exactly I'm doing with the changes.
As a solution to "avoid setting the height in JavaScript", I just made 'maxHeight' a parameter in the JS function called toggleHeight. Now it can be set in the HTML for each div of class expandable.
I'll say this up front, I'm not super experienced with front-end languages, and there's an issue where I need to click the 'Show/hide' button twice initially before the animation starts. I suspect it's an issue with focus.
The other issue with my solution is that you can actually figure out what the hidden text is without pressing the show/hide button just by clicking in the div and dragging down, you can highlight the text that's not visible and paste it to a visible space.
My suggestion for a next step on top of what I've done is to make it so that the show/hide button changes dynamically. I think you can figure out how to do that with what you already seem to know about showing and hiding text with JS.
$('a[href$="ABC"]')...
Selector documentation can be found at http://docs.jquery.com/Selectors
For attributes:
= is exactly equal
!= is not equal
^= is starts with
$= is ends with
*= is contains
~= is contains word
|= is starts with prefix (i.e., |= "prefix" matches "prefix-...")
So I just had this same issue, but a little different. I already had the icon as an object as Philippe Boissonneault suggests, but I was using an SVG image.
What solved it for me was:
Switch from an SVG image to a PNG and following Catherine Nyo on having an image that is double the size of what you will use.
Using Underscore.js or lodash.js
_.intersection( [0,345,324] , [1,0,324] ) // gives [0,324]
sqlplus user/password@sid < sqlfile.sql
This will also work from the DOS command line. In this case the file sqlfile.sql contains the SQL you wish to execute.
code to select dropdown using xpath
Select select = new
Select(driver.findElement(By.xpath("//select[@id='periodId']));
code to select particaular option using selectByVisibleText
select.selectByVisibleText(Last 52 Weeks);
Use CURRENT_TIMESTAMP (or GETDATE() on archaic versions of SQL Server).
Just to throw in another example, the generic version of Class (Class<T>
) allows one to write generic functions such as the one below.
public static <T extends Enum<T>>Optional<T> optionalFromString(
@NotNull Class<T> clazz,
String name
) {
return Optional<T> opt = Optional.ofNullable(name)
.map(String::trim)
.filter(StringUtils::isNotBlank)
.map(String::toUpperCase)
.flatMap(n -> {
try {
return Optional.of(Enum.valueOf(clazz, n));
} catch (Exception e) {
return Optional.empty();
}
});
}
A couple of additional points re use of vector
here.
Unlike ArrayList
and Array
in Java, you don't need to do anything special to treat a vector
as an array - the underlying storage in C++ is guaranteed to be contiguous and efficiently indexable.
Unlike ArrayList
, a vector
can efficiently hold primitive types without encapsulation as a full-fledged object.
When removing items from a vector
, be aware that the items above the removed item have to be moved down to preserve contiguous storage. This can get expensive for large containers.
Make sure if you store complex objects in the vector
that their copy constructor and assignment operators are efficient. Under the covers, C++ STL uses these during container housekeeping.
Advice about reserve()
ing storage upfront (ie. at vector construction or initialilzation time) to minimize memory reallocation on later extension carries over from Java to C++.
Since PostgreSQL 9.1 there is the convenient FOREACH
:
DO
$do$
DECLARE
m varchar[];
arr varchar[] := array[['key1','val1'],['key2','val2']];
BEGIN
FOREACH m SLICE 1 IN ARRAY arr
LOOP
RAISE NOTICE 'another_func(%,%)',m[1], m[2];
END LOOP;
END
$do$
Solution for older versions:
DO
$do$
DECLARE
arr varchar[] := '{{key1,val1},{key2,val2}}';
BEGIN
FOR i IN array_lower(arr, 1) .. array_upper(arr, 1)
LOOP
RAISE NOTICE 'another_func(%,%)',arr[i][1], arr[i][2];
END LOOP;
END
$do$
Also, there is no difference between varchar[]
and varchar[][]
for the PostgreSQL type system. I explain in more detail here.
The DO
statement requires at least PostgreSQL 9.0, and LANGUAGE plpgsql
is the default (so you can omit the declaration).
You can also use short trick to use image and color both like this :-
body {
background:#000 url('images/checked.png');
}
I'm coming from a SQL Server background also and spent the past 2 weeks figuring out how to run scripts like this in IBM Data Studio. Hope it helps.
CREATE VARIABLE v_lookupid INTEGER DEFAULT (4815162342); --where 4815162342 is your variable data
SELECT * FROM DB1.PERSON WHERE PERSON_ID = v_lookupid;
SELECT * FROM DB1.PERSON_DATA WHERE PERSON_ID = v_lookupid;
SELECT * FROM DB1.PERSON_HIST WHERE PERSON_ID = v_lookupid;
DROP VARIABLE v_lookupid;
$ foo="/some/directory/file"
$ [ ${foo:0:1} == "/" ] && echo 1 || echo 0
1
$ foo="[email protected]:/some/directory/file"
$ [ ${foo:0:1} == "/" ] && echo 1 || echo 0
0
I've found it true, as already mentioned, that the best performing method is to write out key/vals to a file, and then use grep/awk to retrieve them. It sounds like all sorts of unnecessary IO, but disk cache kicks in and makes it extremely efficient -- much faster than trying to store them in memory using one of the above methods (as the benchmarks show).
Here's a quick, clean method I like:
hinit() {
rm -f /tmp/hashmap.$1
}
hput() {
echo "$2 $3" >> /tmp/hashmap.$1
}
hget() {
grep "^$2 " /tmp/hashmap.$1 | awk '{ print $2 };'
}
hinit capitols
hput capitols France Paris
hput capitols Netherlands Amsterdam
hput capitols Spain Madrid
echo `hget capitols France` and `hget capitols Netherlands` and `hget capitols Spain`
If you wanted to enforce single-value per key, you could also do a little grep/sed action in hput().
This is what worked for me on CentOS, first install:
sudo yum install postgresql postgresql-devel python-devel
On Ubuntu just use the equivilent apt-get packages.
sudo apt-get install postgresql postgresql-dev python-dev
And now include the path to your postgresql binary dir with you pip install, this should work for either Debain or RHEL based Linux:
sudo PATH=$PATH:/usr/pgsql-9.3/bin/ pip install psycopg2
Make sure to include the correct path. Thats all :)
To create a "drop down menu" you can use OptionMenu
in tkinter
Example of a basic OptionMenu
:
from Tkinter import *
master = Tk()
variable = StringVar(master)
variable.set("one") # default value
w = OptionMenu(master, variable, "one", "two", "three")
w.pack()
mainloop()
More information (including the script above) can be found here.
Creating an OptionMenu
of the months from a list would be as simple as:
from tkinter import *
OPTIONS = [
"Jan",
"Feb",
"Mar"
] #etc
master = Tk()
variable = StringVar(master)
variable.set(OPTIONS[0]) # default value
w = OptionMenu(master, variable, *OPTIONS)
w.pack()
mainloop()
In order to retrieve the value the user has selected you can simply use a .get()
on the variable that we assigned to the widget, in the below case this is variable
:
from tkinter import *
OPTIONS = [
"Jan",
"Feb",
"Mar"
] #etc
master = Tk()
variable = StringVar(master)
variable.set(OPTIONS[0]) # default value
w = OptionMenu(master, variable, *OPTIONS)
w.pack()
def ok():
print ("value is:" + variable.get())
button = Button(master, text="OK", command=ok)
button.pack()
mainloop()
I would highly recommend reading through this site for further basic tkinter information as the above examples are modified from that site.
Step 1: Get the latest aws-java-sdk
<!-- https://mvnrepository.com/artifact/org.apache.hadoop/hadoop-aws -->
<dependency>
<groupId>com.amazonaws</groupId>
<artifactId>aws-java-sdk</artifactId>
<version>1.11.660</version>
</dependency>
Step 2: The correct imports
import com.amazonaws.auth.AWSCredentials;
import com.amazonaws.auth.BasicAWSCredentials;
import com.amazonaws.regions.Region;
import com.amazonaws.regions.Regions;
import com.amazonaws.services.s3.AmazonS3;
import com.amazonaws.services.s3.AmazonS3Client;
import com.amazonaws.services.s3.AmazonS3ClientBuilder;
import com.amazonaws.services.s3.model.ListObjectsRequest;
import com.amazonaws.services.s3.model.ObjectListing;
If you are sure the bucket exists, Specified key does not exists error
would mean the bucketname is not spelled correctly ( contains slash or special characters). Refer the documentation for naming convention.
The document quotes:
If the requested object is available in the bucket and users are still getting the 404 NoSuchKey error from Amazon S3, check the following:
Confirm that the request matches the object name exactly, including the capitalization of the object name. Requests for S3 objects are case sensitive. For example, if an object is named myimage.jpg, but Myimage.jpg is requested, then requester receives a 404 NoSuchKey error. Confirm that the requested path matches the path to the object. For example, if the path to an object is awsexamplebucket/Downloads/February/Images/image.jpg, but the requested path is awsexamplebucket/Downloads/February/image.jpg, then the requester receives a 404 NoSuchKey error. If the path to the object contains any spaces, be sure that the request uses the correct syntax to recognize the path. For example, if you're using the AWS CLI to download an object to your Windows machine, you must use quotation marks around the object path, similar to: aws s3 cp "s3://awsexamplebucket/Backup Copy Job 4/3T000000.vbk". Optionally, you can enable server access logging to review request records in further detail for issues that might be causing the 404 error.
AWSCredentials credentials = new BasicAWSCredentials(AWS_ACCESS_KEY_ID, AWS_SECRET_KEY);
AmazonS3 s3Client = AmazonS3ClientBuilder.standard().withRegion(Regions.US_EAST_1).build();
ObjectListing objects = s3Client.listObjects("bigdataanalytics");
System.out.println(objects.getObjectSummaries());
Okay. You only need to use 'flatMap' when you're facing nested Optionals. Here's the example.
public class Person {
private Optional<Car> optionalCar;
public Optional<Car> getOptionalCar() {
return optionalCar;
}
}
public class Car {
private Optional<Insurance> optionalInsurance;
public Optional<Insurance> getOptionalInsurance() {
return optionalInsurance;
}
}
public class Insurance {
private String name;
public String getName() {
return name;
}
}
public class Test {
// map cannot deal with nested Optionals
public Optional<String> getCarInsuranceName(Person person) {
return person.getOptionalCar()
.map(Car::getOptionalInsurance) // ? leads to a Optional<Optional<Insurance>
.map(Insurance::getName); // ?
}
}
Like Stream, Optional#map will return a value wrapped by a Optional. That's why we get a nested Optional -- Optional<Optional<Insurance>
. And at ?, we want to map it as an Insurance instance, that's how the tragedy happened.
The root is nested Optionals. If we can get the core value regardless the shells, we'll get it done. That's what flatMap does.
public Optional<String> getCarInsuranceName(Person person) {
return person.getOptionalCar()
.flatMap(Car::getOptionalInsurance)
.map(Insurance::getName);
}
In the end, I stronly recommed the Java 8 In Action to you if you'd like to study Java8 Systematicly.
You can delete localStorage items one by one using Firebug (a useful web development extension) or Firefox's developer console.
You can enter these commands into the console:
localStorage; // click arrow to view object's properties
localStorage.removeItem("foo");
localStorage.clear(); // remove all of localStorage's properties
Firefox now has a built in storage inspector, which you may need to manually enable. See rahilwazir's answer below.
Django forms module uses __call__
method nicely to implement a consistent API for form validation. You can write your own validator for a form in Django as a function.
def custom_validator(value):
#your validation logic
Django has some default built-in validators such as email validators, url validators etc., which broadly fall under the umbrella of RegEx validators. To implement these cleanly, Django resorts to callable classes (instead of functions). It implements default Regex Validation logic in a RegexValidator and then extends these classes for other validations.
class RegexValidator(object):
def __call__(self, value):
# validation logic
class URLValidator(RegexValidator):
def __call__(self, value):
super(URLValidator, self).__call__(value)
#additional logic
class EmailValidator(RegexValidator):
# some logic
Now both your custom function and built-in EmailValidator can be called with the same syntax.
for v in [custom_validator, EmailValidator()]:
v(value) # <-----
As you can see, this implementation in Django is similar to what others have explained in their answers below. Can this be implemented in any other way? You could, but IMHO it will not be as readable or as easily extensible for a big framework like Django.
Here is what the JSF javadocs have to say about the commandButton
action
attribute:
MethodExpression representing the application action to invoke when this component is activated by the user. The expression must evaluate to a public method that takes no parameters, and returns an Object (the toString() of which is called to derive the logical outcome) which is passed to the NavigationHandler for this application.
It would be illuminating to me if anyone can explain what that has to do with any of the answers on this page. It seems pretty clear that action
refers to some page's filename and not a method.
I am not very sure if what i did was right, but it worked anyways. I renamed repo2 folder present inside repo1, and committed the changes. In my case it was just one repo which i wanted to merge , so this approach worked. Later on, some path changes were done.
Other alternative:
JAXBElement<String> element = new JAXBElement<>(new QName("Your localPart"),
String.class, "Your message");
Then:
System.out.println(element.getValue()); // Result: Your message
Thanks to AddRange
:
Example:
public class Person
{
private string Name;
private string FirstName;
public Person(string name, string firstname) => (Name, FirstName) = (name, firstname);
}
To add multiple Person
to a List<>
:
List<Person> listofPersons = new List<Person>();
listofPersons.AddRange(new List<Person>
{
new Person("John1", "Doe" ),
new Person("John2", "Doe" ),
new Person("John3", "Doe" ),
});
You could make it more readable and more efficient:
string oldValue = valueFieldValue.ToString();
string newValue = value.ToString();
int index = listofelements.IndexOf(oldValue);
if(index != -1)
listofelements[index] = newValue;
This asks only once for the index. Your approach uses Contains
first which needs to loop all items(in the worst case), then you're using IndexOf
which needs to enumerate the items again .
For all to those having problems with this i did this tutorial:
How to install Imagemagick and Php module Imagick on ubuntu?
i did this 7 simple steps:
Update libraries, and packages
apt-get update
Remove obsolete things
apt-get autoremove
For the libraries of ImageMagick
apt-get install libmagickwand-dev
for the core class Imagick
apt-get install imagemagick
For create the binaries, and conections in beetween
pecl install imagick
Append the extension to your php.ini
echo "extension=imagick.so" >> /etc/php5/apache2/php.ini
Restart Apache
service apache2 restart
I found a problem. PHP searches for .so files in a folder called /usr/lib/php5/20100525, and the imagick.so is stored in a folder called /usr/lib/php5/20090626. So you have to copy the file to that folder.
Writing exception-safe code in C++ is not so much about using lots of try { } catch { } blocks. It's about documenting what kind of guarantees your code provides.
I recommend reading Herb Sutter's Guru Of The Week series, in particular installments 59, 60 and 61.
To summarize, there are three levels of exception safety you can provide:
Personally, I discovered these articles quite late, so much of my C++ code is definitely not exception-safe.
How about using Pandas to read the csv file into a DataFrame (pd.read_csv), then manipulating the columns if you want (dropping them or updating values) and finally converting the DataFrame back to JSON (pd.DataFrame.to_json).
Note: I haven't checked how efficient this will be but this is definitely one of the easiest ways to manipulate and convert a large csv to json.
You could use --where option on mysqldump to produce an output that you are waiting for:
mysqldump -u root -p test t1 --where="1=1 limit 100" > arquivo.sql
At most 100 rows from test.t1 will be dumped from database table.
Cheers, WB
Yes, you can.
From cplusplus.com:
Because these functions are operator overloading functions, the usual way in which they are called is:
strm >> variable;
Where
strm
is the identifier of a istream object andvariable
is an object of any type supported as right parameter. It is also possible to call a succession of extraction operations as:strm >> variable1 >> variable2 >> variable3; //...
which is the same as performing successive extractions from the same object
strm
.
Just replace strm
with cin
.
We are finally beginning to see a built-in matchAll
function, see here for the description and compatibility table. It looks like as of May 2020, Chrome, Edge, Firefox, and Node.js (12+) are supported but not IE, Safari, and Opera. Seems like it was drafted in December 2018 so give it some time to reach all browsers, but I trust it will get there.
The built-in matchAll
function is nice because it returns an iterable. It also returns capturing groups for every match! So you can do things like
// get the letters before and after "o"
let matches = "stackoverflow".matchAll(/(\w)o(\w)/g);
for (match of matches) {
console.log("letter before:" + match[1]);
console.log("letter after:" + match[2]);
}
arrayOfAllMatches = [...matches]; // you can also turn the iterable into an array
It also seem like every match object uses the same format as match()
. So each object is an array of the match and capturing groups, along with three additional properties index
, input
, and groups
. So it looks like:
[<match>, <group1>, <group2>, ..., index: <match offset>, input: <original string>, groups: <named capture groups>]
For more information about matchAll
there is also a Google developers page. There are also polyfills/shims available.
For sum of elements in array of Objects
self.rankDataModelArray.flatMap{$0.count}.reduce(0, +)
From ScottGu's blog:
Starting with the ASP.NET MVC 3 Beta release, you can now add a file called _ViewStart.cshtml (or _ViewStart.vbhtml for VB) underneath the \Views folder of your project:
The _ViewStart file can be used to define common view code that you want to execute at the start of each View’s rendering. For example, we could write code within our _ViewStart.cshtml file to programmatically set the Layout property for each View to be the SiteLayout.cshtml file by default:
Because this code executes at the start of each View, we no longer need to explicitly set the Layout in any of our individual view files (except if we wanted to override the default value above).
Important: Because the _ViewStart.cshtml allows us to write code, we can optionally make our Layout selection logic richer than just a basic property set. For example: we could vary the Layout template that we use depending on what type of device is accessing the site – and have a phone or tablet optimized layout for those devices, and a desktop optimized layout for PCs/Laptops. Or if we were building a CMS system or common shared app that is used across multiple customers we could select different layouts to use depending on the customer (or their role) when accessing the site.
This enables a lot of UI flexibility. It also allows you to more easily write view logic once, and avoid repeating it in multiple places.
Also see this.
In a more general sense this ability of MVC framework to "know" about _Viewstart.cshtml is called "Coding by convention".
Convention over configuration (also known as coding by convention) is a software design paradigm which seeks to decrease the number of decisions that developers need to make, gaining simplicity, but not necessarily losing flexibility. The phrase essentially means a developer only needs to specify unconventional aspects of the application. For example, if there's a class Sale in the model, the corresponding table in the database is called “sales” by default. It is only if one deviates from this convention, such as calling the table “products_sold”, that one needs to write code regarding these names.
Wikipedia
There's no magic to it. Its just been written into the core codebase of the MVC framework and is therefore something that MVC "knows" about. That why you don't find it in the .config files or elsewhere; it's actually in the MVC code. You can however override to alter or null out these conventions.
A template class is like a macro, only a whole lot less evil.
Think of a template as a macro. The parameters to the template get substituted into a class (or function) definition, when you define a class (or function) using a template.
The difference is that the parameters have "types" and values passed are checked during compilation, like parameters to functions. The types valid are your regular C++ types, like int and char. When you instantiate a template class, you pass a value of the type you specified, and in a new copy of the template class definition this value gets substituted in wherever the parameter name was in the original definition. Just like a macro.
You can also use the "class
" or "typename
" types for parameters (they're really the same). With a parameter of one of these types, you may pass a type name instead of a value. Just like before, everywhere the parameter name was in the template class definition, as soon as you create a new instance, becomes whatever type you pass. This is the most common use for a template class; Everybody that knows anything about C++ templates knows how to do this.
Consider this template class example code:
#include <cstdio>
template <int I>
class foo
{
void print()
{
printf("%i", I);
}
};
int main()
{
foo<26> f;
f.print();
return 0;
}
It's functionally the same as this macro-using code:
#include <cstdio>
#define MAKE_A_FOO(I) class foo_##I \
{ \
void print() \
{ \
printf("%i", I); \
} \
};
MAKE_A_FOO(26)
int main()
{
foo_26 f;
f.print();
return 0;
}
Of course, the template version is a billion times safer and more flexible.
From memory, it's either this
SELECT * FROM sys.objects
WHERE type = 'PK'
AND object_id = OBJECT_ID ('tableName')
or this..
SELECT * FROM sys.objects
WHERE type = 'PK'
AND parent_object_id = OBJECT_ID ('tableName')
I think one of them should probably work depending on how the data is stored but I am afraid I have no access to SQL to actually verify the same.
Try to run this command if you are using nohup -
nohup npm start 2>/dev/null 1>/dev/null&
You can also use forever to start server
forever start -c "npm start" ./
PM2 also supports npm start
pm2 start npm -- start
Drop all the foreign keys of a table:
USE [Database_Name]
DECLARE @FOREIGN_KEY_NAME VARCHAR(100)
DECLARE FOREIGN_KEY_CURSOR CURSOR FOR
SELECT name FOREIGN_KEY_NAME FROM sys.foreign_keys WHERE parent_object_id = (SELECT object_id FROM sys.objects WHERE name = 'Table_Name' AND TYPE = 'U')
OPEN FOREIGN_KEY_CURSOR
----------------------------------------------------------
FETCH NEXT FROM FOREIGN_KEY_CURSOR INTO @FOREIGN_KEY_NAME
WHILE @@FETCH_STATUS = 0
BEGIN
DECLARE @DROP_COMMAND NVARCHAR(150) = 'ALTER TABLE Table_Name DROP CONSTRAINT' + ' ' + @FOREIGN_KEY_NAME
EXECUTE Sp_executesql @DROP_COMMAND
FETCH NEXT FROM FOREIGN_KEY_CURSOR INTO @FOREIGN_KEY_NAME
END
-----------------------------------------------------------------------------------------------------------------
CLOSE FOREIGN_KEY_CURSOR
DEALLOCATE FOREIGN_KEY_CURSOR
Apparently Facebook no longer (as of 2014) allows you to customise the sharing screen, no matter if you are just opening sharer.php URL or using Android intents in more specialised ways. See for example these answers:
Anyway, using plain Intents, you can still share a URL, but not any default text with it, as billynomates commented. (Also, if you have no URL to share, just launching Facebook app with empty "Write Post" (i.e. status update) dialog is equally easy; use the code below but leave out EXTRA_TEXT
.)
Here's the best solution I've found that does not involve using any Facebook SDKs.
This code opens the official Facebook app directly if it's installed, and otherwise falls back to opening sharer.php in a browser. (Most of the other solutions in this question bring up a huge "Complete action using…" dialog which isn't optimal at all!)
String urlToShare = "https://stackoverflow.com/questions/7545254";
Intent intent = new Intent(Intent.ACTION_SEND);
intent.setType("text/plain");
// intent.putExtra(Intent.EXTRA_SUBJECT, "Foo bar"); // NB: has no effect!
intent.putExtra(Intent.EXTRA_TEXT, urlToShare);
// See if official Facebook app is found
boolean facebookAppFound = false;
List<ResolveInfo> matches = getPackageManager().queryIntentActivities(intent, 0);
for (ResolveInfo info : matches) {
if (info.activityInfo.packageName.toLowerCase().startsWith("com.facebook.katana")) {
intent.setPackage(info.activityInfo.packageName);
facebookAppFound = true;
break;
}
}
// As fallback, launch sharer.php in a browser
if (!facebookAppFound) {
String sharerUrl = "https://www.facebook.com/sharer/sharer.php?u=" + urlToShare;
intent = new Intent(Intent.ACTION_VIEW, Uri.parse(sharerUrl));
}
startActivity(intent);
(Regarding the com.facebook.katana
package name, see MatheusJardimB's comment.)
The result looks like this on my Nexus 7 (Android 4.4) with Facebook app installed:
I realize you've found another answer - but the fact is that your original code was nearly correct but for a syntax error.
Your code contained the line
set /A COUNTER=%COUNTER%+1
and the syntax that would work is simply...
set /A COUNTER=COUNTER+1
See http://ss64.com/nt/set.html for all the details on the SET command. I just thought I'd add this clarification for anyone else who doesn't have the option of using FreeDOS.
fn
literally refers to the jquery prototype
.
This line of code is in the source code:
jQuery.fn = jQuery.prototype = {
//list of functions available to the jQuery api
}
But the real tool behind fn
is its availability to hook your own functionality into jQuery. Remember that jquery will be the parent scope to your function, so this
will refer to the jquery object.
$.fn.myExtension = function(){
var currentjQueryObject = this;
//work with currentObject
return this;//you can include this if you would like to support chaining
};
So here is a simple example of that. Lets say I want to make two extensions, one which puts a blue border, and which colors the text blue, and I want them chained.
jsFiddle Demo
$.fn.blueBorder = function(){
this.each(function(){
$(this).css("border","solid blue 2px");
});
return this;
};
$.fn.blueText = function(){
this.each(function(){
$(this).css("color","blue");
});
return this;
};
Now you can use those against a class like this:
$('.blue').blueBorder().blueText();
(I know this is best done with css such as applying different class names, but please keep in mind this is just a demo to show the concept)
This answer has a good example of a full fledged extension.
This will output the date in YYYY-MM-DD format:
let date = new Date();
date = date.toISOString().slice(0,10);
If you want be sure you need to check both
SomeProperty == null || SomeProperty == Guid.Empty
Because it can be null 'Nullable' and it can be an empty GUID something like this {00000000-0000-0000-0000-000000000000}
I couldn't figure out what exactly you meant by byte String, but here are some conversions from byte to String and vice versa, of course there is a lot more on the official documentations
Integer intValue = 149;
The corresponding byte value is:
Byte byteValue = intValue.byteValue(); // this will convert the rightmost byte of the intValue to byte, because Byte is an 8 bit object and Integer is at least 16 bit, and it will give you a signed number in this case -107
get the integer value back from a Byte variable:
Integer anInt = byteValue.intValue(); // This will convert the byteValue variable to a signed Integer
From Byte and Integer to hex String:
This is the way I do it:
Integer anInt = 149
Byte aByte = anInt.byteValue();
String hexFromInt = "".format("0x%x", anInt); // This will output 0x95
String hexFromByte = "".format("0x%x", aByte); // This will output 0x95
Converting an array of bytes to a hex string:
As far as I know there is no simple function to convert all the elements inside an array of some Object
to elements of another Object
, So you have to do it yourself. You can use the following functions:
From byte[] to String:
public static String byteArrayToHexString(byte[] byteArray){
String hexString = "";
for(int i = 0; i < byteArray.length; i++){
String thisByte = "".format("%x", byteArray[i]);
hexString += thisByte;
}
return hexString;
}
And from hex string to byte[]:
public static byte[] hexStringToByteArray(String hexString){
byte[] bytes = new byte[hexString.length() / 2];
for(int i = 0; i < hexString.length(); i += 2){
String sub = hexString.substring(i, i + 2);
Integer intVal = Integer.parseInt(sub, 16);
bytes[i / 2] = intVal.byteValue();
String hex = "".format("0x%x", bytes[i / 2]);
}
return bytes;
}
It is too late but I hope this could help some others ;)
A VIP swap is an internal change to Azure's routers/load balancers, not an external DNS change. They're just routing traffic to go from one internal [set of] server[s] to another instead. Therefore the DNS info for mysite.cloudapp.net doesn't change at all. Therefore the change for people accessing via the IP bound to mysite.cloudapp.net (and CNAME'd by you) will see the change as soon as the VIP swap is complete.
Add one unique session or cookie in button click event then redirect page on same URL using Request.RawUrl Now add code in Page_Load event to grab that session or coockie. If session/cookie matches then you can knows that page redirected using refresh button. So decrease hit counter by 1 to keep it on same number do hitcountr -= hitconter
Else increase the hit counter.
I used the action delegate like this in a project once:
private static Dictionary<Type, Action<Control>> controldefaults = new Dictionary<Type, Action<Control>>() {
{typeof(TextBox), c => ((TextBox)c).Clear()},
{typeof(CheckBox), c => ((CheckBox)c).Checked = false},
{typeof(ListBox), c => ((ListBox)c).Items.Clear()},
{typeof(RadioButton), c => ((RadioButton)c).Checked = false},
{typeof(GroupBox), c => ((GroupBox)c).Controls.ClearControls()},
{typeof(Panel), c => ((Panel)c).Controls.ClearControls()}
};
which all it does is store a action(method call) against a type of control so that you can clear all the controls on a form back to there defaults.
I have another solution since the STR() function would result some blank spaces, so I use the FORMAT() function as folowing example:
SELECT ':' + STR(1000.2324422), ':' + FORMAT(1000.2324422,'##.#######'), ':' + FORMAT(1000.2324422,'##')
The result of above code would be:
: 1000 :1000.2324422 :1000
Here is yet another (working) variant:
This opens a new gnome terminal, then in the new terminal it runs bash. The user's rc file is read first, then a command ls -la
is sent for execution to the new shell before it turns interactive.
The last echo adds an extra newline that is needed to finish execution.
gnome-terminal -- bash -c 'bash --rcfile <( cat ~/.bashrc; echo ls -la ; echo)'
I also find it useful sometimes to decorate the terminal, e.g. with colorfor better orientation.
gnome-terminal --profile green -- bash -c 'bash --rcfile <( cat ~/.bashrc; echo ls -la ; echo)'
It's good when reading to use the OpenFileDialog control to browse to any file you want to read. Find the code below:
Don't forget to add the following using
statement to read files: using System.IO;
private void button1_Click(object sender, EventArgs e)
{
if (openFileDialog1.ShowDialog() == DialogResult.OK)
{
textBox1.Text = File.ReadAllText(openFileDialog1.FileName);
}
}
To write files you can use the method File.WriteAllText
.
One reason to always include a character set specification on every page containing text is to avoid cross site scripting vulnerabilities. In most cases the UTF-8 character set is the best choice for text, including HTML pages.
Had the same issue, writing this here in case someone in the future stumbles upon this and has issues with multiple modals that have to have scrolling as well (I'm using Bootstrap 3.3.7)
What I did is have a button like this inside my first modal:
<div id="FirstId" data-dismiss="modal" data-toggle="modal" data-target="#YourModalId_2">Open modal</div>
It will hide the first and then display the second, and in the second modal I would have a close button that would look like this:
<div id="SecondId" data-dismiss="modal" data-toggle="modal" data-target="#YourModalId_1">Close</div>
So this will close the second modal and open up the first one and to make scrolling work I added to my .css file this line:
.modal {
overflow: auto !important;
}
PS: Just a side note, you have to have these modals separately, the minor modal can not be nested in the first one as you hide the first one
So here's the full example based on the bootstrap modal example:
<!-- Button trigger modal -->
<button type="button" class="btn btn-primary" data-toggle="modal" data-target="#exampleModal">
Launch demo modal
</button>
<!-- Modal 1 -->
<div class="modal fade" id="exampleModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="exampleModalLabel">Modal title</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
Add lorem ipsum here
</div>
<div class="modal-footer">
<button type="button" class="btn btn-primary" data-dismiss="modal" data-toggle="modal" data-target="#exampleModal2">
Open second modal
</button>
</div>
</div>
</div>
</div>
<!-- Modal 2 -->
<div class="modal fade" id="exampleModal2" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="exampleModalLabel">Modal title</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
...
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal" data-toggle="modal" data-target="#exampleModal">Close</button>
</div>
</div>
</div>
</div>
Microsoft also release the Microsoft Visual Studio 2015 Installer Projects Extension This is the same extension as the 2013 version but for Visual Studio 2015
No. Unlike other virtual methods, where you would explicitly call the Base method from the Derived to 'chain' the call, the compiler generates code to call the destructors in the reverse order in which their constructors were called.
Here's the other one, particularly useful to convert the multiple columns to string instead of just single column:
In [76]: import numpy as np
In [77]: import pandas as pd
In [78]: df = pd.DataFrame({
...: 'A': [20, 30.0, np.nan],
...: 'B': ["a45a", "a3", "b1"],
...: 'C': [10, 5, np.nan]})
...:
In [79]: df.dtypes ## Current datatype
Out[79]:
A float64
B object
C float64
dtype: object
## Multiple columns string conversion
In [80]: df[["A", "C"]] = df[["A", "C"]].astype(str)
In [81]: df.dtypes ## Updated datatype after string conversion
Out[81]:
A object
B object
C object
dtype: object
string Output = Regex.Replace(Input, @"([ a-zA-Z0-9&, _]|^\s)", "");
Here all the special characters except space, comma, and ampersand are replaced. You can also omit space, comma and ampersand by the following regular expression.
string Output = Regex.Replace(Input, @"([ a-zA-Z0-9_]|^\s)", "");
Where Input is the string which we need to replace the characters.
All the three are access modifiers and keywords which are used in a class. Anything declared in public can be used by any object within the class or outside the class,variables in private can only be used by the objects within the class and could not be changed through direct access(as it can change through functions like friend function).Anything defined under protected section can be used by the class and their just derived class.
The scripts mentioned in previous answers, like:
$("body, html").animate({
scrollTop: $(document).height()
}, 400)
or
$(window).scrollTop($(document).height());
will not work in Chrome and will be jumpy in Safari in case html
tag in CSS has overflow: auto;
property set. It took me nearly an hour to figure out.
You can just say
callback();
Alternately you can use the call
method if you want to adjust the value of this
within the callback.
callback.call( newValueForThis);
Inside the function this
would be whatever newValueForThis
is.
If all you want is a two dimensional container to hold some elements, you could conveniently use a dictionary instead:
Matrix = {}
Then you can do:
Matrix[1,2] = 15
print Matrix[1,2]
This works because 1,2
is a tuple, and you're using it as a key to index the dictionary. The result is similar to a dumb sparse matrix.
As indicated by osa and Josap Valls, you can also use Matrix = collections.defaultdict(lambda:0)
so that the missing elements have a default value of 0
.
Vatsal further points that this method is probably not very efficient for large matrices and should only be used in non performance-critical parts of the code.
I think there is an error in the trigger code. As you want to delete all rows with the deleted patron ID, you have to use old.id (Otherwise it would delete other IDs)
Try this as the new trigger:
CREATE TRIGGER log_patron_delete AFTER DELETE on patrons
FOR EACH ROW
BEGIN
DELETE FROM patron_info
WHERE patron_info.pid = old.id;
END
Dont forget the ";" on the delete query. Also if you are entering the TRIGGER code in the console window, make use of the delimiters also.
In addition to Harry's answer, I think it's crucial to add/emphasize that :last-child will not work if the element is not the VERY LAST element in a container. For whatever reason it took me hours to realize that, and even though Harry's answer is very thorough I couldn't extract that information from "The last-child selector is used to select the last child element of a parent."
Suppose this is my selector: a:last-child {}
This works:
<div>
<a></a>
<a>This will be selected</a>
</div>
This doesn't:
<div>
<a></a>
<a>This will no longer be selected</a>
<div>This is now the last child :'( </div>
</div>
It doesn't because the a
element is not the last element inside its parent.
It may be obvious, but it was not for me...
This error would happen when the number of guesses (so_far) is less than the length of the word. Did you miss an initialization for the variable so_far somewhere, that sets it to something like
so_far = " " * len(word)
?
Edit:
try something like
print "%d / %d" % (new, so_far)
before the line that throws the error, so you can see exactly what goes wrong. The only thing I can think of is that so_far is in a different scope, and you're not actually using the instance you think.
You don't want git revert
. That undoes a previous commit. You want git checkout
to get git's version of the file from master.
git checkout -- filename.txt
In general, when you want to perform a git operation on a single file, use -- filename
.
2020 Update
Git introduced a new command git restore
in version 2.23.0
. Therefore, if you have git version 2.23.0+
, you can simply git restore filename.txt
- which does the same thing as git checkout -- filename.txt
. The docs for this command do note that it is currently experimental.
You can export collection by clicking on arrow button
and then click on download collection button
If you are using UI router then you can use a decorator and update $templateFactory service and append a query string parameter to templateUrl, and the browser will always load the new template from the server.
function configureTemplateFactory($provide) {
// Set a suffix outside the decorator function
var cacheBust = Date.now().toString();
function templateFactoryDecorator($delegate) {
var fromUrl = angular.bind($delegate, $delegate.fromUrl);
$delegate.fromUrl = function (url, params) {
if (url !== null && angular.isDefined(url) && angular.isString(url)) {
url += (url.indexOf("?") === -1 ? "?" : "&");
url += "v=" + cacheBust;
}
return fromUrl(url, params);
};
return $delegate;
}
$provide.decorator('$templateFactory', ['$delegate', templateFactoryDecorator]);
}
app.config(['$provide', configureTemplateFactory]);
I am sure you can achieve the same result by decorating the "when" method in $routeProvider.
You have some variables that are different types in Java language like that:
message of type string
timestamp of type time
count of type integer
version of type integer
If you use a HashMap like:
HashMap<String,Object> yourHash = new HashMap<String,Object>();
yourHash.put("message","message");
yourHash.put("timestamp",timestamp);
yourHash.put("count ",count);
yourHash.put("version ",version);
If you want to use the yourHash:
for(String key : yourHash.keySet()){
String message = (String) yourHash.get(key);
Datetime timestamp= (Datetime) yourHash.get(key);
int timestamp= (int) yourHash.get(key);
}
You're using S_ISREG()
and S_ISDIR()
correctly, you're just using them on the wrong thing.
In your while((dit = readdir(dip)) != NULL)
loop in main
, you're calling stat
on currentPath
over and over again without changing currentPath
:
if(stat(currentPath, &statbuf) == -1) {
perror("stat");
return errno;
}
Shouldn't you be appending a slash and dit->d_name
to currentPath
to get the full path to the file that you want to stat
? Methinks that similar changes to your other stat
calls are also needed.
Trigger a hyperlink <a> element that is inside the element you want to hookup the jQuery .click() to:
<div class="TopicControl">
<div class="articleImage">
<a href=""><img src="" alt=""></a>
</div>
</div>
In your script you hookup to the main container you want the click event on. Then you use standard jQuery methodology to find the element (type, class, and id) and fire the click. jQuery enters a recursive function to fire the click and you break the recursive function by taking the event 'e' and stopPropagation() function and return false, because you don't want jQuery to do anything else but fire the link.
$('.TopicControl').click(function (event) {
$(this).find('a').click();
event.stopPropagation();
return false;
});
Alternative solution is to wrap the containers in the <a> element and place 's as containers inside instead of <div>'s. Set the spans to display block to conform with W3C standards.
You can have multiple <context:property-placeholder />
elements instead of explicitly declaring multiple PropertiesPlaceholderConfigurer beans.
Try this one
.parent_div{
display: flex;
}
If you're stuck with Java 8 but have access to Guava 21.0 or newer, you can use Streams.stream
to convert an optional into a stream.
Thus, given
import com.google.common.collect.Streams;
you can write
Optional<Other> result =
things.stream()
.map(this::resolve)
.flatMap(Streams::stream)
.findFirst();
To my surprise you do not need users-permission CONTACT_READ to read the names and some basic information (Is the contact starred, what was the last calling time). However you do need permission to read the details of the contact like phone number.
This worked for me:
COPY (SELECT * FROM table)
TO E'C:\\Program Files (x86)\\PostgreSQL\\8.4\\data\\try.csv';
In my case the problem was with the writing permission to a special folder (though I work as administrator), after changing the path to the original data folder under PostgreSQL I had success.
Omit row if either of two specific columns contain <NA>
.
DF[!is.na(DF$x)&!is.na(DF$z),]
AppendChild
(E) is more than 2x faster than other solutions on chrome and safari, insertAdjacentHTML
(F) is fastest on firefox. The innerHTML=
(B) (do not confuse with +=
(A)) is second fast solution on all browsers and it is much more handy than E and F.
Set up environment (2019.07.10) MacOs High Sierra 10.13.4 on Chrome 75.0.3770 (64-bit), Safari 11.1.0 (13604.5.6), Firefox 67.0.0 (64-bit)
You can replay test in your machine here
function A() { _x000D_
container.innerHTML += '<p>A: Just some <span>text</span> here</p>';_x000D_
}_x000D_
_x000D_
function B() { _x000D_
container.innerHTML = '<p>B: Just some <span>text</span> here</p>';_x000D_
}_x000D_
_x000D_
function C() { _x000D_
$('#container').append('<p>C: Just some <span>text</span> here</p>');_x000D_
}_x000D_
_x000D_
function D() {_x000D_
var p = document.createElement("p");_x000D_
p.innerHTML = 'D: Just some <span>text</span> here';_x000D_
container.appendChild(p);_x000D_
}_x000D_
_x000D_
function E() { _x000D_
var p = document.createElement("p");_x000D_
var s = document.createElement("span"); _x000D_
s.appendChild( document.createTextNode("text ") );_x000D_
p.appendChild( document.createTextNode("E: Just some ") );_x000D_
p.appendChild( s );_x000D_
p.appendChild( document.createTextNode(" here") );_x000D_
container.appendChild(p);_x000D_
}_x000D_
_x000D_
function F() { _x000D_
container.insertAdjacentHTML('beforeend', '<p>F: Just some <span>text</span> here</p>');_x000D_
}_x000D_
_x000D_
A();_x000D_
B();_x000D_
C();_x000D_
D();_x000D_
E();_x000D_
F();
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
_x000D_
This snippet only for show code used in test (in jsperf.com) - it not perform test itself. _x000D_
<div id="container"></div>
_x000D_
I'm not sure how necessary this is, and it adds a call to getElementById
, but if you're really keen on getting inline JavaScript out of your code, you can pass it as an HTML attribute, namely:
<span class="metadata" id="metadata-size-of-widget" title="<?php echo json_encode($size_of_widget) ?>"></span>
And then in your JavaScript:
var size_of_widget = document.getElementById("metadata-size-of-widget").title;
I came across this thread because I also had the error Could not create SSL/TLS secure channel. In my case, I was attempting to access a Siebel configuration REST API from PowerShell using Invoke-RestMethod
, and none of the suggestions above helped.
Eventually I stumbled across the cause of my problem: the server I was contacting required client certificate authentication.
To make the calls work, I had to provide the client certificate (including the private key) with the -Certificate
parameter:
$Pwd = 'certificatepassword'
$Pfx = New-Object -TypeName 'System.Security.Cryptography.X509Certificates.X509Certificate2'
$Pfx.Import('clientcert.p12', $Pwd, 'Exportable,PersistKeySet')
Invoke-RestMethod -Uri 'https://your.rest.host/api/' -Certificate $Pfx -OtherParam ...
Hopefully my experience might help someone else who has my particular flavour of this problem.
I found that there is height of div still showing, when it have text or not. So you can use this for best results.
<div style=" overflow:auto;max-height:300px; max-width:300px;"></div>
It means "no value". You use void
to indicate that a function doesn't return a value or that it has no parameters or both. Pretty much consistent with typical uses of word void in English.
On my website I use this method:
//Symb array
private const string _SymbolsAll = "~`!@#$%^&*()_+=-\\|[{]}'\";:/?.>,<";
//Random symb
public string GetSymbol(int Length)
{
Random Rand = new Random(DateTime.Now.Millisecond);
StringBuilder result = new StringBuilder();
for (int i = 0; i < Length; i++)
result.Append(_SymbolsAll[Rand.Next(0, _SymbolsAll.Length)]);
return result.ToString();
}
Edit string _SymbolsAll
for your array list.
Try my way :
robocopy.exe "Desktop\Test folder 1" "Desktop\Test folder 2" /XD "C:\Users\Steve\Desktop\Test folder 2\XXX dont touch" /MIR
Had to put /XD
before /MIR
while including the full Destination Source directly after /XD
.
I need more information really but it will be along the lines of..
SELECT table1.*, table2.col1, table2.col3 FROM table1 JOIN table2 USING(id)
2014 and above at least you can set a default and it will take that and NOT error when you do not pass that parameter. Partial Example: the 3rd parameter is added as optional. exec of the actual procedure with only the first two parameters worked fine
exec getlist 47,1,0
create procedure getlist
@convId int,
@SortOrder int,
@contestantsOnly bit = 0
as
Try this : Using this you can select date by last 30 days,
SELECT DATEADD(DAY,-30,GETDATE())
Installing libgl1-mesa-dev from the Ubuntu repo resolved this problem for me.
This question has been asked a couple times ...
See this related question/answer (quoted below) ... how to release the caching which is used by Mongodb?
MongoDB will (at least seem) to use up a lot of available memory, but it actually leaves it up to the OS's VMM to tell it to release the memory (see Caching in the MongoDB docs.)
You should be able to release any and all memory by restarting MongoDB.
However, to some extent MongoDB isn't really "using" the memory.
For example from the MongoDB docs Checking Server Memory Usage ...
Depending on the platform you may see the mapped files as memory in the process, but this is not strictly correct. Unix top may show way more memory for mongod than is really appropriate. The Operating System (the virtual memory manager specifically, depending on OS) manages the memory where the "Memory Mapped Files" reside. This number is usually shown in a program like "free -lmt".
It is called "cached" memory.
MongoDB uses the LRU (Least Recently Used) cache algorithm to determine which "pages" to release, you will find some more information in these two questions ...
keystore simply stores private keys, wheras truststore stores public keys. You will want to generate a java certificate for SSL communication. You can use a keygen command in windows, this will probably be the most easy solution.
My answer is focused to a extended case derived from the one exposed at top.
Suppose you have group of elements from which you want to hide the child elements except first. As an example:
<html>
<div class='some-group'>
<div class='child child-0'>visible#1</div>
<div class='child child-1'>xx</div>
<div class='child child-2'>yy</div>
</div>
<div class='some-group'>
<div class='child child-0'>visible#2</div>
<div class='child child-1'>aa</div>
<div class='child child-2'>bb</div>
</div>
</html>
We want to hide all .child
elements on every group. So this will not help because will hide all .child
elements except visible#1
:
$('.child:not(:first)').hide();
The solution (in this extended case) will be:
$('.some-group').each(function(i,group){
$(group).find('.child:not(:first)').hide();
});
In my case, it was not worknig even after passing the proxy credentails.
Mistake was - forgot to remove the comment line.
<!-- proxy
| Specification for one proxy, to be used in connecting to the network.
<proxy>
<id>optional</id>
<active>true</active>
<protocol>http</protocol>
<username>345325</username>
<password>dfgasdfg</password>
<host>proxy.abc.com</host>
<port>8080</port>
<nonProxyHosts>proxy.abc.com</nonProxyHosts>
</proxy>
|--> ----------REMOVE THIS LINE AND CLOSE It above <proxy> tag
I suggest writing a little script and doing multiple searches with Grep. I've never found a way to search for multiple patterns, and believe me, I've looked!
Like so, your shell file, with an embedded string:
#!/bin/bash
grep *A6* "Alex A1 Alex A6 Alex A7 Bob A1 Chris A9 Chris A6";
grep *A7* "Alex A1 Alex A6 Alex A7 Bob A1 Chris A9 Chris A6";
grep *A8* "Alex A1 Alex A6 Alex A7 Bob A1 Chris A9 Chris A6";
Then run by typing myshell.sh.
If you want to be able to pass in the string on the command line, do it like this, with a shell argument--this is bash notation btw:
#!/bin/bash
$stingtomatch = "${1}";
grep *A6* "${stingtomatch}";
grep *A7* "${stingtomatch}";
grep *A8* "${stingtomatch}";
And so forth.
If there are a lot of patterns to match, you can put it in a for loop.
An option using AutoFilter
Option Explicit
Public Sub FilterOutMultiple()
Dim ws As Worksheet, filterOut As Variant, toHide As Range
Set ws = ActiveSheet
If Application.WorksheetFunction.CountA(ws.Cells) = 0 Then Exit Sub 'Empty sheet
filterOut = Split("A B C D E F G")
Application.ScreenUpdating = False
With ws.UsedRange.Columns("A")
If ws.FilterMode Then .AutoFilter
.AutoFilter Field:=1, Criteria1:=filterOut, Operator:=xlFilterValues
With .SpecialCells(xlCellTypeVisible)
If .CountLarge > 1 Then Set toHide = .Cells 'Remember unwanted (A, B, and C)
End With
.AutoFilter
If Not toHide Is Nothing Then
toHide.Rows.Hidden = True 'Hide unwanted (A, B, and C)
.Cells(1).Rows.Hidden = False 'Unhide header
End If
End With
Application.ScreenUpdating = True
End Sub
You could make the identifier a param for a query selector. For PHP and compatible languages use an associative array (in effect an objects) and then json_encode.
$temp=array('#id' =>array('href'=>'services.html')
,'img' =>array('src'=>"img/SolutionInnerbananer.jpg")
,'.html'=>'<h2 class="fg-white">AboutUs</h2><p class="fg-white">...</p>'
);
echo json_encode($temp);
But HTML don't do it for you without some JS.
{"#id":{"href":"services.html"},"img":{"src":"img\/SolutionInnerbananer.jpg"}
,".html":"<h2 class=\"fg-white\">AboutUs<\/h2><p class=\"fg-white\">...<\/p>"}
Try this:
document.frames["myiframe"].onload = function(){
alert("Hello World");
}
The approved answer from @jbochi does not work for me. The str() function call raises an exception because it cannot encode the non-ascii characters in the BeautifulSoup element. Here is a more succinct way to filter the example web page to visible text.
html = open('21storm.html').read()
soup = BeautifulSoup(html)
[s.extract() for s in soup(['style', 'script', '[document]', 'head', 'title'])]
visible_text = soup.getText()
You DO NOT NEED to replace the comma and dot..
I have had the very same problem. The reason is simple, the conversion culture plays a big role in which the comma or a dot is interpreted. I use a German culture where the comma distinguish the fractions, where as elsewhere the dot does the job.
Here I made a complete example to make the difference clear.
string[] doubleStrings = {"hello", "0.123", "0,123"};
double localCultreResult;
foreach (var doubleString in doubleStrings)
{
double.TryParse(doubleString, NumberStyles.Any, CultureInfo.CurrentCulture, out localCultreResult);
Console.WriteLine(string.Format("Local culture results for the parsing of {0} is {1}", doubleString, localCultreResult));
}
double invariantCultureResult;
foreach (var doubleString in doubleStrings)
{
double.TryParse(doubleString, NumberStyles.Any, CultureInfo.InvariantCulture, out invariantCultureResult);
Console.WriteLine(string.Format("Invariant culture results for the parsing of {0} is {1}", doubleString, invariantCultureResult));
}
The results is the following:
Play around with the culture and you will get the result you need.
In SQL server, use:
select top 10 ...
e.g.
select top 100 * from myTable
select top 100 colA, colB from myTable
In MySQL, use:
select ... order by num desc limit 10
AJAX is simply Asyncronous JSON or XML (in most newer situations JSON). Because we are doing an ASYNC task we will likely be providing our users with a more enjoyable UI experience. In this specific case we are doing a FORM submission using AJAX.
Really quickly there are 4 general web actions GET
, POST
, PUT
, and DELETE
; these directly correspond with SELECT/Retreiving DATA
, INSERTING DATA
, UPDATING/UPSERTING DATA
, and DELETING DATA
. A default HTML/ASP.Net webform/PHP/Python or any other form
action is to "submit" which is a POST action. Because of this the below will all describe doing a POST. Sometimes however with http you might want a different action and would likely want to utilitize .ajax
.
/* attach a submit handler to the form */
$("#formoid").submit(function(event) {
/* stop form from submitting normally */
event.preventDefault();
/* get the action attribute from the <form action=""> element */
var $form = $(this),
url = $form.attr('action');
/* Send the data using post with element id name and name2*/
var posting = $.post(url, {
name: $('#name').val(),
name2: $('#name2').val()
});
/* Alerts the results */
posting.done(function(data) {
$('#result').text('success');
});
posting.fail(function() {
$('#result').text('failed');
});
});
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form id="formoid" action="studentFormInsert.php" title="" method="post">
<div>
<label class="title">First Name</label>
<input type="text" id="name" name="name">
</div>
<div>
<label class="title">Last Name</label>
<input type="text" id="name2" name="name2">
</div>
<div>
<input type="submit" id="submitButton" name="submitButton" value="Submit">
</div>
</form>
<div id="result"></div>
_x000D_
From jQuery website $.post
documentation.
Example: Send form data using ajax requests
$.post("test.php", $("#testform").serialize());
Example: Post a form using ajax and put results in a div
<!DOCTYPE html>
<html>
<head>
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
</head>
<body>
<form action="/" id="searchForm">
<input type="text" name="s" placeholder="Search..." />
<input type="submit" value="Search" />
</form>
<!-- the result of the search will be rendered inside this div -->
<div id="result"></div>
<script>
/* attach a submit handler to the form */
$("#searchForm").submit(function(event) {
/* stop form from submitting normally */
event.preventDefault();
/* get some values from elements on the page: */
var $form = $(this),
term = $form.find('input[name="s"]').val(),
url = $form.attr('action');
/* Send the data using post */
var posting = $.post(url, {
s: term
});
/* Put the results in a div */
posting.done(function(data) {
var content = $(data).find('#content');
$("#result").empty().append(content);
});
});
</script>
</body>
</html>
Without using OAuth or at minimum HTTPS (TLS/SSL) please don't use this method for secure data (credit card numbers, SSN, anything that is PCI, HIPAA, or login related)
Finally the right solution for PHP 5.3 and above: (added optional Timezone to the Example like mentioned in the comments)
$date = \DateTime::createFromFormat('Y-m-d H:i:s', $mysql_source_date, new \DateTimeZone('UTC'));
$date->setTimezone(new \DateTimeZone('Europe/Berlin')); // optional
echo $date->format('m/d/y h:i a');
In your application context, change the bean with id from emf
to entityManagerFactory
:
<bean id="emf"
class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="packagesToScan" value="org.wahid.cse.entity" />
<property name="dataSource" ref="dataSource" />
<property name="jpaProperties">
<props>
<prop key="hibernate.show_sql">true</prop>
<prop key="hibernate.hbm2ddl.auto">create</prop>
<prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
</props>
</property>
<property name="persistenceProvider">
<bean class="org.hibernate.jpa.HibernatePersistenceProvider"></bean>
</property>
</bean>
To
<bean id="entityManagerFactory"
class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="packagesToScan" value="org.wahid.cse.entity" />
<property name="dataSource" ref="dataSource" />
<property name="jpaProperties">
<props>
<prop key="hibernate.show_sql">true</prop>
<prop key="hibernate.hbm2ddl.auto">create</prop>
<prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
</props>
</property>
<property name="persistenceProvider">
<bean class="org.hibernate.jpa.HibernatePersistenceProvider"></bean>
</property>
</bean>
Credit to: curiousmind.jlion.com/exceltotextfile (Link no longer exists)
Script:
Sub MakeXML(iCaptionRow As Integer, iDataStartRow As Integer, sOutputFileName As String)
Dim Q As String
Q = Chr$(34)
Dim sXML As String
sXML = "<?xml version=" & Q & "1.0" & Q & " encoding=" & Q & "UTF-8" & Q & "?>"
sXML = sXML & "<rows>"
''--determine count of columns
Dim iColCount As Integer
iColCount = 1
While Trim$(Cells(iCaptionRow, iColCount)) > ""
iColCount = iColCount + 1
Wend
Dim iRow As Integer
iRow = iDataStartRow
While Cells(iRow, 1) > ""
sXML = sXML & "<row id=" & Q & iRow & Q & ">"
For icol = 1 To iColCount - 1
sXML = sXML & "<" & Trim$(Cells(iCaptionRow, icol)) & ">"
sXML = sXML & Trim$(Cells(iRow, icol))
sXML = sXML & "</" & Trim$(Cells(iCaptionRow, icol)) & ">"
Next
sXML = sXML & "</row>"
iRow = iRow + 1
Wend
sXML = sXML & "</rows>"
Dim nDestFile As Integer, sText As String
''Close any open text files
Close
''Get the number of the next free text file
nDestFile = FreeFile
''Write the entire file to sText
Open sOutputFileName For Output As #nDestFile
Print #nDestFile, sXML
Close
End Sub
Sub test()
MakeXML 1, 2, "C:\Users\jlynds\output2.xml"
End Sub
SQLite is database engine, .sqlite
or .db
should be a database. If you don't need to program anything, you can use a GUI like sqlitebrowser or anything like that to view the database contents.
There is also spatialite, https://www.gaia-gis.it/fossil/spatialite_gui/index
using System.ComponentModel;
private readonly BackgroundWorker worker = new BackgroundWorker();
worker.DoWork += worker_DoWork;
worker.RunWorkerCompleted += worker_RunWorkerCompleted;
private void worker_DoWork(object sender, DoWorkEventArgs e)
{
// run all background tasks here
}
private void worker_RunWorkerCompleted(object sender,
RunWorkerCompletedEventArgs e)
{
//update ui once worker complete his work
}
worker.RunWorkerAsync();
Track progress (optional, but often useful)
a) subscribe to ProgressChanged
event and use ReportProgress(Int32)
in DoWork
b) set worker.WorkerReportsProgress = true;
(credits to @zagy)
public JSONObject makJsonObject(int id[], String name[], String year[],
String curriculum[], String birthday[], int numberof_students)
throws JSONException {
JSONObject obj = null;
JSONArray jsonArray = new JSONArray();
for (int i = 0; i < numberof_students; i++) {
obj = new JSONObject();
try {
obj.put("id", id[i]);
obj.put("name", name[i]);
obj.put("year", year[i]);
obj.put("curriculum", curriculum[i]);
obj.put("birthday", birthday[i]);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
jsonArray.put(obj);
}
JSONObject finalobject = new JSONObject();
finalobject.put("student", jsonArray);
return finalobject;
}
It doesn't always need to be toolkit-dependent or one doesn't always need use the FontMetrics approach since it requires one to first obtain a graphics object which is absent in a web container or in a headless enviroment.
I have tested this in a web servlet and it does calculate the text width.
import java.awt.Font;
import java.awt.font.FontRenderContext;
import java.awt.geom.AffineTransform;
...
String text = "Hello World";
AffineTransform affinetransform = new AffineTransform();
FontRenderContext frc = new FontRenderContext(affinetransform,true,true);
Font font = new Font("Tahoma", Font.PLAIN, 12);
int textwidth = (int)(font.getStringBounds(text, frc).getWidth());
int textheight = (int)(font.getStringBounds(text, frc).getHeight());
Add the necessary values to these dimensions to create any required margin.
Close the cursor, if it is empty then deallocate it:
IF CURSOR_STATUS('global','myCursor') >= -1
BEGIN
IF CURSOR_STATUS('global','myCursor') > -1
BEGIN
CLOSE myCursor
END
DEALLOCATE myCursor
END
For Print Result to text file
we can follow
echo "test data" > test.txt
This will create test.txt file and written "test data"
If you want to append then
echo "test data" >> test.txt
Use first
which python
This will give the output as the location where my python interpreter (binary) is present.
This output could be any such as
/usr/bin/python
or
/bin/python
Now appropriately select the shebang line and use it.
To generalize we can use:
#!/usr/bin/env
or
#!/bin/env
inp0= pd.read_csv("bank_marketing_updated_v1.csv",skiprows=2)
or if you want to do in existing dataframe
simply do following command
I suggest you to use 2 queries:
db.collection.count()
will return total number of items. This value is stored somewhere in Mongo and it is not calculated.
db.collection.find().skip(20).limit(10)
here I assume you could use a sort by some field, so do not forget to add an index on this field. This query will be fast too.
I think that you shouldn't query all items and than perform skip and take, cause later when you have big data you will have problems with data transferring and processing.
UPDATE 2: A fork of this plugin has been merged with the main Eclipse Platform. You should find it pre-installed in the future Eclipse releases ;)
UPDATE: I released a new version, it's a little bit darker, now pretty everything that can be currently modified has been aligned to the theme colors. Have fun!
Here is a screenshot:
if you may like, I uploaded on github a dark theme I made some months ago to avoid blinding my eyes when spending many hours on the editor.. I made it because with all the others themes some Eclipse parts remains ugly and unstyled.
You can find it here: http://guari.github.io/eclipse-ui-theme/
With my Eclipse configurations works quite ok, if you'll find some elements that remains unstyled you can submit an issue or suggest a change and I'll try to correct it if it's possible ;) (remind that currently, CSS styling support in Eclipse it's uncomplete and sometimes buggy..)
Simple read example below:
using NPOI.HSSF.UserModel;
using NPOI.SS.UserModel;
//.....
private void button1_Click(object sender, EventArgs e)
{
HSSFWorkbook hssfwb;
using (FileStream file = new FileStream(@"c:\test.xls", FileMode.Open, FileAccess.Read))
{
hssfwb= new HSSFWorkbook(file);
}
ISheet sheet = hssfwb.GetSheet("Arkusz1");
for (int row = 0; row <= sheet.LastRowNum; row++)
{
if (sheet.GetRow(row) != null) //null is when the row only contains empty cells
{
MessageBox.Show(string.Format("Row {0} = {1}", row, sheet.GetRow(row).GetCell(0).StringCellValue));
}
}
}
By the way: on NPOI website here in Download section there is example package - a pack of C# examples. Try it, if you haven't yet. :)
You can use a Scanner
and its nextInt()
method.
Scanner also has nextLong()
for larger integers, if needed.
Use PHP_EOL
which outputs \r\n
or \n
depending on the OS.
Working successfuly :
sudo apt install libjpeg8-dev zlib1g-dev
It's definitely conceivable but I am not sure we're there yet. In the meantime, I'd recommend using something like Silverlight with IIS Smooth Streaming. Silverlight is plugin-based, but it works on Windows/OSX/Linux. Some day the HTML5 <video>
element will be the way to go, but that will lack support for a little while.
How to glue the code given here ...
Step-1. You need your own rating stars in res/drawable
...
Step-2 In res/drawable
you need ratingstars.xml
as follow ...
<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
<item android:id="@android:id/background"
android:drawable="@drawable/star_empty" />
<item android:id="@android:id/secondaryProgress"
android:drawable="@drawable/star_empty" />
<item android:id="@android:id/progress"
android:drawable="@drawable/star" />
</layer-list>
Step-3 In res/values
you need styles.xml
as follow ...
<?xml version="1.0" encoding="utf-8"?>
<resources>
<style name="foodRatingBar" parent="@android:style/Widget.RatingBar">
<item name="android:progressDrawable">@drawable/ratingstars</item>
<item name="android:minHeight">22dip</item>
<item name="android:maxHeight">22dip</item>
</style>
</resources>
Step-4 In your layout ...
<RatingBar
android:id="@+id/rtbProductRating"
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:numStars="5"
android:rating="3.5"
android:isIndicator="false"
style="@style/foodRatingBar"
/>
To empty a particular collection in a database:
model.remove(function(err, p){
if(err){
throw err;
} else{
console.log('No Of Documents deleted:' + p);
}
});
Note:
One possible explanation is a database trigger that fires for each DROP TABLE
statement. To find the trigger, query the _TRIGGERS
dictionary views:
select * from all_triggers
where trigger_type in ('AFTER EVENT', 'BEFORE EVENT')
disable any suspicious trigger with
alter trigger <trigger_name> disable;
and try re-running your DROP TABLE
statement
If we need only one column to be numeric
yyz$b <- as.numeric(as.character(yyz$b))
But, if all the columns needs to changed to numeric
, use lapply
to loop over the columns and convert to numeric
by first converting it to character
class as the columns were factor
.
yyz[] <- lapply(yyz, function(x) as.numeric(as.character(x)))
Both the columns in the OP's post are factor
because of the string "n/a"
. This could be easily avoided while reading the file using na.strings = "n/a"
in the read.table/read.csv
or if we are using data.frame
, we can have character
columns with stringsAsFactors=FALSE
(the default is stringsAsFactors=TRUE
)
Regarding the usage of apply
, it converts the dataset to matrix
and matrix
can hold only a single class. To check the class
, we need
lapply(yyz, class)
Or
sapply(yyz, class)
Or check
str(yyz)
Swift 2.0
You can do following thing to get hours and minute from a date :
let dateFromat = NSDateFormatter()
dateFromat.dateFormat = "hh:mm a"
let date = dateFromat.dateFromString(string1) // In your case its string1
print(date) // you will get - 11:59 AM
In [1]: x = "anmxcjkwnekmjkldm!^%@(*)#_+@78935014712jksdfs"
In [2]: len(x)
Out[2]: 45
Now, For positive index ranges for x is from 0 to 44 (i.e. length - 1)
In [3]: x[0]
Out[3]: 'a'
In [4]: x[45]
---------------------------------------------------------------------------
IndexError Traceback (most recent call last)
/home/<ipython console> in <module>()
IndexError: string index out of range
In [5]: x[44]
Out[5]: 's'
For Negative index, index ranges from -1 to -45
In [6]: x[-1]
Out[6]: 's'
In [7]: x[-45]
Out[7]: 'a
For negative index, negative [length -1] i.e. the last valid value of positive index will give second list element as the list is read in reverse order,
In [8]: x[-44]
Out[8]: 'n'
Other, index's examples,
In [9]: x[1]
Out[9]: 'n'
In [10]: x[-9]
Out[10]: '7'
This is something easy to do and it worked for me:
//Create a Javascript executor
JavascriptExecutor jst= (JavascriptExecutor) driver;
jst.executeScript("arguments[1].value = arguments[0]; ", 55, driver.findElement(By.id("id")));
55 = value assigned
Additional relevant info: A common need is to pass the ID of the object represented by the marker to some ajax call for the purpose of fetching more info from the server.
It seems that when we do:
marker.on('click', function(e) {...
The e
points to a MouseEvent, which does not let us get to the marker object. But there is a built-in this
object which strangely, requires us to use this.options
to get to the options
object which let us pass anything we need. In the above case, we can pass some ID in an option, let's say objid
then within the function above, we can get the value by invoking: this.options.objid
For Swift 4
let backgroundImage = UIImageView(frame: UIScreen.main.bounds)
backgroundImage.image = UIImage(named: "bg_name.png")
backgroundImage.contentMode = UIViewContentMode.scaleAspectFill
self.view.insertSubview(backgroundImage, at: 0)
This solution runs only one loop and has the minimun object to map numerals to roman letters
function RomantoNumeral(r){
let result = 0,
keys = {M:1000, D:500, C:100, L:50, C:100, L:50, X:10, V:5, I:1},
order = Object.keys(keys),
rom = Array.from(r)
rom.forEach((e, i)=>{
if( i < rom.length -1 && order.indexOf(e) > order.indexOf(rom[i+1])){
result -= keys[e]
} else {
result +=keys[e]
}
})
return result
}
RomantoNumeral('MMDCCCXXXVII') #2837
Here's your example in the "one" line.
this.$OuterDiv = $('<div></div>')
.hide()
.append($('<table></table>')
.attr({ cellSpacing : 0 })
.addClass("text")
)
;
Update: I thought I'd update this post since it still gets quite a bit of traffic. In the comments below there's some discussion about $("<div>")
vs $("<div></div>")
vs $(document.createElement('div'))
as a way of creating new elements, and which is "best".
I put together a small benchmark, and here are roughly the results of repeating the above options 100,000 times:
jQuery 1.4, 1.5, 1.6
Chrome 11 Firefox 4 IE9
<div> 440ms 640ms 460ms
<div></div> 420ms 650ms 480ms
createElement 100ms 180ms 300ms
jQuery 1.3
Chrome 11
<div> 770ms
<div></div> 3800ms
createElement 100ms
jQuery 1.2
Chrome 11
<div> 3500ms
<div></div> 3500ms
createElement 100ms
I think it's no big surprise, but document.createElement
is the fastest method. Of course, before you go off and start refactoring your entire codebase, remember that the differences we're talking about here (in all but the archaic versions of jQuery) equate to about an extra 3 milliseconds per thousand elements.
Update 2
Updated for jQuery 1.7.2 and put the benchmark on JSBen.ch
which is probably a bit more scientific than my primitive benchmarks, plus it can be crowdsourced now!
I had the same error using an UpdateView
I had this:
if form.is_valid() and form2.is_valid():
form.save()
form2.save()
return HttpResponseRedirect(self.get_success_url())
and I solved just doing:
if form.is_valid() and form2.is_valid():
form.save()
form2.save()
return HttpResponseRedirect(reverse_lazy('adopcion:solicitud_listar'))
webpack =>
renamed as build to dist
output: {
filename: '[name].bundle.js',
path: path.resolve(__dirname, 'dist'),
},
You should read that, it's still valid.
You'll adapt the function you use depending on your needs.
Basically:
if you already load all entries, say User.all
, then you should use length
to avoid another db query
if you haven't anything loaded, use count
to make a count query on your db
if you don't want to bother with these considerations, use size
which will adapt
Use a DecimalFormat object with a format string of "0.#".
Platform Architecture is not the reliable way. Instead us:
$ arch -i386 /usr/local/bin/python2.7
Python 2.7.9 (v2.7.9:648dcafa7e5f, Dec 10 2014, 10:10:46)
[GCC 4.2.1 (Apple Inc. build 5666) (dot 3)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import platform, sys
>>> platform.architecture(), sys.maxsize
(('64bit', ''), 2147483647)
>>> ^D
$ arch -x86_64 /usr/local/bin/python2.7
Python 2.7.9 (v2.7.9:648dcafa7e5f, Dec 10 2014, 10:10:46)
[GCC 4.2.1 (Apple Inc. build 5666) (dot 3)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import platform, sys
>>> platform.architecture(), sys.maxsize
(('64bit', ''), 9223372036854775807)
You can even say:
FollowHyperlink "www.google.com"
If you get Automation Error then use http://
:
ThisWorkbook.FollowHyperlink("http://www.google.com")
If you are trying to keep some parameters, while changing others, be sure to copy the state of the vue router query and not reuse it.
This works, since you are making an unreferenced copy:
const query = Object.assign({}, this.$route.query);
query.page = page;
query.limit = rowsPerPage;
await this.$router.push({ query });
while below will lead to Vue Router thinking you are reusing the same query and lead to the NavigationDuplicated
error:
const query = this.$route.query;
query.page = page;
query.limit = rowsPerPage;
await this.$router.push({ query });
Of course, you could decompose the query object, such as follows, but you'll need to be aware of all the query parameters to your page, otherwise you risk losing them in the resultant navigation.
const { page, limit, ...otherParams } = this.$route.query;
await this.$router.push(Object.assign({
page: page,
limit: rowsPerPage
}, otherParams));
);
Note, while the above example is for push()
, this works with replace()
too.
Tested with vue-router 3.1.6.
This is called the "shape" in NumPy, and can be requested via the .shape
attribute:
>>> a = zeros((2, 5))
>>> a.shape
(2, 5)
If you prefer a function, you could also use numpy.shape(a)
.
In my case mongodb
packages are named mongodb-org
and mongodb-org-*
So when I type sudo apt purge mongo
then tab
(for auto-completion) I can see all installed packages that start with mongo
.
Another option is to run the following command (which will list all packages that contain mongo
in their names or their descriptions):
dpkg -l | grep mongo
In summary, I would do (to purge all packages that start with mongo
):
sudo apt purge mongo*
and then (to make sure that no mongo packages are left):
dpkg -l | grep mongo
Of course, as mentioned by @alicanozkara, you will need to manually remove some directories like /var/log/mongodb
and /var/lib/mongodb
Running the following find
commands:
sudo find /etc/ -name "*mongo*"
and sudo find /var/ -name "*mongo*"
may also show some files that you may want to remove, like:
/etc/systemd/system/mongodb.service
/etc/apt/sources.list.d/mongodb-org-3.2.list
and:
/var/lib/apt/lists/repo.mongodb.*
You may also want to remove user and group mongodb
, to do so you need to run:
sudo userdel -r mongodb
sudo groupdel mongodb
To check whether mongodb
user/group exists or not, try:
cut -d: -f1 /etc/passwd | grep mongo
cut -d: -f1 /etc/group | grep mongo
I met this error and tried several ways you guys mentioned still didn't work. I even tried to reinstall Tomcat, still have this error.
The last thing I did was to remove the entire Netbeans and Tomcat. It finally worked out. I know this isn't a good way to solve problem, but if you are really hurry and don't know what to do.
General purpose normalisation function to format any timestamp from any timezone to other.
Very useful for storing datetimestamps of users from different timezones in a relational database. For database comparisons store timestamp as UTC and use with gmdate('Y-m-d H:i:s')
/**
* Convert Datetime from any given olsonzone to other.
* @return datetime in user specified format
*/
function datetimeconv($datetime, $from, $to)
{
try {
if ($from['localeFormat'] != 'Y-m-d H:i:s') {
$datetime = DateTime::createFromFormat($from['localeFormat'], $datetime)->format('Y-m-d H:i:s');
}
$datetime = new DateTime($datetime, new DateTimeZone($from['olsonZone']));
$datetime->setTimeZone(new DateTimeZone($to['olsonZone']));
return $datetime->format($to['localeFormat']);
} catch (\Exception $e) {
return null;
}
}
Usage:
$from = ['localeFormat' => "d/m/Y H:i A", 'olsonZone' => 'Asia/Calcutta']; $to = ['localeFormat' => "Y-m-d H:i:s", 'olsonZone' => 'UTC']; datetimeconv("14/05/1986 10:45 PM", $from, $to); // returns "1986-05-14 17:15:00"
In Swift3:
let fileUrl = Foundation.URL(string: filePath)
Had the error today on a 12c and none of the existing answers fit (no duplicates, no non-deterministic expressions in the WHERE clause). My case was related to that other possible cause of the error, according to Oracle's message text (emphasis below):
ORA-30926: unable to get a stable set of rows in the source tables
Cause: A stable set of rows could not be got because of large dml activity or a non-deterministic where clause.
The merge was part of a larger batch, and was executed on a live database with many concurrent users. There was no need to change the statement. I just committed the transaction before the merge, then ran the merge separately, and committed again. So the solution was found in the suggested action of the message:
Action: Remove any non-deterministic where clauses and reissue the dml.
Still anyone have this problem, use following code inside your form as below.
echo '<input type = "hidden" name = "_token" value = "'. csrf_token().'" >';
If you cannot find the process locking the table (cause it is alreay dead), it may be a thread still cleaning up like this
section TRANSACTION of
show engine innodb status;
at the end
---TRANSACTION 1135701157, ACTIVE 6768 sec
MySQL thread id 5208136, OS thread handle 0x7f2982e91700, query id 882213399 xxxIPxxx 82.235.36.49 my_user cleaning up
as mentionned in a comment in Clear transaction deadlock?
you can try killing the transaction thread directly, here with
KILL 5208136;
worked for me.
You can use the FileStream.Write(byte[] array, int offset, int count) method to write it out.
If your array name is "myArray" the code would be.
myStream.Write(myArray, 0, myArray.count);
If you want to some data after passing token in header so that try this code
const api = 'your api';
const token = JSON.parse(sessionStorage.getItem('data'));
const token = user.data.id; /*take only token and save in token variable*/
axios.get(api , { headers: {"Authorization" : `Bearer ${token}`} })
.then(res => {
console.log(res.data);
.catch((error) => {
console.log(error)
});
For AWS users.
I had to use the following steps to get there.
1) Ensure that pip and django are installed at the sudo level
2) Ensure that security group in-bound rules includ http on port 80 for 0.0.0.0/0
3) Add Public IP and DNS to ALLOWED_HOSTS
4) Launch development server with sudo on port 80
Site now available at either of the following (no need for :80 as that is default for http):
You will have to edit 2 files - 1. httpd-vhosts.conf & 2. httpd-xampp.conf
NOTE : Make sure u backup files ( httpd-xampp.conf ) and ( httpd-vhosts.conf ) , Both Files are located in Drive:\xampp\apache\conf\extra
Open httpd-vhosts.conf file and in the bottom of the file change it
<VirtualHost *:80>
DocumentRoot “E:/xampp/htdocs/”
ServerName localhost
<Directory E:/xampp/htdocs/>.
Require all granted
</Directory>
</VirtualHost>
Here E:/xampp is my project workspace, you can change it as per your settings
and Second Change is on httpd-xampp.conf file and in the bottom of the file change it
#
# New XAMPP security concept
#
<LocationMatch “^/(?i:(?:xampp|security|licenses|phpmyadmin|webalizer|server-status|server-info))”>
Order deny,allow
Allow from all
Allow from ::1 127.0.0.0/8
ErrorDocument 403 /error/XAMPP_FORBIDDEN.html.var
</LocationMatch>
Font.Name
, Font.XYZProperty
, etc are readonly as Font
is an immutable object, so you need to specify a new Font
object to replace it:
mainForm.lblName.Font = new Font("Arial", mainForm.lblName.Font.Size);
Check the constructor of the Font
class for further options.
The escape code "
can also be used instead of "
.
On Debian 7.0, 64-bit (Wheezy), just run:
sudo apt-get install libpq-dev
After you successfully installed libpq-dev, run:
bundle install
This way you can Create NSArray, NSMutableArray.
NSArray keys =[NSArray arrayWithObjects:@"key1",@"key2",@"key3",nil];
NSArray objects =[NSArray arrayWithObjects:@"value1",@"value2",@"value3",nil];
Using the standard CustomCreationConverter
, I was struggling to work how to generate the correct type (Person
or Employee
), because in order to determine this you need to analyse the JSON and there is no built in way to do this using the Create
method.
I found a discussion thread pertaining to type conversion and it turned out to provide the answer. Here is a link: Type converting.
What's required is to subclass JsonConverter
, overriding the ReadJson
method and creating a new abstract Create
method which accepts a JObject
.
The JObject class provides a means to load a JSON object and provides access to the data within this object.
The overridden ReadJson
method creates a JObject
and invokes the Create
method (implemented by our derived converter class), passing in the JObject
instance.
This JObject
instance can then be analysed to determine the correct type by checking existence of certain fields.
Example
string json = "[{
\"Department\": \"Department1\",
\"JobTitle\": \"JobTitle1\",
\"FirstName\": \"FirstName1\",
\"LastName\": \"LastName1\"
},{
\"Department\": \"Department2\",
\"JobTitle\": \"JobTitle2\",
\"FirstName\": \"FirstName2\",
\"LastName\": \"LastName2\"
},
{\"Skill\": \"Painter\",
\"FirstName\": \"FirstName3\",
\"LastName\": \"LastName3\"
}]";
List<Person> persons =
JsonConvert.DeserializeObject<List<Person>>(json, new PersonConverter());
...
public class PersonConverter : JsonCreationConverter<Person>
{
protected override Person Create(Type objectType, JObject jObject)
{
if (FieldExists("Skill", jObject))
{
return new Artist();
}
else if (FieldExists("Department", jObject))
{
return new Employee();
}
else
{
return new Person();
}
}
private bool FieldExists(string fieldName, JObject jObject)
{
return jObject[fieldName] != null;
}
}
public abstract class JsonCreationConverter<T> : JsonConverter
{
/// <summary>
/// Create an instance of objectType, based properties in the JSON object
/// </summary>
/// <param name="objectType">type of object expected</param>
/// <param name="jObject">
/// contents of JSON object that will be deserialized
/// </param>
/// <returns></returns>
protected abstract T Create(Type objectType, JObject jObject);
public override bool CanConvert(Type objectType)
{
return typeof(T).IsAssignableFrom(objectType);
}
public override bool CanWrite
{
get { return false; }
}
public override object ReadJson(JsonReader reader,
Type objectType,
object existingValue,
JsonSerializer serializer)
{
// Load JObject from stream
JObject jObject = JObject.Load(reader);
// Create target object based on JObject
T target = Create(objectType, jObject);
// Populate the object properties
serializer.Populate(jObject.CreateReader(), target);
return target;
}
}
None of this solution worked for me since I'm in a cross-domain scenario creating a bookmarklet like Pinterest's Pin It.
I've found a bookmarklet template on GitHub https://gist.github.com/kn0ll/1020251 that solved the problem of closing the Iframe sending the command from within it.
Since I can't access any element from parent window within the IFrame, this communication can only be made posting events between the two windows using window.postMessage
All these steps are on the GitHub link:
1- You have to inject a JS file on the parent page.
2- In this file injected on the parent, add a window event listner
window.addEventListener('message', function(e) {
var someIframe = window.parent.document.getElementById('iframeid');
someIframe.parentNode.removeChild(window.parent.document.getElementById('iframeid'));
});
This listener will handle the close and any other event you wish
3- Inside the Iframe page you send the close command via postMessage:
$(this).trigger('post-message', [{
event: 'unload-bookmarklet'
}]);
Follow the template on https://gist.github.com/kn0ll/1020251 and you'll be fine!
Hope it helps,
-webkit-transform: rotate(90deg);
The other answers are correct but they led to some alignment problems. On trying out different things this CSS piece code worked perfectly for me.
.vertical{
writing-mode:tb-rl;
-webkit-transform:rotate(90deg);
-moz-transform:rotate(90deg);
-o-transform: rotate(90deg);
-ms-transform:rotate(90deg);
transform: rotate(90deg);
white-space:nowrap;
display:block;
bottom:0;
width:20px;
height:20px;
}
In Android Studio 2.2.3 I think you can change default SDK location for all projects from the top menu:
File -> Project Structure...
A window like below shows up:
I had the same problem and it was because of IIS running on the server, you can stop it using IIS Manager if it is the case for you.
The problem is related to this error: Execution Policy Change
Start virtualenv by running the following command:
Command Line C: \ Users \ Name \ yourdjangofilesname > myvenv \ Scripts \ activate
NOTE: On Windows 10, you may receive an error by Windows PowerShell that the implementation of these scenarios is disabled on this system. In this case, open another Windows PowerShell with the "Run as Administrator" option. After that, try typing the following commands before starting your virtual environment:
C:\WINDOWS\system32> set-executionpolicy remotesigned
Execution Policy Change: The execution policy helps protect you from scripts that you do not trust. Changing the execution policy might expose you to the security risks described in the about_Execution_Policies help topic at http://go.microsoft.com/fwlink/?LinkID=135170.
Do you want to change the execution policy? [Y] Yes [A] Yes to All [N] No [L] No to All [S] Suspend [?] Help (default is "N"): A
After selection Y(es), close the Powershell admin window, and then go back to the Powershell Window(where you got the error) and run the command again.
> myenv\Scripts\activate and then python manage.py runserver 8085 ,
(8085 or any number if you want to change its default port to work on otherwise you dont need to point out anything. )
Thanks to mcandre, the answer is:
#python3
from inspect import currentframe, getframeinfo
frameinfo = getframeinfo(currentframe())
print(frameinfo.filename, frameinfo.lineno)
This one worked, double quotes when $user and $password are outside single quotes. Single quotes when inside a single quote statement.
mysql --user="$user" --password="$password" --database="$user" --execute='DROP DATABASE '$user'; CREATE DATABASE '$user';'