After years, I want to add another approach by using a view engine in Express.js
var fs = require('fs');
app.get('/test', function(req, res, next) {
var html = fs.readFileSync('./html/test.html', 'utf8')
res.render('test', { html: html })
// or res.send(html)
})
Then, do that in your views/test
if you choose res.render
method at the above code (I'm writing in EJS format):
<%- locals.html %>
That's all.
In this way, you don't need to break your View Engine arrangements.
jsPlumb is an option available that supports drag and drop, as seen by its numerous demos, including the Flowchart demo.
It is available in a free Community edition, and a paid Toolkit edition.
The Toolkit edition wraps the Community edition with a comprehensive data binding layer, as well as several UI widgets for building applications and integrations for popular libraries, and is commercially licensed.
You may want to try the following:
SELECT CONCAT(title, ' ', forename, ' ', surname) AS name
FROM customer c
JOIN (
SELECT MAX(id) max_id, customer_id
FROM customer_data
GROUP BY customer_id
) c_max ON (c_max.customer_id = c.customer_id)
JOIN customer_data cd ON (cd.id = c_max.max_id)
WHERE CONCAT(title, ' ', forename, ' ', surname) LIKE '%Smith%'
LIMIT 10, 20;
Note that a JOIN
is just a synonym for INNER JOIN
.
Test case:
CREATE TABLE customer (customer_id int);
CREATE TABLE customer_data (
id int,
customer_id int,
title varchar(10),
forename varchar(10),
surname varchar(10)
);
INSERT INTO customer VALUES (1);
INSERT INTO customer VALUES (2);
INSERT INTO customer VALUES (3);
INSERT INTO customer_data VALUES (1, 1, 'Mr', 'Bobby', 'Smith');
INSERT INTO customer_data VALUES (2, 1, 'Mr', 'Bob', 'Smith');
INSERT INTO customer_data VALUES (3, 2, 'Mr', 'Jane', 'Green');
INSERT INTO customer_data VALUES (4, 2, 'Miss', 'Jane', 'Green');
INSERT INTO customer_data VALUES (5, 3, 'Dr', 'Jack', 'Black');
Result (query without the LIMIT
and WHERE
):
SELECT CONCAT(title, ' ', forename, ' ', surname) AS name
FROM customer c
JOIN (
SELECT MAX(id) max_id, customer_id
FROM customer_data
GROUP BY customer_id
) c_max ON (c_max.customer_id = c.customer_id)
JOIN customer_data cd ON (cd.id = c_max.max_id);
+-----------------+
| name |
+-----------------+
| Mr Bob Smith |
| Miss Jane Green |
| Dr Jack Black |
+-----------------+
3 rows in set (0.00 sec)
In SQL Server, it does not seem possible without using ordering in the query. This is what I have used.
SELECT *
FROM
(
SELECT TOP 5 *
FROM [MyTable]
ORDER BY Id DESC /*Primary Key*/
) AS T
ORDER BY T.Id ASC; /*Primary Key*/
There are multiple ways to do this.
Events - already explained well.
ui router - explained above.
*
<superhero flight speed strength> Superman is here! </superhero>
<superhero speed> Flash is here! </superhero>
*
app.directive('superhero', function(){
return {
restrict: 'E',
scope:{}, // IMPORTANT - to make the scope isolated else we will pollute it in case of a multiple components.
controller: function($scope){
$scope.abilities = [];
this.addStrength = function(){
$scope.abilities.push("strength");
}
this.addSpeed = function(){
$scope.abilities.push("speed");
}
this.addFlight = function(){
$scope.abilities.push("flight");
}
},
link: function(scope, element, attrs){
element.addClass('button');
element.on('mouseenter', function(){
console.log(scope.abilities);
})
}
}
});
app.directive('strength', function(){
return{
require:'superhero',
link: function(scope, element, attrs, superHeroCtrl){
superHeroCtrl.addStrength();
}
}
});
app.directive('speed', function(){
return{
require:'superhero',
link: function(scope, element, attrs, superHeroCtrl){
superHeroCtrl.addSpeed();
}
}
});
app.directive('flight', function(){
return{
require:'superhero',
link: function(scope, element, attrs, superHeroCtrl){
superHeroCtrl.addFlight();
}
}
});
I know this a very much late reply but I saw this query recently And found a working scenario,
OnClick of Submit use the below code:
$('#Submit').click(function ()
{ $(this).html('<img src="icon-loading.gif" />'); // A GIF Image of Your choice
return false });
To Stop the Gif use the below code:
$('#Submit').ajaxStop();
As I can see, you are comparing the message with the empty string using ==.
Its very hard to write the full code, but I can tell the flow of code - first, create db class & method inide that which will return the connection. second, create a servelet(ex-login.java) & import that db class onto that servlet. third, create instance of imported db class with the help of new operator & call the connection method of that db class. fourth, creaet prepared statement & execute statement & put this code in try catch block for exception handling.Use if-else condition in the try block to navigate your login page based on success or failure.
I hope, it will help you. If any problem, then please revert.
Nikhil Pahariya
myjson={}
myjson["Country"]= {"KR": { "id": "220", "name": "South Korea"}}
myjson["Creative"]= {
"1067405": {
"id": "1067405",
"url": "https://cdn.gowadogo.com/559d1ba1-8d50-4c7f-b3f5-d80f918006e0.jpg"
},
"1067406": {
"id": "1067406",
"url": "https://cdn.gowadogo.com/3799a70d-339c-4ecb-bc1f-a959dde675b8.jpg"
},
"1067407": {
"id": "1067407",
"url": "https://cdn.gowadogo.com/180af6a5-251d-4aa9-9cd9-51b2fc77d0c6.jpg"
}
}
myjson["Offer"]= {
"advanced_targeting_enabled": "f",
"category_name": "E-commerce/ Shopping",
"click_lifespan": "168",
"conversion_cap": "50",
"currency": "USD",
"default_payout": "1.5"
}
json_data = json.dumps(myjson)
#reverse back into a json
paths=[]
def walk_the_tree(inputDict,suffix=None):
for key, value in inputDict.items():
if isinstance(value, dict):
if suffix==None:
suffix=key
else:
suffix+=":"+key
walk_the_tree(value,suffix)
else:
paths.append(suffix+":"+key+":"+value)
walk_the_tree(myjson)
print(paths)
#split and build your nested dictionary
json_specs = {}
for path in paths:
parts=path.split(':')
value=(parts[-1])
d=json_specs
for p in parts[:-1]:
if p==parts[-2]:
d = d.setdefault(p,value)
else:
d = d.setdefault(p,{})
print(json_specs)
Paths:
['Country:KR:id:220', 'Country:KR:name:South Korea', 'Country:Creative:1067405:id:1067405', 'Country:Creative:1067405:url:https://cdn.gowadogo.com/559d1ba1-8d50-4c7f-b3f5-d80f918006e0.jpg', 'Country:Creative:1067405:1067406:id:1067406', 'Country:Creative:1067405:1067406:url:https://cdn.gowadogo.com/3799a70d-339c-4ecb-bc1f-a959dde675b8.jpg', 'Country:Creative:1067405:1067406:1067407:id:1067407', 'Country:Creative:1067405:1067406:1067407:url:https://cdn.gowadogo.com/180af6a5-251d-4aa9-9cd9-51b2fc77d0c6.jpg', 'Country:Creative:Offer:advanced_targeting_enabled:f', 'Country:Creative:Offer:category_name:E-commerce/ Shopping', 'Country:Creative:Offer:click_lifespan:168', 'Country:Creative:Offer:conversion_cap:50', 'Country:Creative:Offer:currency:USD', 'Country:Creative:Offer:default_payout:1.5']
I recommend Google protocol buffers. I had the chance to test drive the library on a new project and it's remarkably easy to use. The library is heavily optimized for performance.
Protobuf is different than other serialization solutions mentioned here in the sense that it does not serialize your objects, but rather generates code for objects that are serialization according to your specification.
No need to go with GSON for this; Jackson can do either plain Maps/Lists:
ObjectMapper mapper = new ObjectMapper();
Map<String,Object> map = mapper.readValue(json, Map.class);
or more convenient JSON Tree:
JsonNode rootNode = mapper.readTree(json);
By the way, there is no reason why you could not actually create Java classes and do it (IMO) more conveniently:
public class Library {
@JsonProperty("libraryname")
public String name;
@JsonProperty("mymusic")
public List<Song> songs;
}
public class Song {
@JsonProperty("Artist Name") public String artistName;
@JsonProperty("Song Name") public String songName;
}
Library lib = mapper.readValue(jsonString, Library.class);
you can do it by using Sheetsee.js and tabletop.js
const string ua = "Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; WOW64; Trident/5.0)";
Request.Headers["User-Agent"] = ua;
var httpWorkerRequestField = Request.GetType().GetField("_wr", BindingFlags.Instance | BindingFlags.NonPublic);
if (httpWorkerRequestField != null)
{
var httpWorkerRequest = httpWorkerRequestField.GetValue(Request);
var knownRequestHeadersField = httpWorkerRequest.GetType().GetField("_knownRequestHeaders", BindingFlags.Instance | BindingFlags.NonPublic);
if (knownRequestHeadersField != null)
{
string[] knownRequestHeaders = (string[])knownRequestHeadersField.GetValue(httpWorkerRequest);
knownRequestHeaders[39] = ua;
}
}
$model = Mage::getModel('catalog/product'); //getting product model
$_products = $model->getCollection(); //getting product object for particular product id
foreach($_products as $_product) { ?>
<a href = '<?php echo $model->load($_product->getData("entity_id"))->getUrl_path(); ?>'> <img src= '<?php echo $model->load($_product->getData("entity_id"))->getImageUrl(); ?>' width="75px" height="75px"/></a>
<?php echo "<br/>".$model->load($_product->getData("entity_id"))->getPrice()."<br/>". $model->load($_product->getData("entity_id"))->getSpecial_price()."<br/>".$model->load($_product->getData("entity_id"))->getName()?>
<?php
Query plans can be obtained from an Extended Events session via the query_post_execution_showplan
event. Here's a sample XEvent session:
/*
Generated via "Query Detail Tracking" template.
*/
CREATE EVENT SESSION [GetExecutionPlan] ON SERVER
ADD EVENT sqlserver.query_post_execution_showplan(
ACTION(package0.event_sequence,sqlserver.plan_handle,sqlserver.query_hash,sqlserver.query_plan_hash,sqlserver.session_id,sqlserver.sql_text,sqlserver.tsql_frame,sqlserver.tsql_stack)),
/* Remove any of the following events (or include additional events) as desired. */
ADD EVENT sqlserver.error_reported(
ACTION(package0.event_sequence,sqlserver.client_app_name,sqlserver.database_id,sqlserver.plan_handle,sqlserver.query_hash,sqlserver.query_plan_hash,sqlserver.session_id,sqlserver.sql_text,sqlserver.tsql_frame,sqlserver.tsql_stack)
WHERE ([package0].[greater_than_uint64]([sqlserver].[database_id],(4)) AND [package0].[equal_boolean]([sqlserver].[is_system],(0)))),
ADD EVENT sqlserver.module_end(SET collect_statement=(1)
ACTION(package0.event_sequence,sqlserver.client_app_name,sqlserver.database_id,sqlserver.plan_handle,sqlserver.query_hash,sqlserver.query_plan_hash,sqlserver.session_id,sqlserver.sql_text,sqlserver.tsql_frame,sqlserver.tsql_stack)
WHERE ([package0].[greater_than_uint64]([sqlserver].[database_id],(4)) AND [package0].[equal_boolean]([sqlserver].[is_system],(0)))),
ADD EVENT sqlserver.rpc_completed(
ACTION(package0.event_sequence,sqlserver.client_app_name,sqlserver.database_id,sqlserver.plan_handle,sqlserver.query_hash,sqlserver.query_plan_hash,sqlserver.session_id,sqlserver.sql_text,sqlserver.tsql_frame,sqlserver.tsql_stack)
WHERE ([package0].[greater_than_uint64]([sqlserver].[database_id],(4)) AND [package0].[equal_boolean]([sqlserver].[is_system],(0)))),
ADD EVENT sqlserver.sp_statement_completed(SET collect_object_name=(1)
ACTION(package0.event_sequence,sqlserver.client_app_name,sqlserver.database_id,sqlserver.plan_handle,sqlserver.query_hash,sqlserver.query_plan_hash,sqlserver.session_id,sqlserver.sql_text,sqlserver.tsql_frame,sqlserver.tsql_stack)
WHERE ([package0].[greater_than_uint64]([sqlserver].[database_id],(4)) AND [package0].[equal_boolean]([sqlserver].[is_system],(0)))),
ADD EVENT sqlserver.sql_batch_completed(
ACTION(package0.event_sequence,sqlserver.client_app_name,sqlserver.database_id,sqlserver.plan_handle,sqlserver.query_hash,sqlserver.query_plan_hash,sqlserver.session_id,sqlserver.sql_text,sqlserver.tsql_frame,sqlserver.tsql_stack)
WHERE ([package0].[greater_than_uint64]([sqlserver].[database_id],(4)) AND [package0].[equal_boolean]([sqlserver].[is_system],(0)))),
ADD EVENT sqlserver.sql_statement_completed(
ACTION(package0.event_sequence,sqlserver.client_app_name,sqlserver.database_id,sqlserver.plan_handle,sqlserver.query_hash,sqlserver.query_plan_hash,sqlserver.session_id,sqlserver.sql_text,sqlserver.tsql_frame,sqlserver.tsql_stack)
WHERE ([package0].[greater_than_uint64]([sqlserver].[database_id],(4)) AND [package0].[equal_boolean]([sqlserver].[is_system],(0))))
ADD TARGET package0.ring_buffer
WITH (MAX_MEMORY=4096 KB,EVENT_RETENTION_MODE=ALLOW_SINGLE_EVENT_LOSS,MAX_DISPATCH_LATENCY=30 SECONDS,MAX_EVENT_SIZE=0 KB,MEMORY_PARTITION_MODE=NONE,TRACK_CAUSALITY=ON,STARTUP_STATE=OFF)
GO
After you create the session, (in SSMS) go to the Object Explorer and delve down into Management | Extended Events | Sessions. Right-click the "GetExecutionPlan" session and start it. Right-click it again and select "Watch Live Data".
Next, open a new query window and run one or more queries. Here's one for AdventureWorks:
USE AdventureWorks;
GO
SELECT p.Name AS ProductName,
NonDiscountSales = (OrderQty * UnitPrice),
Discounts = ((OrderQty * UnitPrice) * UnitPriceDiscount)
FROM Production.Product AS p
INNER JOIN Sales.SalesOrderDetail AS sod
ON p.ProductID = sod.ProductID
ORDER BY ProductName DESC;
GO
After a moment or two, you should see some results in the "GetExecutionPlan: Live Data" tab. Click one of the query_post_execution_showplan events in the grid, and then click the "Query Plan" tab below the grid. It should look similar to this:
EDIT: The XEvent code and the screen shot were generated from SQL/SSMS 2012 w/ SP2. If you're using SQL 2008/R2, you might be able to tweak the script to make it run. But that version doesn't have a GUI, so you'd have to extract the showplan XML, save it as a *.sqlplan file and open it in SSMS. That's cumbersome. XEvents didn't exist in SQL 2005 or earlier. So, if you're not on SQL 2012 or later, I'd strongly suggest one of the other answers posted here.
In DJango 3.0 the default value of a BooleanField in model.py is set like this:
class model_name(models.Model):
example_name = models.BooleanField(default=False)
Another solution is passing the read function to the constructor of Readable (cf doc stream readeable options)
var s = new Readable({read(size) {
this.push("your string here")
this.push(null)
}});
you can after use s.pipe for exemple
str.toLowerCase().replace(/[\*\^\'\!]/g, '').split(' ').join('-')
Not only does it depend on what keeps your users happy, but how much development time do you have? What kind of resources can you throw at the problem (software, hardware, and people)?
I don't mind a couple-few second delay for hosted applications if they're doing something "complex". If it's really simple, delays bother me.
Do not use communicate(input=""). It writes input to the process, closes its stdin and then reads all output.
Do it like this:
p=subprocess.Popen(["python","1st.py"],stdin=PIPE,stdout=PIPE)
# get output from process "Something to print"
one_line_output = p.stdout.readline()
# write 'a line\n' to the process
p.stdin.write('a line\n')
# get output from process "not time to break"
one_line_output = p.stdout.readline()
# write "n\n" to that process for if r=='n':
p.stdin.write('n\n')
# read the last output from the process "Exiting"
one_line_output = p.stdout.readline()
What you would do to remove the error:
all_the_process_will_tell_you = p.communicate('all you will ever say to this process\nn\n')[0]
But since communicate closes the stdout
and stdin
and stderr
, you can not read or write after you called communicate.
adb shell
am start -n com.package.name/com.package.name.ActivityName
Or you can use this directly:
adb shell am start -n com.package.name/com.package.name.ActivityName
You can also specify actions to be filter by your intent-filters:
am start -a com.example.ACTION_NAME -n com.package.name/com.package.name.ActivityName
When a constructor is invoked, although there is no object created till that point, we still know the kind of object that is gonna be created because the specific constructor of the class to which the object belongs to has already been called.
Virtual
keyword associated with a function means the function of a particular object type is gonna be called.
So, my thinking says that there is no need to make the virtual constructor because already the desired constructor whose object is gonna be created has been invoked and making constructor virtual is just a redundant thing to do because the object-specific constructor has already been invoked and this is same as calling class-specific function which is achieved through the virtual keyword.
Although the inner implementation won’t allow virtual constructor for vptr and vtable related reasons.
Another reason is that C++ is a statically typed language and we need to know the type of a variable at compile-time.
The compiler must be aware of the class type to create the object. The type of object to be created is a compile-time decision.
If we make the constructor virtual then it means that we don’t need to know the type of the object at compile-time(that’s what virtual function provide. We don’t need to know the actual object and just need the base pointer to point an actual object call the pointed object’s virtual functions without knowing the type of the object) and if we don’t know the type of the object at compile time then it is against the statically typed languages. And hence, run-time polymorphism cannot be achieved.
Hence, Constructor won’t be called without knowing the type of the object at compile-time. And so the idea of making a virtual constructor fails.
Short answer, no, there's no way to 'trigger' the default functionality of the html5 bubble inline before submission of the form, you can checkValidity()
on certain inputs, but again doesn't work as you would want. Short of preventing the default if you still want to submit the form once validation is complete, you can still process this style by doing the following:
Note, on forms you don't want the validation css styles to be applied, you can simply add the novalidate
attribute to the form.
HTML:
<form name="login" id="loginForm" method="POST">
<input type="email" name="username" placeholder="Email">
<input type="password" name="password" placeholder="Password">
<input type="submit" value="LOG IN" class="hero left clearBoth">
</form>
If you're not using SCSS, I would highly recommend looking into it, it's much more manageable, easy to write and less convoluted. Note: In the fiddle example, i do have the exact css that this will compile. I've also included a bubble style example.
SCSS:
form:not([novalidate]) {
input, textarea {
&:required {background: transparent url('/../../images/icons/red_asterisk.png') no-repeat 98% center;}
&:required:valid {background: transparent url('/../../images/icons/valid.png') no-repeat 98% center; @include box-shadow(0 0 5px #5cd053);border-color: #28921f;}
&:not(:focus):valid {box-shadow: none;border: 1px solid $g4;}
&:focus:invalid {background: transparent url('/../../images/icons/invalid.png') no-repeat 98% center; @include box-shadow(0 0 5px #d45252); border-color: #b03535}
}
}
span.formHintBubble {position:absolute; background:$g7; margin-top:50px;@include borderRadius(10px); padding:5px 40px 5px 10px; color:white; @include opacity(0.9); @include box-shadow(1px 1px 6px 1px rgba(0,0,0,0.2));
&:after {
@include triangle(30px, $g7, up); content: " "; margin-bottom:27px; left:25px;
}
.cross {background:black; border:1px solid $g3; @include borderRadius(10px); width:15px; height:15px; color:#fff; display:block; line-height:15px; position:absolute; right:5px; top:50%; margin-top:-7.5px; padding:0; text-align:center; font-size:10px; cursor:pointer;}
}
JAVASCRIPT:
Here, we can do some funky stuff to use the default messages and inherit them inside your own 'bubble' or error message box.
var form = $('form');
var item = form.find(':invalid').first();
var node = item.get(0);
var pos = item.position();
var message = node.validationMessage || 'Invalid value.';
var bubble = $('<span/>').html('<span class="formHintBubble" style="left: ' + pos.left + 'px; top:' + pos.top + 'px;">' + message + '<div class="cross">X</div></span>').contents();
bubble.insertAfter(item);
DEMO:
http://jsfiddle.net/shannonhochkins/wJkVS/
Enjoy and I hope I help others with HTML5 form validation as it's awesome, and it needs to get out there!
Shannon
// this is how I always do it
for (i = n; --i >= 0;){
...
}
in KotlinDSL you can use like this :
flavorDimensions ("PlaceApp")
productFlavors {
create("tapsi") {
setDimension("PlaceApp")
buildConfigField("String", "API_BASE_URL", "https://xxx/x/x/")
}
}
I had the same issue, my problem was that the firewall on the server wasn't open from the current ip address.
@Michael Durrant's answer ably covers the shell itself, but the shell environment also includes the various commands you use in the shell and these are going to be similar -- but not identical -- between OS X and linux. In general, both will have the same core commands and features (especially those defined in the Posix standard), but a lot of extensions will be different.
For example, linux systems generally have a useradd
command to create new users, but OS X doesn't. On OS X, you generally use the GUI to create users; if you need to create them from the command line, you use dscl
(which linux doesn't have) to edit the user database (see here). (Update: starting in macOS High Sierra v10.13, you can use sysadminctl -addUser
instead.)
Also, some commands they have in common will have different features and options. For example, linuxes generally include GNU sed
, which uses the -r
option to invoke extended regular expressions; on OS X, you'd use the -E
option to get the same effect. Similarly, in linux you might use ls --color=auto
to get colorized output; on macOS, the closest equivalent is ls -G
.
EDIT: Another difference is that many linux commands allow options to be specified after their arguments (e.g. ls file1 file2 -l
), while most OS X commands require options to come strictly first (ls -l file1 file2
).
Finally, since the OS itself is different, some commands wind up behaving differently between the OSes. For example, on linux you'd probably use ifconfig
to change your network configuration. On OS X, ifconfig
will work (probably with slightly different syntax), but your changes are likely to be overwritten randomly by the system configuration daemon; instead you should edit the network preferences with networksetup
, and then let the config daemon apply them to the live network state.
You can use the df.reindex() function in pandas. df is
Net Upper Lower Mid Zsore
Answer option
More than once a day 0% 0.22% -0.12% 2 65
Once a day 0% 0.32% -0.19% 3 45
Several times a week 2% 2.45% 1.10% 4 78
Once a week 1% 1.63% -0.40% 6 65
define an list of column names
cols = df.columns.tolist()
cols
Out[13]: ['Net', 'Upper', 'Lower', 'Mid', 'Zsore']
move the column name to wherever you want
cols.insert(0, cols.pop(cols.index('Mid')))
cols
Out[16]: ['Mid', 'Net', 'Upper', 'Lower', 'Zsore']
then use df.reindex()
function to reorder
df = df.reindex(columns= cols)
out put is: df
Mid Upper Lower Net Zsore
Answer option
More than once a day 2 0.22% -0.12% 0% 65
Once a day 3 0.32% -0.19% 0% 45
Several times a week 4 2.45% 1.10% 2% 78
Once a week 6 1.63% -0.40% 1% 65
I found that decreasing contrast, brightness and saturation a little makes blurred images more pretty so I combined various methods from stack overflow and made this Blur Class which deals with blurring images, changing brightness, saturation, contrast and size of the blurred images. It can also convert images from drawable to bitmap and vice-versa.
You can use -[NSString integerValue]
, -[NSString floatValue]
, etc. However, the correct (locale-sensitive, etc.) way to do this is to use -[NSNumberFormatter numberFromString:]
which will give you an NSNumber converted from the appropriate locale and given the settings of the NSNumberFormatter
(including whether it will allow floating point values).
Put the date in single quotes and move the parenthesis (after the 'yes'
) to the end:
INSERT INTO custorder
VALUES ('Kevin', 'yes' , STR_TO_DATE('1-01-2012', '%d-%m-%Y') ) ;
^ ^
---parenthesis removed--| and added here ------|
But you can always use dates without STR_TO_DATE()
function, just use the (Y-m-d) '20120101'
or '2012-01-01'
format. Check the MySQL docs: Date and Time Literals
INSERT INTO custorder
VALUES ('Kevin', 'yes', '2012-01-01') ;
Full thanks must go to Felix Kling for his excellent answer which I have gratefully used in my code. I offer a small enhancement of a boolean return value to report success or failure:
function recurse_copy($src, $dst) {
$dir = opendir($src);
$result = ($dir === false ? false : true);
if ($result !== false) {
$result = @mkdir($dst);
if ($result === true) {
while(false !== ( $file = readdir($dir)) ) {
if (( $file != '.' ) && ( $file != '..' ) && $result) {
if ( is_dir($src . '/' . $file) ) {
$result = recurse_copy($src . '/' . $file,$dst . '/' . $file);
} else {
$result = copy($src . '/' . $file,$dst . '/' . $file);
}
}
}
closedir($dir);
}
}
return $result;
}
I was getting this error even when all the relevant dependencies were in place because I hadn't created the schema in MySQL.
I thought it would be created automatically but it wasn't. Although the table itself will be created, you have to create the schema.
To plot just a selection of your columns you can select the columns of interest by passing a list to the subscript operator:
ax = df[['V1','V2']].plot(kind='bar', title ="V comp", figsize=(15, 10), legend=True, fontsize=12)
What you tried was df['V1','V2']
this will raise a KeyError
as correctly no column exists with that label, although it looks funny at first you have to consider that your are passing a list hence the double square brackets [[]]
.
import matplotlib.pyplot as plt
ax = df[['V1','V2']].plot(kind='bar', title ="V comp", figsize=(15, 10), legend=True, fontsize=12)
ax.set_xlabel("Hour", fontsize=12)
ax.set_ylabel("V", fontsize=12)
plt.show()
Maybe this old topic but i found this library is very helpful and easy to use
example for using it in android
Bitmap myBitmap = QRCode.from("www.example.org").bitmap();
ImageView myImage = (ImageView) findViewById(R.id.imageView);
myImage.setImageBitmap(myBitmap);
There is 'ncftp' which is available for installation in linux. This works on the FTP protocol and can be used to download files and folders recursively. works on linux. Has been used and is working fine for recursive folder/file transfer.
Check this link... http://www.ncftp.com/
I had an issue with R 2.15.3 whereby while trying to create a tree structure recursively on a shared network drive I would get a permission error.
To get around this oddity I manually create the structure;
mkdirs <- function(fp) {
if(!file.exists(fp)) {
mkdirs(dirname(fp))
dir.create(fp)
}
}
mkdirs("H:/foo/bar")
I've been reading that hashing functions like SHA256 weren't really intended for use with storing passwords: https://patrickmn.com/security/storing-passwords-securely/#notpasswordhashes
Instead adaptive key derivation functions like PBKDF2, bcrypt or scrypt were. Here is a PBKDF2 based one that Microsoft wrote for PasswordHasher in their Microsoft.AspNet.Identity library:
/* =======================
* HASHED PASSWORD FORMATS
* =======================
*
* Version 3:
* PBKDF2 with HMAC-SHA256, 128-bit salt, 256-bit subkey, 10000 iterations.
* Format: { 0x01, prf (UInt32), iter count (UInt32), salt length (UInt32), salt, subkey }
* (All UInt32s are stored big-endian.)
*/
public string HashPassword(string password)
{
var prf = KeyDerivationPrf.HMACSHA256;
var rng = RandomNumberGenerator.Create();
const int iterCount = 10000;
const int saltSize = 128 / 8;
const int numBytesRequested = 256 / 8;
// Produce a version 3 (see comment above) text hash.
var salt = new byte[saltSize];
rng.GetBytes(salt);
var subkey = KeyDerivation.Pbkdf2(password, salt, prf, iterCount, numBytesRequested);
var outputBytes = new byte[13 + salt.Length + subkey.Length];
outputBytes[0] = 0x01; // format marker
WriteNetworkByteOrder(outputBytes, 1, (uint)prf);
WriteNetworkByteOrder(outputBytes, 5, iterCount);
WriteNetworkByteOrder(outputBytes, 9, saltSize);
Buffer.BlockCopy(salt, 0, outputBytes, 13, salt.Length);
Buffer.BlockCopy(subkey, 0, outputBytes, 13 + saltSize, subkey.Length);
return Convert.ToBase64String(outputBytes);
}
public bool VerifyHashedPassword(string hashedPassword, string providedPassword)
{
var decodedHashedPassword = Convert.FromBase64String(hashedPassword);
// Wrong version
if (decodedHashedPassword[0] != 0x01)
return false;
// Read header information
var prf = (KeyDerivationPrf)ReadNetworkByteOrder(decodedHashedPassword, 1);
var iterCount = (int)ReadNetworkByteOrder(decodedHashedPassword, 5);
var saltLength = (int)ReadNetworkByteOrder(decodedHashedPassword, 9);
// Read the salt: must be >= 128 bits
if (saltLength < 128 / 8)
{
return false;
}
var salt = new byte[saltLength];
Buffer.BlockCopy(decodedHashedPassword, 13, salt, 0, salt.Length);
// Read the subkey (the rest of the payload): must be >= 128 bits
var subkeyLength = decodedHashedPassword.Length - 13 - salt.Length;
if (subkeyLength < 128 / 8)
{
return false;
}
var expectedSubkey = new byte[subkeyLength];
Buffer.BlockCopy(decodedHashedPassword, 13 + salt.Length, expectedSubkey, 0, expectedSubkey.Length);
// Hash the incoming password and verify it
var actualSubkey = KeyDerivation.Pbkdf2(providedPassword, salt, prf, iterCount, subkeyLength);
return actualSubkey.SequenceEqual(expectedSubkey);
}
private static void WriteNetworkByteOrder(byte[] buffer, int offset, uint value)
{
buffer[offset + 0] = (byte)(value >> 24);
buffer[offset + 1] = (byte)(value >> 16);
buffer[offset + 2] = (byte)(value >> 8);
buffer[offset + 3] = (byte)(value >> 0);
}
private static uint ReadNetworkByteOrder(byte[] buffer, int offset)
{
return ((uint)(buffer[offset + 0]) << 24)
| ((uint)(buffer[offset + 1]) << 16)
| ((uint)(buffer[offset + 2]) << 8)
| ((uint)(buffer[offset + 3]));
}
Note this requires Microsoft.AspNetCore.Cryptography.KeyDerivation nuget package installed which requires .NET Standard 2.0 (.NET 4.6.1 or higher). For earlier versions of .NET see the Crypto class from Microsoft's System.Web.Helpers library.
Update Nov 2015
Updated answer to use an implementation from a different Microsoft library which uses PBKDF2-HMAC-SHA256 hashing instead of PBKDF2-HMAC-SHA1 (note PBKDF2-HMAC-SHA1 is still secure if iterCount is high enough). You can check out the source the simplified code was copied from as it actually handles validating and upgrading hashes implemented from previous answer, useful if you need to increase iterCount in the future.
Use the span
tag
<style>
.redText
{
color:red;
}
.blackText
{
color:black;
font-weight:bold;
}
</style>
<span class="redText">My Name is:</span> <span class="blackText">Tintincute</span>
It's also a good idea to avoid inline styling. Use a custom CSS class instead.
// replace
return <p>hello</p>;
// with
return <p>{JSON.stringify(movies)}</p>;
Now you should see, that your code actually does work. What does not work is the console.log(movies)
. This is because movies
points to the old state. If you move your console.log(movies)
outside of useEffect
, right above the return, you will see the updated movies object.
Are you trying to remove a single value or all matching values?
If you are trying to remove a single value, how do you define the value you wish to remove?
The reason you don't get a key back when querying on values is because the dictionary could contain multiple keys paired with the specified value.
If you wish to remove all matching instances of the same value, you can do this:
foreach(var item in dic.Where(kvp => kvp.Value == value).ToList())
{
dic.Remove(item.Key);
}
And if you wish to remove the first matching instance, you can query to find the first item and just remove that:
var item = dic.First(kvp => kvp.Value == value);
dic.Remove(item.Key);
Note: The ToList()
call is necessary to copy the values to a new collection. If the call is not made, the loop will be modifying the collection it is iterating over, causing an exception to be thrown on the next attempt to iterate after the first value is removed.
For this problem you should:
Check whether the flashlight is available or not?
If so then Turn Off/On
If not then you can do whatever, according to your app needs.
For Checking availability of flash in the device:
You can use the following:
context.getPackageManager().hasSystemFeature(PackageManager.FEATURE_CAMERA_FLASH);
which will return true if a flash is available, false if not.
See:
http://developer.android.com/reference/android/content/pm/PackageManager.html for more information.
For turning on/off flashlight:
I googled out and got this about android.permission.FLASHLIGHT. Android manifests' permission looks promising:
<!-- Allows access to the flashlight -->
<permission android:name="android.permission.FLASHLIGHT"
android:permissionGroup="android.permission-group.HARDWARE_CONTROLS"
android:protectionLevel="normal"
android:label="@string/permlab_flashlight"
android:description="@string/permdesc_flashlight" />
Then make use of Camera and set Camera.Parameters. The main parameter used here is FLASH_MODE_TORCH.
eg.
Code Snippet to turn on camera flashlight.
Camera cam = Camera.open();
Parameters p = cam.getParameters();
p.setFlashMode(Parameters.FLASH_MODE_TORCH);
cam.setParameters(p);
cam.startPreview();
Code snippet to turn off camera led light.
cam.stopPreview();
cam.release();
I just found a project that uses this permission. Check quick-settings' src code. here http://code.google.com/p/quick-settings/ (Note: This link is now broken)
For Flashlight directly look http://code.google.com/p/quick-settings/source/browse/trunk/quick-settings/#quick-settings/src/com/bwx/bequick/flashlight (Note: This link is now broken)
Update6 You could also try to add a SurfaceView as described in this answer LED flashlight on Galaxy Nexus controllable by what API? This seems to be a solution that works on many phones.
Update 5 Major Update
I have found an alternative Link (for the broken links above): http://www.java2s.com/Open-Source/Android/Tools/quick-settings/com.bwx.bequick.flashlight.htm You can now use this link. [Update: 14/9/2012 This link is now broken]
Update 1
Another OpenSource Code : http://code.google.com/p/torch/source/browse/
Update 2
Example showing how to enable the LED on a Motorola Droid: http://code.google.com/p/droidled/
Another Open Source Code :
http://code.google.com/p/covedesigndev/
http://code.google.com/p/search-light/
Update 3 (Widget for turning on/off camera led)
If you want to develop a widget that turns on/off your camera led, then you must refer my answer Widget for turning on/off camera flashlight in android..
Update 4
If you want to set the intensity of light emerging from camera LED you can refer Can I change the LED intensity of an Android device? full post. Note that only rooted HTC devices support this feature.
** Issues:**
There are also some problems while turning On/Off flashlight. eg. for the devices not having FLASH_MODE_TORCH
or even if it has, then flashlight does not turn ON etc.
Typically Samsung creates a lot of problems.
You can refer to problems in the given below list:
Use camera flashlight in Android
Turn ON/OFF Camera LED/flash light in Samsung Galaxy Ace 2.2.1 & Galaxy Tab
That's because timer is a local variable to your function.
Try creating it outside of the function.
when we using this line open(filename, "a")
, that a
indicates the appending the file, that means allow to insert extra data to the existing file.
You can just use this following lines to append the text in your file
def FileSave(filename,content):
with open(filename, "a") as myfile:
myfile.write(content)
FileSave("test.txt","test1 \n")
FileSave("test.txt","test2 \n")
The JsonTools library is very complete. It can be found at Github.
To search an element in an array, you can use array_search
function and to remove an element from an array you can use unset
function. Ex:
<?php
$hackers = array ('Alan Kay', 'Peter Norvig', 'Linus Trovalds', 'Larry Page');
print_r($hackers);
// Search
$pos = array_search('Linus Trovalds', $hackers);
echo 'Linus Trovalds found at: ' . $pos;
// Remove from array
unset($hackers[$pos]);
print_r($hackers);
You can refer: https://www.php.net/manual/en/ref.array.php for more array related functions.
Read this article for better insight. Note: Numpy reports the shape of 3D arrays in the order layers, rows, columns.
$('.input').keypress(function (e) {
if (e.which == 13) {
$('form#login').submit();
return false; //<---- Add this line
}
});
Check out this stackoverflow answer: event.preventDefault() vs. return false
Essentially, "return false" is the same as calling e.preventDefault
and e.stopPropagation()
.
I was running into the same issue but was able to package all dependencies into my jar file using the Maven Shade Plugin
function_that_needs_strings(*my_list) # works!
Below code will give the output for number of days, by taking out the difference between two dates..
$str = "Jul 02 2013";
$str = strtotime(date("M d Y ")) - (strtotime($str));
echo floor($str/3600/24);
You can use browser default prompt window.
Instead of basic <input type="submit" (...) >
try:
<button onClick="if(confirm(\'are you sure ?\')){ this.form.submit() }">Save</button>
Based on the answer I linked to in my comment above, this should work:
delete from
(
select pf.* From PRODUCTFILTERS pf
where pf.id>=200
And pf.rowid in
(
Select rowid from PRODUCTFILTERS
inner join PRODUCTS on PRODUCTFILTERS.PRODUCTID = PRODUCTS.ID
And PRODUCTS.NAME= 'Mark'
)
);
or
delete from PRODUCTFILTERS where rowid in
(
select pf.rowid From PRODUCTFILTERS pf
where pf.id>=200
And pf.rowid in
(
Select PRODUCTFILTERS.rowid from PRODUCTFILTERS
inner join PRODUCTS on PRODUCTFILTERS.PRODUCTID = PRODUCTS.ID
And PRODUCTS.NAME= 'Mark'
)
);
iOS users also expect autocapitalization: In a standard text field, the first letter of a sentence in a case-sensitive language is automatically capitalized.
You can decide whether or not to implement such features; there is no dedicated API for any of the features just listed, so providing them is a competitive advantage.
Apple document is saying there is no API available for this feature and some other expected feature in a customkeyboard. so you need to find out your own logic to implement this.
Observable
, Observer
)ContainerAdapter
, ComponentAdapter
, FocusAdapter
, KeyAdapter
, MouseAdapter
are not adapters; they are actually Null Objects. Poor naming choice by Sun.BufferedInputStream
can decorate other streams such as FilterInputStream
)java.lang.Runtime#getRuntime()
is SingletonButtonGroup
for Mediator patternAction
, AbstractAction
may be used for different visual representations to execute same code -> Command patternand many more I guess
From the Maven docs, sounds like it's just a difference in which repository you install the package into:
Maybe there is some confusion in that "install" to the CI server installs it to it's local repository, which then you as a user are sharing?
npm start
runs a script that the app maker built for easy starting of the app
npm install
installs all the packages in package.json
run npm install
first
then run npm start
In Microsoft SQL SERVER - SQL Function
CREATE FUNCTION IsOverlapDates
(
@startDate1 as datetime,
@endDate1 as datetime,
@startDate2 as datetime,
@endDate2 as datetime
)
RETURNS int
AS
BEGIN
DECLARE @Overlap as int
SET @Overlap = (SELECT CASE WHEN (
(@startDate1 BETWEEN @startDate2 AND @endDate2) -- caters for inner and end date outer
OR
(@endDate1 BETWEEN @startDate2 AND @endDate2) -- caters for inner and start date outer
OR
(@startDate2 BETWEEN @startDate1 AND @endDate1) -- only one needed for outer range where dates are inside.
) THEN 1 ELSE 0 END
)
RETURN @Overlap
END
GO
--Execution of the above code
DECLARE @startDate1 as datetime
DECLARE @endDate1 as datetime
DECLARE @startDate2 as datetime
DECLARE @endDate2 as datetime
DECLARE @Overlap as int
SET @startDate1 = '2014-06-01 01:00:00'
SET @endDate1 = '2014-06-01 02:00:00'
SET @startDate2 = '2014-06-01 01:00:00'
SET @endDate2 = '2014-06-01 01:30:00'
SET @Overlap = [dbo].[IsOverlapDates] (@startDate1, @endDate1, @startDate2, @endDate2)
SELECT Overlap = @Overlap
In my opinion, the best solution involves neither images nor using the input's default value. Rather, it looks something like David Dorward's solution.
It's easy to implement and degrades nicely for screen readers and users with no javascript.
Take a look at the two examples here: http://attardi.org/labels/
I usually use the second method (labels2) on my forms.
Simple answer is that: Go to your console app's properties(project's properties).In the "Application" tab, just change the "Output type" to "Windows Application". That's all.
In my machine, ssh-keygen
was available from powershell.
Basically, the third parameter in loggedIn
should not be an integer, it should be an object of some kind, but we can't know for sure because you did not name the parameters in the method call. Provide the method signature so we can see for sure. Perhaps it takes an NSNumber
or something.
This prints the key combination directly to the image:
The first window shows 'z'
pressed, the second shows 'ctrl' + 'z'
pressed. When a key combination is used, a question mark appear.
Don't mess up with the question mark code, which is 63
.
import numpy as np
import cv2
im = np.zeros((100, 300), np.uint8)
cv2.imshow('Keypressed', im)
while True:
key = cv2.waitKey(0)
im_c = im.copy()
cv2.putText(
im_c,
f'{chr(key)} -> {key}',
(10, 60),
cv2.FONT_HERSHEY_SIMPLEX,
1,
(255,255,255),
2)
cv2.imshow('Keypressed', im_c)
if key == 27: break # 'ESC'
String is immutable it means that,the content of the String Object can't be change, once it is created. If you want to modify the content then you can go for StringBuffer/StringBuilder instead of String. StringBuffer and StringBuilder are mutable classes.
Because you are using quantified subpattern and as descried in Perl Doc,
By default, a quantified subpattern is "greedy", that is, it will match as many times as possible (given a particular starting location) while still allowing the rest of the pattern to match. If you want it to match the minimum number of times possible, follow the quantifier with a "?" . Note that the meanings don't change, just the "greediness":
*? //Match 0 or more times, not greedily (minimum matches)
+? //Match 1 or more times, not greedily
Thus, to allow your quantified pattern to make minimum match, follow it by ?
:
/location="(.*?)"/
Using jquery, try this. if your button id is say id= clickme
$("clickme").on('çlick', function(){
$(this).css('background-color', 'grey'); .......
you can do this with jdk >= 8
getComboBox().addItemListener(this::comboBoxitemStateChanged);
so
public void comboBoxitemStateChanged(ItemEvent e) {
if (e.getStateChange() == ItemEvent.SELECTED) {
YourObject selectedItem = (YourObject) e.getItem();
//TODO your actitons
}
}
Adding the following attribute within the opening < widget > tag worked for me. Simple and live reloads correctly on a Android 9 emulator. xmlns:android="http://schemas.android.com/apk/res/android"
<widget id="com.my.awesomeapp" version="1.0.0"
xmlns="http://www.w3.org/ns/widgets"
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:cdv="http://cordova.apache.org/ns/1.0">
With the advent of ES2015 Object.assign and computed property names the OP's code boils down to:
var obj = Object.assign.apply({}, $(itemsFromDom).map((i, el) => ({[el.id]: el.value})));
double.Parse("-"); raises an exception, while double.TryParse("-", out parsed); parses to 0 so I guess TryParse does more complex conversions.
I just found this when googling to solve the same problem, and had to make a minor change to the solution to make it work in my situation, as I had 2 similar substrings, "Sun" and "Sunstruck" to search for. The offered solution was locating the wrong entry when searching for "Sun". Data in column B
I added another column C, formulaes C1=" "&B1&" " and changed the search to =COUNTIF(B1:B10,"* "&A1&" *")>0, the extra column to allow finding the first of last entry in the concatenated string.
You can use list slicing to archive your goal:
n = 5
mylist = [1,2,3,4,5,6,7,8,9]
newlist = mylist[n:]
print newlist
Outputs:
[6, 7, 8, 9]
Or del
if you only want to use one list:
n = 5
mylist = [1,2,3,4,5,6,7,8,9]
del mylist[:n]
print mylist
Outputs:
[6, 7, 8, 9]
Bootstrap V3:
Once i was searching for laravel features then i got to know this amazing form validation. Later on, i amended glyphicon icon features. Now, it looks great.
<div class="col-md-12">
<div class="form-group has-error has-feedback">
<input id="enter email" name="email" type="text" placeholder="Enter email" class="form-control ">
<span class="glyphicon glyphicon-remove form-control-feedback"></span>
<span class="help-block"><p>The Email field is required.</p></span>
</div>
</div>
<div class="clearfix"></div>
<div class="col-md-6">
<div class="form-group has-error has-feedback">
<input id="account_holder_name" name="name" type="text" placeholder="Name" class="form-control ">
<span class="glyphicon glyphicon-remove form-control-feedback"></span>
<span class="help-block"><p>The Name field is required.</p></span>
</div>
</div>
<div class="col-md-6">
<div class="form-group has-error has-feedback">
<input id="check_np" name="check_no" type="text" placeholder="Check no" class="form-control ">
<span class="glyphicon glyphicon-remove form-control-feedback"></span>
<span class="help-block"><p>The Check No. field is required.</p></span>
</div>
</div>
Once i completed it i thought i should implement it in Codeigniter as well. So here is the Codeigniter-3 validation with Bootstrap:
Controller
function addData()
{
$this->load->library('form_validation');
$this->form_validation->set_rules('email','Email','trim|required|valid_email|max_length[128]');
if($this->form_validation->run() == FALSE)
{
//validation fails. Load your view.
$this->loadViews('Load your view','pass your data to view if any');
}
else
{
//validation pass. Your code here.
}
}
View
<div class="col-md-12">
<?php
$email_error = (form_error('email') ? 'has-error has-feedback' : '');
if(!empty($email_error)){
$emailData = '<span class="help-block">'.form_error('email').'</span>';
$emailClass = $email_error;
$emailIcon = '<span class="glyphicon glyphicon-remove form-control-feedback"></span>';
}
else{
$emailClass = $emailIcon = $emailData = '';
}
?>
<div class="form-group <?= $emailClass ?>">
<input id="enter email" name="email" type="text" placeholder="Enter email" class="form-control ">
<?= $emailIcon ?>
<?= $emailData ?>
</div>
</div>
Those answers aren't bad, but they are limited in that they don't actually allow you to enter data. We had a similar problem where we were using barcode readers to enter data into a field, but we wanted to suppress the keyboard.
This is what I put together, it works pretty well:
https://codepen.io/bobjase/pen/QrQQvd/
<!-- must be a select box with no children to suppress the keyboard -->
input: <select id="hiddenField" />
<span id="fakecursor" />
<input type="text" readonly="readonly" id="visibleField" />
<div id="cursorMeasuringDiv" />
#hiddenField {
height:17px;
width:1px;
position:absolute;
margin-left:3px;
margin-top:2px;
border:none;
border-width:0px 0px 0px 1px;
}
#cursorMeasuringDiv {
position:absolute;
visibility:hidden;
margin:0px;
padding:0px;
}
#hiddenField:focus {
border:1px solid gray;
border-width:0px 0px 0px 1px;
outline:none;
animation-name: cursor;
animation-duration: 1s;
animation-iteration-count: infinite;
}
@keyframes cursor {
from {opacity:0;}
to {opacity:1;}
}
// whenever the visible field gets focused
$("#visibleField").bind("focus", function(e) {
// silently shift the focus to the hidden select box
$("#hiddenField").focus();
$("#cursorMeasuringDiv").css("font", $("#visibleField").css("font"));
});
// whenever the user types on his keyboard in the select box
// which is natively supported for jumping to an <option>
$("#hiddenField").bind("keypress",function(e) {
// get the current value of the readonly field
var currentValue = $("#visibleField").val();
// and append the key the user pressed into that field
$("#visibleField").val(currentValue + e.key);
$("#cursorMeasuringDiv").text(currentValue + e.key);
// measure the width of the cursor offset
var offset = 3;
var textWidth = $("#cursorMeasuringDiv").width();
$("#hiddenField").css("marginLeft",Math.min(offset+textWidth,$("#visibleField").width()));
});
When you click in the <input>
box, it simulates a cursor in that box but really puts the focus on an empty <select>
box. Select boxes naturally allow for keypresses to support jumping to an element in the list so it was only a matter of rerouting the keypress to the original input and offsetting the simulated cursor.
This won't work for backspace, delete, etc... but we didn't need those. You could probably use jQuery's trigger to send the keyboard event directly to another input box somewhere but we didn't need to bother with that so I didn't do it.
For the record an alternative approach might be to make the clickable layer the overlay: you make it semi-transparent and then place the "overlay" image behind it (somewhat counterintuitively, the "overlay" image could then be opaque). Depending on what you're trying to do, you might well be able to get the exact same visual effect (of an image and a clickable layer semi-transparently superimposed on top of each other), while avoiding clickability problems (because the "overlay" is in fact in the background).
I am trying to parse JSON data returned from an ajax call, and the following is working for me:
Sample PHP code
$portfolio_array= Array('desc'=>'This is test description1','item1'=>'1.jpg','item2'=>'2.jpg');
echo json_encode($portfolio_array);
And in the .js, i am parsing like this:
var req=$.post("json.php", { id: "" + id + ""},
function(data) {
data=$.parseJSON(data);
alert(data.desc);
$.each(data, function(i,item){
alert(item);
});
})
.success(function(){})
.error(function(){alert('There was problem loading portfolio details.');})
.complete(function(){});
If you have multidimensional array like below
$portfolio_array= Array('desc'=>'This is test description 1','items'=> array('item1'=>'1.jpg','item2'=>'2.jpg'));
echo json_encode($portfolio_array);
Then the code below should work:
var req=$.post("json.php", { id: "" + id +
function(data) {
data=$.parseJSON(data);
alert(data.desc);
$.each(data.items, function(i,item){
alert(item);
});
})
.success(function(){})
.error(function(){alert('There was problem loading portfolio details.');})
.complete(function(){});
Please note the sub array key here is items, and suppose if you have xyz
then in place of data.items
use data.xyz
This can't be done with pure HTML.
However if you have access to PHP on the Apache server (you tagged the post "apache") it can be done easilly - se the PHP glob function. If not - you might try Server Side Include - it's an Apache thing, and I don't know much about it.
You can use setTimeout()
and clearTimeout()
in conjunction with jQuery.data
:
$(window).resize(function() {
clearTimeout($.data(this, 'resizeTimer'));
$.data(this, 'resizeTimer', setTimeout(function() {
//do something
alert("Haven't resized in 200ms!");
}, 200));
});
Update
I wrote an extension to enhance jQuery's default on
(& bind
)-event-handler. It attaches an event handler function for one or more events to the selected elements if the event was not triggered for a given interval. This is useful if you want to fire a callback only after a delay, like the resize event, or else.
https://github.com/yckart/jquery.unevent.js
;(function ($) {
var methods = { on: $.fn.on, bind: $.fn.bind };
$.each(methods, function(k){
$.fn[k] = function () {
var args = [].slice.call(arguments),
delay = args.pop(),
fn = args.pop(),
timer;
args.push(function () {
var self = this,
arg = arguments;
clearTimeout(timer);
timer = setTimeout(function(){
fn.apply(self, [].slice.call(arg));
}, delay);
});
return methods[k].apply(this, isNaN(delay) ? arguments : args);
};
});
}(jQuery));
Use it like any other on
or bind
-event handler, except that you can pass an extra parameter as a last:
$(window).on('resize', function(e) {
console.log(e.type + '-event was 200ms not triggered');
}, 200);
small scripts for drag and drop by angular
(function(angular) {
'use strict';
angular.module('drag', []).
directive('draggable', function($document) {
return function(scope, element, attr) {
var startX = 0, startY = 0, x = 0, y = 0;
element.css({
position: 'relative',
border: '1px solid red',
backgroundColor: 'lightgrey',
cursor: 'pointer',
display: 'block',
width: '65px'
});
element.on('mousedown', function(event) {
// Prevent default dragging of selected content
event.preventDefault();
startX = event.screenX - x;
startY = event.screenY - y;
$document.on('mousemove', mousemove);
$document.on('mouseup', mouseup);
});
function mousemove(event) {
y = event.screenY - startY;
x = event.screenX - startX;
element.css({
top: y + 'px',
left: x + 'px'
});
}
function mouseup() {
$document.off('mousemove', mousemove);
$document.off('mouseup', mouseup);
}
};
});
})(window.angular);
jq '.users[]|.first,.last' | paste - -
The answer marked is perfect but for one scenario, where in the dd and mm are actually single digits. the following regex is perfect in this case:
function validateDate(testdate) {_x000D_
var date_regex = /^(0?[1-9]|1[0-2])\/(0?[1-9]|1\d|2\d|3[01])\/(19|20)\d{2}$/ ;_x000D_
return date_regex.test(testdate);_x000D_
}
_x000D_
A 32 bit floating point number has 23 + 1 bits of mantissa and an 8 bit exponent (-126 to 127 is used though) so the largest number you can represent is:
(1 + 1 / 2 + ... 1 / (2 ^ 23)) * (2 ^ 127) =
(2 ^ 23 + 2 ^ 23 + .... 1) * (2 ^ (127 - 23)) =
(2 ^ 24 - 1) * (2 ^ 104) ~= 3.4e38
Consider using Roxterm instead.
roxterm --tab
opens a tab in the current window.
I did Install-Package Microsoft.AspNet.WebApi.Core -version 5.2.3
but it still did not work. Then looked in my project bin folder and saw that it still had the old System.Web.Mvc file.
So I manually copied the newer file from the package to the bin folder. Then I was up and running again.
I usually do this using zip
:
>>> df = pd.DataFrame([[i] for i in range(10)], columns=['num'])
>>> df
num
0 0
1 1
2 2
3 3
4 4
5 5
6 6
7 7
8 8
9 9
>>> def powers(x):
>>> return x, x**2, x**3, x**4, x**5, x**6
>>> df['p1'], df['p2'], df['p3'], df['p4'], df['p5'], df['p6'] = \
>>> zip(*df['num'].map(powers))
>>> df
num p1 p2 p3 p4 p5 p6
0 0 0 0 0 0 0 0
1 1 1 1 1 1 1 1
2 2 2 4 8 16 32 64
3 3 3 9 27 81 243 729
4 4 4 16 64 256 1024 4096
5 5 5 25 125 625 3125 15625
6 6 6 36 216 1296 7776 46656
7 7 7 49 343 2401 16807 117649
8 8 8 64 512 4096 32768 262144
9 9 9 81 729 6561 59049 531441
This is correct formula to find integers from i
to j
where i <= R <= j
FLOOR(min+RAND()*(max-min))
Many ways to skin this cat. I put a simple function in each table's package...
function exists( id_in in yourTable.id%type ) return boolean is
res boolean := false;
begin
for c1 in ( select 1 from yourTable where id = id_in and rownum = 1 ) loop
res := true;
exit; -- only care about one record, so exit.
end loop;
return( res );
end exists;
Makes your checks really clean...
IF pkg.exists(someId) THEN
...
ELSE
...
END IF;
Create the database, with Script Database as... CREATE To
Within SSMS on the source server, use the export wizard with the destination server database as the destination.
Your arguments are incorrect, error doesn't return an object containing status and message, it passed them as separate parameters in the order described below.
Taken from the angular docs:
So you'd need to change your code to:
$http.get(dataUrl)
.success(function (data){
$scope.data.products = data;
})
.error(function (error, status){
$scope.data.error = { message: error, status: status};
console.log($scope.data.error.status);
});
Obviously, you don't have to create an object representing the error, you could just create separate scope properties but the same principle applies.
Here is one approach. ifelse
is vectorized and it checks all rows for zero values of b
and replaces est
with (a - 5)/2.53
if that is the case.
df <- transform(df, est = ifelse(b == 0, (a - 5)/2.53, est))
=$W$4<=TODAY()
Returns true for dates up to and including today, false otherwise.
very basic:
<?php
$username = 'user';
$password = 'password';
$server = 'localhost';
// Opens a connection to a MySQL server
$connection = mysql_connect ($server, $username, $password) or die('try again in some minutes, please');
//if you want to suppress the error message, substitute the connection line for:
//$connection = @mysql_connect($server, $username, $password) or die('try again in some minutes, please');
?>
result:
Warning: mysql_connect() [function.mysql-connect]: Access denied for user 'user'@'localhost' (using password: YES) in /home/user/public_html/zdel1.php on line 6 try again in some minutes, please
as per Wrikken's recommendation below, check out a complete error handler for more complex, efficient and elegant solutions: http://www.php.net/manual/en/function.set-error-handler.php
You can't use it in the way you describe. The point about generic types, is that although you may not know them at "coding time", the compiler needs to be able to resolve them at compile time. Why? Because under the hood, the compiler will go away and create a new type (sometimes called a closed generic type) for each different usage of the "open" generic type.
In other words, after compilation,
DoesEntityExist<int>
is a different type to
DoesEntityExist<string>
This is how the compiler is able to enfore compile-time type safety.
For the scenario you describe, you should pass the type as an argument that can be examined at run time.
The other option, as mentioned in other answers, is that of using reflection to create the closed type from the open type, although this is probably recommended in anything other than extreme niche scenarios I'd say.
Yes, you want to use tee
:
tee - read from standard input and write to standard output and files
Just pipe your command to tee and pass the file as an argument, like so:
exec 1 | tee ${LOG_FILE}
exec 2 | tee ${LOG_FILE}
This both prints the output to the STDOUT and writes the same output to a log file. See man tee
for more information.
Note that this won't write stderr to the log file, so if you want to combine the two streams then use:
exec 1 2>&1 | tee ${LOG_FILE}
If there is any default export in the file, there isn't any need to use the curly braces in the import statement.
if there are more than one export in the file then we need to use curly braces in the import file so that which are necessary we can import.
You can find the complete difference when to use curly braces and default statement in the below YouTube video (very heavy Indian accent, including rolling on the r's...).
21. ES6 Modules. Different ways of using import/export, Default syntax in the code. ES6 | ES2015
It's part of the Oracle analytic functions.
This line:
<input type="password" name="PasswordInput"/>
should have an id attribute, like so:
<input type="password" name="PasswordInput" id="PasswordInput"/>
Warning about using TODAY (or any calcs in a column).
If you set up a filter and have JUST [Today] it it you should be fine.
But the moment you do something like [Today]-1 ... the view will no longer show up when trying to pick it for alerts.
Another microsoft wonder.
$("#grid_GridHeader").eq(0)
As noted above by other contributors, using a .bowerrc
file with the JSON
{ "directory": "some/path" }
is necessary -- HOWEVER, you may run into an issue on Windows while creating that file. If Windows gives you a message imploring you to add a "file name", simply use a text editor / IDE such as Notepad++.
Add the JSON to an unnamed file, save it as .bowerrc -- you're good to go!
Probably an easy assumption, but I hope this save others the unnecessary headache :)
<?php
$str = "I bought _ sheep";
preg_match("/I bought (.*?) sheep", $str, $match);
print_r($match);
?>
If you want more granularity and better decription, you could use NotImplementedException from commons-lang
Warning: Available before versions 2.6 and after versions 3.2, only.
You can also do it in easy way
def sum(numbers)
return 0 if numbers.length < 1
result = 0
numbers.each { |num| result += num }
result
end
Use string instead of char
like
char c[10];
scanf ("%s", c);
I belive it works nice.
Try this
<a href="javascript:window.open('','_self').close();">close</a>
Modified shA.t's query for more clarity:
-- t1 left join t2
SELECT t1.value, t2.value
FROM t1 LEFT JOIN t2 ON t1.value = t2.value
UNION ALL -- include duplicates
-- t1 right exclude join t2 (records found only in t2)
SELECT t1.value, t2.value
FROM t1 RIGHT JOIN t2 ON t1.value = t2.value
WHERE t1.value IS NULL
I had similar problem with loading FacebookSDK, I added ~/Documents/FacebookSDK (search where your frameworks are) to Framework search paths in Build settings and after that I was able to import the FBSDKShareKit module
If you are looking for a custom configuration section like following
<CustomApplicationConfig>
<Credentials Username="itsme" Password="mypassword"/>
<PrimaryAgent Address="10.5.64.26" Port="3560"/>
<SecondaryAgent Address="10.5.64.7" Port="3570"/>
<Site Id="123" />
<Lanes>
<Lane Id="1" PointId="north" Direction="Entry"/>
<Lane Id="2" PointId="south" Direction="Exit"/>
</Lanes>
</CustomApplicationConfig>
then you can use my implementation of configuration section so to get started add System.Configuration
assembly reference to your project
Look at the each nested elements I used, First one is Credentials with two attributes so lets add it first
Credentials Element
public class CredentialsConfigElement : System.Configuration.ConfigurationElement
{
[ConfigurationProperty("Username")]
public string Username
{
get
{
return base["Username"] as string;
}
}
[ConfigurationProperty("Password")]
public string Password
{
get
{
return base["Password"] as string;
}
}
}
PrimaryAgent and SecondaryAgent
Both has the same attributes and seem like a Address to a set of servers for a primary and a failover, so you just need to create one element class for both of those like following
public class ServerInfoConfigElement : ConfigurationElement
{
[ConfigurationProperty("Address")]
public string Address
{
get
{
return base["Address"] as string;
}
}
[ConfigurationProperty("Port")]
public int? Port
{
get
{
return base["Port"] as int?;
}
}
}
I'll explain how to use two different element with one class later in this post, let us skip the SiteId as there is no difference in it. You just have to create one class same as above with one property only. let us see how to implement Lanes collection
it is splitted in two parts first you have to create an element implementation class then you have to create collection element class
LaneConfigElement
public class LaneConfigElement : ConfigurationElement
{
[ConfigurationProperty("Id")]
public string Id
{
get
{
return base["Id"] as string;
}
}
[ConfigurationProperty("PointId")]
public string PointId
{
get
{
return base["PointId"] as string;
}
}
[ConfigurationProperty("Direction")]
public Direction? Direction
{
get
{
return base["Direction"] as Direction?;
}
}
}
public enum Direction
{
Entry,
Exit
}
you can notice that one attribute of LanElement
is an Enumeration and if you try to use any other value in configuration which is not defined in Enumeration application will throw an System.Configuration.ConfigurationErrorsException
on startup. Ok lets move on to Collection Definition
[ConfigurationCollection(typeof(LaneConfigElement), AddItemName = "Lane", CollectionType = ConfigurationElementCollectionType.BasicMap)]
public class LaneConfigCollection : ConfigurationElementCollection
{
public LaneConfigElement this[int index]
{
get { return (LaneConfigElement)BaseGet(index); }
set
{
if (BaseGet(index) != null)
{
BaseRemoveAt(index);
}
BaseAdd(index, value);
}
}
public void Add(LaneConfigElement serviceConfig)
{
BaseAdd(serviceConfig);
}
public void Clear()
{
BaseClear();
}
protected override ConfigurationElement CreateNewElement()
{
return new LaneConfigElement();
}
protected override object GetElementKey(ConfigurationElement element)
{
return ((LaneConfigElement)element).Id;
}
public void Remove(LaneConfigElement serviceConfig)
{
BaseRemove(serviceConfig.Id);
}
public void RemoveAt(int index)
{
BaseRemoveAt(index);
}
public void Remove(String name)
{
BaseRemove(name);
}
}
you can notice that I have set the AddItemName = "Lane"
you can choose whatever you like for your collection entry item, i prefer to use "add" the default one but i changed it just for the sake of this post.
Now all of our nested Elements have been implemented now we should aggregate all of those in a class which has to implement System.Configuration.ConfigurationSection
CustomApplicationConfigSection
public class CustomApplicationConfigSection : System.Configuration.ConfigurationSection
{
private static readonly ILog log = LogManager.GetLogger(typeof(CustomApplicationConfigSection));
public const string SECTION_NAME = "CustomApplicationConfig";
[ConfigurationProperty("Credentials")]
public CredentialsConfigElement Credentials
{
get
{
return base["Credentials"] as CredentialsConfigElement;
}
}
[ConfigurationProperty("PrimaryAgent")]
public ServerInfoConfigElement PrimaryAgent
{
get
{
return base["PrimaryAgent"] as ServerInfoConfigElement;
}
}
[ConfigurationProperty("SecondaryAgent")]
public ServerInfoConfigElement SecondaryAgent
{
get
{
return base["SecondaryAgent"] as ServerInfoConfigElement;
}
}
[ConfigurationProperty("Site")]
public SiteConfigElement Site
{
get
{
return base["Site"] as SiteConfigElement;
}
}
[ConfigurationProperty("Lanes")]
public LaneConfigCollection Lanes
{
get { return base["Lanes"] as LaneConfigCollection; }
}
}
Now you can see that we have two properties with name PrimaryAgent
and SecondaryAgent
both have the same type now you can easily understand why we had only one implementation class against these two element.
Before you can use this newly invented configuration section in your app.config (or web.config) you just need to tell you application that you have invented your own configuration section and give it some respect, to do so you have to add following lines in app.config (may be right after start of root tag).
<configSections>
<section name="CustomApplicationConfig" type="MyNameSpace.CustomApplicationConfigSection, MyAssemblyName" />
</configSections>
NOTE: MyAssemblyName should be without .dll e.g. if you assembly file name is myDll.dll then use myDll instead of myDll.dll
to retrieve this configuration use following line of code any where in your application
CustomApplicationConfigSection config = System.Configuration.ConfigurationManager.GetSection(CustomApplicationConfigSection.SECTION_NAME) as CustomApplicationConfigSection;
I hope above post would help you to get started with a bit complicated kind of custom config sections.
Happy Coding :)
****Edit****
To Enable LINQ on LaneConfigCollection
you have to implement IEnumerable<LaneConfigElement>
And Add following implementation of GetEnumerator
public new IEnumerator<LaneConfigElement> GetEnumerator()
{
int count = base.Count;
for (int i = 0; i < count; i++)
{
yield return base.BaseGet(i) as LaneConfigElement;
}
}
for the people who are still confused about how yield really works read this nice article
Two key points taken from above article are
it doesn’t really end the method’s execution. yield return pauses the method execution and the next time you call it (for the next enumeration value), the method will continue to execute from the last yield return call. It sounds a bit confusing I think… (Shay Friedman)
Yield is not a feature of the .Net runtime. It is just a C# language feature which gets compiled into simple IL code by the C# compiler. (Lars Corneliussen)
No, there is absolutely nothing wrong with using the !
operator in if..then..else
statements.
The naming of variables, and in your example, methods is what is important. If you are using:
if(!isPerson()) { ... } // Nothing wrong with this
However:
if(!balloons()) { ... } // method is named badly
It all comes down to readability. Always aim for what is the most readable and you won't go wrong. Always try to keep your code continuous as well, for instance, look at Bill the Lizards answer.
Add this code in web.config
under the <configuration>
tag as shown in image below. Your error should then be gone.
<configuration>
<appSettings>
<add key="owin:AutomaticAppStartup" value="false" />
</appSettings>
...
</configuration>
If you really want, you could always compile with Cython. This will generate C code, which you can then compile with any C compiler such as GCC.
Try jQuery.inArray()
Here is a jsfiddle link using the same code : http://jsfiddle.net/yrshaikh/SUKn2/
The $.inArray() method is similar to JavaScript's native .indexOf() method in that it returns -1 when it doesn't find a match. If the first element within the array matches value, $.inArray() returns 0
Example Code :
<html>
<head>
<style>
div { color:blue; }
span { color:red; }
</style>
<script src="http://code.jquery.com/jquery-latest.js"></script>
</head>
<body>
<div>"John" found at <span></span></div>
<div>4 found at <span></span></div>
<div>"Karl" not found, so <span></span></div>
<div>
"Pete" is in the array, but not at or after index 2, so <span></span>
</div>
<script>
var arr = [ 4, "Pete", 8, "John" ];
var $spans = $("span");
$spans.eq(0).text(jQuery.inArray("John", arr));
$spans.eq(1).text(jQuery.inArray(4, arr));
$spans.eq(2).text(jQuery.inArray("Karl", arr));
$spans.eq(3).text(jQuery.inArray("Pete", arr, 2));
</script>
</body>
</html>
Output:
"John" found at 3 4 found at 0 "Karl" not found, so -1 "Pete" is in the array, but not at or after index 2, so -1
Have a look at the example http://www.cplusplus.com/reference/clibrary/cstdarg/va_arg/, they pass the number of arguments to the method but you can ommit that and modify the code appropriately (see the example).
This error would suggest that User::where('email', '=', $userEmail)->first()
is returning null, rather than a problem with updating your model.
Check that you actually have a User before attempting to change properties on it, or use the firstOrFail()
method.
$UpdateDetails = User::where('email', $userEmail)->first();
if (is_null($UpdateDetails)) {
return false;
}
or using the firstOrFail()
method, theres no need to check if the user is null because this throws an exception (ModelNotFoundException
) when a model is not found, which you can catch using App::error()
http://laravel.com/docs/4.2/errors#handling-errors
$UpdateDetails = User::where('email', $userEmail)->firstOrFail();
You can use require as well to render images like
//then in the render function of Jsx insert the mainLogo variable
class NavBar extends Component {
render() {
return (
<nav className="nav" style={nbStyle}>
<div className="container">
//right below here
<img src={require('./logoWhite.png')} style={nbStyle.logo} alt="fireSpot"/>
</div>
</nav>
);
}
}
Try doing this:
adb kill-server && adb start-server
(that restarts adb) Also you can try to edit an adb config file .android/adb_usb.ini
and add a line 04e8
after the header. Restart adb required for changes to take effect.
It's not a good way, but for me it seems the most simplest.
Add an anchor tag which contains the modal data-target and data-toggle, have an id associated with it. (Can be added mostly anywhere in the html view)
<a href="" data-toggle="modal" data-target="#myModal" id="myModalShower"></a>
Now,
Inside the angular controller, from where you want to trigger the modal just use
angular.element('#myModalShower').trigger('click');
This will mimic a click to the button based on the angular code and the modal will appear.
I think the following should work:
// fire request
request({
url: url,
method: "POST",
json: requestData
}, ...
In this case, the Content-type: application/json
header is automatically added.
Try to use the new '@supports' feature, here is one good hack that you might like:
* UPDATE!!! * Microsoft Edge and Safari 9 both added support for the @supports feature in Fall 2015, Firefox also -- so here is my updated version for you:
/* Chrome 29+ (Only) */
@supports (-webkit-appearance:none) and (not (overflow:-webkit-marquee))
and (not (-ms-ime-align:auto)) and (not (-moz-appearance:none)) {
.selector { color:red; }
}
More info on this here (the reverse... Safari but not Chrome): [ is there a css hack for safari only NOT chrome? ]
The previous CSS Hack [before Edge and Safari 9 or newer Firefox versions]:
/* Chrome 28+ (now also Microsoft Edge, Firefox, and Safari 9+) */
@supports (-webkit-appearance:none) { .selector { color:red; } }
This worked for (only) chrome, version 28 and newer.
(The above chrome 28+ hack was not one of my creations. I found this on the web and since it was so good I sent it to BrowserHacks.com recently, there are others coming.)
August 17th, 2014 update: As I mentioned, I have been working on reaching more versions of chrome (and many other browsers), and here is one I crafted that handles chrome 35 and newer.
/* Chrome 35+ */
_::content, _:future, .selector:not(*:root) { color:red; }
In the comments below it was mentioned by @BoltClock about future, past, not... etc... We can in fact use them to go a little farther back in Chrome history.
So then this is one that also works but not 'Chrome-only' which is why I did not put it here. You still have to separate it by a Safari-only hack to complete the process. I have created css hacks to do this however, not to worry. Here are a few of them, starting with the simplest:
/* Chrome 26+, Safari 6.1+ */
_:past, .selector:not(*:root) { color:red; }
Or instead, this one which goes back to Chrome 22 and newer, but Safari as well...
/* Chrome 22+, Safari 6.1+ */
@media screen and (-webkit-min-device-pixel-ratio:0)
and (min-resolution:.001dpcm),
screen and(-webkit-min-device-pixel-ratio:0)
{
.selector { color:red; }
}
The block of Chrome versions 22-28 (more complicated but works nicely) are also possible to target via a combination I worked out:
/* Chrome 22-28 (Only!) */
@media screen and(-webkit-min-device-pixel-ratio:0)
{
.selector {-chrome-:only(;
color:red;
);}
}
Now follow up with this next couple I also created that targets Safari 6.1+ (only) in order to still separate Chrome and Safari. Updated to include Safari 8
/* Safari 6.1-7.0 */
@media screen and (-webkit-min-device-pixel-ratio:0) and (min-color-index:0)
{
.selector {(; color:blue; );}
}
/* Safari 7.1+ */
_::-webkit-full-page-media, _:future, :root .selector { color:blue; }
So if you put one of the Chrome+Safari hacks above, and then the Safari 6.1-7 and 8 hacks in your styles sequentially, you will have Chrome items in red, and Safari items in blue.
Push object into your array. Try this:
export class FormComponent implements OnInit {
name: string;
empoloyeeID : number;
empList: Array<{name: string, empoloyeeID: number}> = [];
constructor() {}
ngOnInit() {}
onEmpCreate(){
console.log(this.name,this.empoloyeeID);
this.empList.push({ name: this.name, empoloyeeID: this.empoloyeeID });
this.name = "";
this.empoloyeeID = 0;
}
}
You can see a difference between the two contexts when you launch your app directly from the home screen vs when your app is launched from another app via share intent.
Here a practical example of what "non-standard back stack behaviors", mentioned by @CommonSenseCode, means:
Suppose that you have two apps that communicate with each other, App1 and App2.
Launch App2:MainActivity from launcher. Then from MainActivity launch App2:SecondaryActivity. There, either using activity context or application context, both activities live in the same task and this is ok (given that you use all standard launch modes and intent flags). You can go back to MainActivity with a back press and in the recent apps you have only one task.
Suppose now that you are in App1 and launch App2:MainActivity with a share intent (ACTION_SEND or ACTION_SEND_MULTIPLE). Then from there try to launch App2:SecondaryActivity (always with all standard launch modes and intent flags). What happens is:
if you launch App2:SecondaryActivity with application context on Android < 10 you cannot launch all the activities in the same task. I have tried with android 7 and 8 and the SecondaryActivity is always launched in a new task (I guess is because App2:SecondaryActivity is launched with the App2 application context but you're coming from App1 and you didn't launch the App2 application directly. Maybe under the hood android recognize that and use FLAG_ACTIVITY_NEW_TASK). This can be good or bad depending on your needs, for my application was bad.
On Android 10 the app crashes with the message
"Calling startActivity() from outside of an Activity context requires the FLAG_ACTIVITY_NEW_TASK flag. Is this really what you want?".
So to make it work on Android 10 you have to use FALG_ACTIVITY_NEW_TASK and you cannot run all activities in the same task.
As you can see the behavior is different between android versions, weird.
if you launch App2:SecondaryActivity with activity context all goes well and you can run all the activities in the same task resulting in a linear backstack navigation.
I hope I have added some useful information
Java 8 added a new way of making Comparators that reduces the amount of code you have to write, Comparator.comparing. Also check out Comparator.reversed
Here's a sample
import org.junit.Test;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import static org.junit.Assert.assertTrue;
public class ComparatorTest {
@Test
public void test() {
List<Person> peopleList = new ArrayList<>();
peopleList.add(new Person("A", 1000));
peopleList.add(new Person("B", 1));
peopleList.add(new Person("C", 50));
peopleList.add(new Person("Z", 500));
//sort by name, ascending
peopleList.sort(Comparator.comparing(Person::getName));
assertTrue(peopleList.get(0).getName().equals("A"));
assertTrue(peopleList.get(peopleList.size() - 1).getName().equals("Z"));
//sort by name, descending
peopleList.sort(Comparator.comparing(Person::getName).reversed());
assertTrue(peopleList.get(0).getName().equals("Z"));
assertTrue(peopleList.get(peopleList.size() - 1).getName().equals("A"));
//sort by age, ascending
peopleList.sort(Comparator.comparing(Person::getAge));
assertTrue(peopleList.get(0).getAge() == 1);
assertTrue(peopleList.get(peopleList.size() - 1).getAge() == 1000);
//sort by age, descending
peopleList.sort(Comparator.comparing(Person::getAge).reversed());
assertTrue(peopleList.get(0).getAge() == 1000);
assertTrue(peopleList.get(peopleList.size() - 1).getAge() == 1);
}
class Person {
String name;
int age;
Person(String n, int a) {
name = n;
age = a;
}
public String getName() {
return name;
}
public int getAge() {
return age;
}
public void setName(String name) {
this.name = name;
}
public void setAge(int age) {
this.age = age;
}
}
}
Place your scripts in this order:
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
<!-- Optional theme -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap-theme.min.css">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datetimepicker/4.17.37/css/bootstrap-datetimepicker.min.css" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.10.6/moment.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datetimepicker/4.17.37/js/bootstrap-datetimepicker.min.js"></script>
The answer is a simple PowerShell
one-liner:
Get-WmiObject Win32_NetworkConnection | ft "RemoteName","LocalName" -A
If you only want to pull the UNC
for one particular drive, add a where statement:
Get-WmiObject Win32_NetworkConnection | where -Property 'LocalName' -eq 'Z:' | ft "RemoteName","LocalName" -A
There's also AppGyver Steroids that unites PhoneGap and Native UI nicely.
With Steroids you can add things like native tabs, native navigation bar, native animations and transitions, native modal windows, native drawer/panel (facebooks side menu) etc. to your PhoneGap app.
Here's a demo: http://youtu.be/oXWwDMdoTCk?t=20m17s
You will need a reference to the specific frame you want to close but assuming you have the reference dispose()
should close the frame.
jButton1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e)
{
frameToClose.dispose();
}
});
ALTER TABLE `table_name` ADD PRIMARY KEY( `column_name`);
Found these docu on the google docu pages:
In your example, you would get (if you picked the 3rd row) "C3:O3", cause C --> O is 12 columns
edit
Using the example on the docu:
// The code below will get the number of columns for the range C2:G8
// in the active spreadsheet, which happens to be "4"
var count = SpreadsheetApp.getActiveSheet().getRange(2, 3, 6, 4).getNumColumns(); Browser.msgBox(count);
The values between brackets:
2: the starting row = 2
3: the starting col = C
6: the number of rows = 6 so from 2 to 8
4: the number of cols = 4 so from C to G
So you come to the range: C2:G8
Here's a script I wrote to handle all of jQuery's dimension methods for hidden elements, even descendants of hidden parents. Note that, of course, there's a performance hit using this.
// Correctly calculate dimensions of hidden elements
(function($) {
var originals = {},
keys = [
'width',
'height',
'innerWidth',
'innerHeight',
'outerWidth',
'outerHeight',
'offset',
'scrollTop',
'scrollLeft'
],
isVisible = function(el) {
el = $(el);
el.data('hidden', []);
var visible = true,
parents = el.parents(),
hiddenData = el.data('hidden');
if(!el.is(':visible')) {
visible = false;
hiddenData[hiddenData.length] = el;
}
parents.each(function(i, parent) {
parent = $(parent);
if(!parent.is(':visible')) {
visible = false;
hiddenData[hiddenData.length] = parent;
}
});
return visible;
};
$.each(keys, function(i, dimension) {
originals[dimension] = $.fn[dimension];
$.fn[dimension] = function(size) {
var el = $(this[0]);
if(
(
size !== undefined &&
!(
(dimension == 'outerHeight' ||
dimension == 'outerWidth') &&
(size === true || size === false)
)
) ||
isVisible(el)
) {
return originals[dimension].call(this, size);
}
var hiddenData = el.data('hidden'),
topHidden = hiddenData[hiddenData.length - 1],
topHiddenClone = topHidden.clone(true),
topHiddenDescendants = topHidden.find('*').andSelf(),
topHiddenCloneDescendants = topHiddenClone.find('*').andSelf(),
elIndex = topHiddenDescendants.index(el[0]),
clone = topHiddenCloneDescendants[elIndex],
ret;
$.each(hiddenData, function(i, hidden) {
var index = topHiddenDescendants.index(hidden);
$(topHiddenCloneDescendants[index]).show();
});
topHidden.before(topHiddenClone);
if(dimension == 'outerHeight' || dimension == 'outerWidth') {
ret = $(clone)[dimension](size ? true : false);
} else {
ret = $(clone)[dimension]();
}
topHiddenClone.remove();
return ret;
};
});
})(jQuery);
Here is one way to “untrack” any files that are would otherwise be ignored under the current set of exclude patterns:
(GIT_INDEX_FILE=some-non-existent-file \
git ls-files --exclude-standard --others --directory --ignored -z) |
xargs -0 git rm --cached -r --ignore-unmatch --
This leaves the files in your working directory but removes them from the index.
The trick used here is to provide a non-existent index file to git ls-files so that it thinks there are no tracked files. The shell code above asks for all the files that would be ignored if the index were empty and then removes them from the actual index with git rm.
After the files have been “untracked”, use git status to verify that nothing important was removed (if so adjust your exclude patterns and use git reset -- path to restore the removed index entry). Then make a new commit that leaves out the “crud”.
The “crud” will still be in any old commits. You can use git filter-branch to produce clean versions of the old commits if you really need a clean history (n.b. using git filter-branch will “rewrite history”, so it should not be undertaken lightly if you have any collaborators that have pulled any of your historical commits after the “crud” was first introduced).
I case that someone need a solution for this, this is one:
if you use a dynamic USE statement all your query need to be dynamic, because it need to be everything in the same context.
You can try with SYNONYM, is basically an ALIAS to a specific Table, this SYNONYM is inserted into the sys.synonyms table so you have access to it from any context
Look this static statement:
CREATE SYNONYM MASTER_SCHEMACOLUMNS FOR Master.INFORMATION_SCHEMA.COLUMNS
SELECT * FROM MASTER_SCHEMACOLUMNS
Now dynamic:
DECLARE @SQL VARCHAR(200)
DECLARE @CATALOG VARCHAR(200) = 'Master'
IF EXISTS(SELECT * FROM sys.synonyms s WHERE s.name = 'CURRENT_SCHEMACOLUMNS')
BEGIN
DROP SYNONYM CURRENT_SCHEMACOLUMNS
END
SELECT @SQL = 'CREATE SYNONYM CURRENT_SCHEMACOLUMNS FOR '+ @CATALOG +'.INFORMATION_SCHEMA.COLUMNS';
EXEC sp_sqlexec @SQL
--Your not dynamic Code
SELECT * FROM CURRENT_SCHEMACOLUMNS
Now just change the value of @CATALOG and you will be able to list the same table but from different catalog.
Like this?
ALTER TABLE `tablename` ADD `new_col_name` INT NOT NULL DEFAULT 0;
How do I change Android Studio editor's background color?
Changing Editor's Background
Open Preference > Editor (In IDE Settings Section) > Colors & Fonts > Darcula or Any item available there
IDE will display a dialog like this, Press 'No'
Darcula color scheme has been set for editors. Would you like to set Darcula as default Look and Feel?
Changing IDE's Theme
Open Preference > Appearance (In IDE Settings Section) > Theme > Darcula or Any item available there
Press OK. Android Studio will ask you to restart the IDE.
This is the way Visual Studio is designed: One solution, one Visual Studio (VS) instance.
Besides switching between solutions in one VS instance, you can also open another VS instance and open your other solution with that one. Next to solutions there are as you said "projects". You can have multiple projects within one solution and therefore view many projects at the same time.
Note: this answer was originally written with regard to older versions of SourceTree for Windows, and is now out-of-date.
See my new answer for the current version of SourceTree for Windows, 1.5.2.0. I'm leaving this answer behind for historical purposes.
as I'm on Windows I don't have a command line tool nor do I know how to use one :( Is it the only way to get that sorted out? The GUI doesn't cover all the git's functions? — Original Poster
Regarding Git GUIs, no, they don't cover all of Git's functions. They don't even come close. I suggest you check out one of the answers in How do I edit an incorrect commit message in Git?, Git is flexible enough that there are multiple solutions...from the command line.
SourceTree might actually come with the msysgit bash shell already, or it might be able to use the standard Windows command shell. Either way, you open it up form SourceTree by clicking the Terminal button:
You set which terminal SourceTree uses (bash or Windows) here:
That being said, here's one way you can do it in SourceTree. Since you mentioned in the comments that you don't mind "reverting back to the faulty commit" (by which I assume you actually mean resetting, which is a different operation in Git), then here are the steps:
Reset current branch to this commit
, and selecting the hard reset option from the drop down. Regarding this comment:
if it's not possible because it's already pushed to Bitbucket, I would not mind creating a new repository and starting over.
Does this mean that you're the only person working on the repo? This is important because it's not trivial to change the history of a repo (like by amending a commit) without causing problems for your collaborators. However, assuming that you're the only person working on the repo, then the next thing you would want to do is force push your changed history to the remote.
Be aware, though, that because you did a hard reset to the faulty commit, then force pushing causes you to lose all work that come after it previously. If that's okay, then you might need to use the following command at the command line to do the force push, because I couldn't find an option to do it in SourceTree:
git push remote-repo head -f
This also assumes that BitBucket will allow you to force push to a repo.
You should really learn how to use Git from the command line anyways though, it'll make you more proficient in Git. #ProTip, use msysgit and turn on Quick Edit mode on in the terminal properties, so that you can double click to highlight a line of text, right click to copy, and right click again to paste. It's pretty quick.
I accomplished something similar using jQuery Waypoints.
There's a lot of moving parts, and quite a bit of logic (that I hope to get on GitHub some day soon), but essentially what you could do is...
fixed
.table.fixed
that make it invisible.sticky
to table.fixed
table.sticky.fixed
that position it just below the navbar and also make just the thead
content visible. This also has a z-index
so it is laid above the rest of the content..sticky
from the table.fixed
You have to duplicate the entire table DOM in order to ensure column widths line up appropriately.
If that sounds really complicated, you might want to try playing around with the DataTables plugin and the FixedHeader extension: https://datatables.net/extensions/fixedheader/
Thanks to @sehe for the one-line escape:
var escaped = new System.Xml.Linq.XText(unescaped).ToString();
I add to it the one-line un-escape:
var unescapedAgain = System.Xml.XmlReader.Create(new StringReader("<r>" + escaped + "</r>")).ReadElementString();
It is better if you don't kill a thread. A way could be to introduce a "try" block into the thread's cycle and to throw an exception when you want to stop the thread (for example a break/return/... that stops your for/while/...). I've used this on my app and it works...
However, if you want to do it anyway, search for regex pattern
<primaryAddress>[\s\S]*?<\/primaryAddress>
and replace it with empty string...
public class EmployeeApiController : ApiController
{
private readonly IEmployee _employeeRepositary;
public EmployeeApiController()
{
_employeeRepositary = new EmployeeRepositary();
}
public async Task<HttpResponseMessage> Create(EmployeeModel Employee)
{
var returnStatus = await _employeeRepositary.Create(Employee);
return Request.CreateResponse(HttpStatusCode.OK, returnStatus);
}
}
Persistance
public async Task<ResponseStatusViewModel> Create(EmployeeModel Employee)
{
var responseStatusViewModel = new ResponseStatusViewModel();
var connection = new SqlConnection(EmployeeConfig.EmployeeConnectionString);
var command = new SqlCommand("usp_CreateEmployee", connection);
command.CommandType = CommandType.StoredProcedure;
var pEmployeeName = new SqlParameter("@EmployeeName", SqlDbType.VarChar, 50);
pEmployeeName.Value = Employee.EmployeeName;
command.Parameters.Add(pEmployeeName);
try
{
await connection.OpenAsync();
await command.ExecuteNonQueryAsync();
command.Dispose();
connection.Dispose();
}
catch (Exception ex)
{
throw ex;
}
return responseStatusViewModel;
}
Repository
Task<ResponseStatusViewModel> Create(EmployeeModel Employee);
public class EmployeeConfig
{
public static string EmployeeConnectionString;
private const string EmployeeConnectionStringKey = "EmployeeConnectionString";
public static void InitializeConfig()
{
EmployeeConnectionString = GetConnectionStringValue(EmployeeConnectionStringKey);
}
private static string GetConnectionStringValue(string connectionStringName)
{
return Convert.ToString(ConfigurationManager.ConnectionStrings[connectionStringName]);
}
}
I tried sudo docker container stats
, and it will give out Container ID along with details of memory usage and Name, etc. If you want to stop viewing the process, do Ctrl+C
. I hope you find it useful.
You're apparently off by one day, exactly 86400 seconds. Use the number 2209161600 Not the number 2209075200 If you Google the two numbers, you'll find support for the above. I tried your formula but was always coming up 1 day different from my server. It's not obvious from the unix timestamp unless you think in unix instead of human time ;-) but if you double check then you'll see this might be correct.
You need to configure the security group as stated by cyraxjoe. Along with that you also need to open System port. Steps to open port in windows :-
yes there is. add
#!/usr/bin/env python
to the beginning of the file and do
chmod u+rx <file>
assuming your user owns the file, otherwise maybe adjust the group or world permissions.
.py files under windows are associated with python as the program to run when opening them just like MS word is run when opening a .docx for example.
Regardless of exception thrown or not in try
block - finally
block will be executed. Exception would not be caught.
Most of the answers here talk about virtual machines. I'm going to give you a one-liner response to this question that has helped me the most over the last couple years of using Docker. It's this:
Docker is just a fancy way to run a process, not a virtual machine.
Now, let me explain a bit more about what that means. Virtual machines are their own beast. I feel like explaining what Docker is will help you understand this more than explaining what a virtual machine is. Especially because there are many fine answers here telling you exactly what someone means when they say "virtual machine". So...
A Docker container is just a process (and its children) that is compartmentalized using cgroups inside the host system's kernel from the rest of the processes. You can actually see your Docker container processes by running ps aux
on the host. For example, starting apache2
"in a container" is just starting apache2
as a special process on the host. It's just been compartmentalized from other processes on the machine. It is important to note that your containers do not exist outside of your containerized process' lifetime. When your process dies, your container dies. That's because Docker replaces pid 1
inside your container with your application (pid 1
is normally the init system). This last point about pid 1
is very important.
As far as the filesystem used by each of those container processes, Docker uses UnionFS-backed images, which is what you're downloading when you do a docker pull ubuntu
. Each "image" is just a series of layers and related metadata. The concept of layering is very important here. Each layer is just a change from the layer underneath it. For example, when you delete a file in your Dockerfile while building a Docker container, you're actually just creating a layer on top of the last layer which says "this file has been deleted". Incidentally, this is why you can delete a big file from your filesystem, but the image still takes up the same amount of disk space. The file is still there, in the layers underneath the current one. Layers themselves are just tarballs of files. You can test this out with docker save --output /tmp/ubuntu.tar ubuntu
and then cd /tmp && tar xvf ubuntu.tar
. Then you can take a look around. All those directories that look like long hashes are actually the individual layers. Each one contains files (layer.tar
) and metadata (json
) with information about that particular layer. Those layers just describe changes to the filesystem which are saved as a layer "on top of" its original state. When reading the "current" data, the filesystem reads data as though it were looking only at the top-most layers of changes. That's why the file appears to be deleted, even though it still exists in "previous" layers, because the filesystem is only looking at the top-most layers. This allows completely different containers to share their filesystem layers, even though some significant changes may have happened to the filesystem on the top-most layers in each container. This can save you a ton of disk space, when your containers share their base image layers. However, when you mount directories and files from the host system into your container by way of volumes, those volumes "bypass" the UnionFS, so changes are not stored in layers.
Networking in Docker is achieved by using an ethernet bridge (called docker0
on the host), and virtual interfaces for every container on the host. It creates a virtual subnet in docker0
for your containers to communicate "between" one another. There are many options for networking here, including creating custom subnets for your containers, and the ability to "share" your host's networking stack for your container to access directly.
Docker is moving very fast. Its documentation is some of the best documentation I've ever seen. It is generally well-written, concise, and accurate. I recommend you check the documentation available for more information, and trust the documentation over anything else you read online, including Stack Overflow. If you have specific questions, I highly recommend joining #docker
on Freenode IRC and asking there (you can even use Freenode's webchat for that!).
just change the path:
"c:\program files\android\sdk" to "c:\progra~1\android\sdk"
or
"c:\program files (x86)\android\sdk" to "c:\progra~2\android\sdk"
note that the paths should not contain spaces.
MY PREFERRED METHOD is using fopen,fwrite and fclose [it will cost less CPU]
$f=fopen('myfile.txt','w');
fwrite($f,'new content');
fclose($f);
Warning for those using file_put_contents
It'll affect a lot in performance, for example [on the same class/situation] file_get_contents too: if you have a BIG FILE, it'll read the whole content in one shot and that operation could take a long waiting time
That's not true Jeff.
You simply have to select a folder within your IIS 7 Manager UI (e.g. Images or event the Default Web Application folder) and then click on "HTTP Response Headers". Then you have to click on "Set Common Header.." in the right pane and select the "Expire Web content". There you can easily configure a max-age of 24 hours by choosing "After:", entering "24" in the Textbox and choose "Hours" in the combobox.
Your first paragraph regarding the web.config entry is right. I'd add the cacheControlCustom-attribute to set the cache control header to "public" or whatever is needed in that case.
You can, of course, achieve the same by providing web.config entries (or files) as needed.
Edit: removed a confusing sentence :)
if you want to import reverse, import it from django.urls
from django.urls import reverse
Obviously this is only for Pydev, but I've worked out that you can get the very useful functions "Shift Right" and "Shift Left" (mapped by default to CTRL+ALT+. and CTRL+ALT+,) to become useful by changing their keybindings to "Pydev Editor Scope" from "Pydev View"
I use the code below to smooth-scroll an item (thisView) to the top.
It works also for GridLayoutManager with views of different heights:
View firstView = mRecyclerView.getChildAt(0);
int toY = firstView.getTop();
int firstPosition = mRecyclerView.getChildAdapterPosition(firstView);
View thisView = mRecyclerView.getChildAt(thisPosition - firstPosition);
int fromY = thisView.getTop();
mRecyclerView.smoothScrollBy(0, fromY - toY);
Seems to work good enough for a quick solution.
If you want to remain both filename (only) and extension, you may use %~nxF
:
FOR /R C:\Directory %F in (*.*) do echo %~nxF
A hacky way of printing a backslash that doesn't involve escaping is to pass its character code to chr
:
>>> print(chr(92))
\
Although not exactly answering the question as formulated, but if you need or can take the end result as string you can also use
string s = Char.ConvertFromUtf32(56);
which will give you surrogate UTF-16 pairs if needed, protecting you if you are out side of the BMP.
Your product
class needs a parameterless constructor. You can make it private, but Jackson needs the constructor.
As a side note: You should use Pascal casing for your class names. That is Product
, and not product
.
You need to take extra precautions when using user supplied data in HTML attributes. Because attributes has many more attack vectors than output inside HTML tags.
The only way to avoid XSS attacks is to encode everything except alphanumeric characters. Escape all characters with ASCII values less than 256 with the &#xHH; format. Which unfortunately may cause problems in your scenario, if you are using CSS classes and javascript to fetch those elements.
OWASP has a good description of how to mitigate HTML attribute XSS:
I encountered similar problem recently. The fix is to set the display property of the li items in the ordered list to list-item, and not display block, and ensure that the display property of ol is not list-item. i.e
li { display: list-item;}
With this, the html parser sees all li as the list item and assign the appropriate value to it, and sees the ol, as an inline-block or block element based on your settings, and doesn't try to assign any count value to it.
As Jeppe Stig Nielsen said, this thread already has great answers, but I thought this rather obvious subtlety was worth mentioning too.
using
directives specified inside namespaces can make for shorter code since they don't need to be fully qualified as when they're specified on the outside.
The following example works because the types Foo
and Bar
are both in the same global namespace, Outer
.
Presume the code file Foo.cs:
namespace Outer.Inner
{
class Foo { }
}
And Bar.cs:
namespace Outer
{
using Outer.Inner;
class Bar
{
public Foo foo;
}
}
That may omit the outer namespace in the using
directive, for short:
namespace Outer
{
using Inner;
class Bar
{
public Foo foo;
}
}
It is easier to compare dates using the java.util.Calendar
.
Here is what you might do:
Calendar toDate = Calendar.getInstance();
Calendar nowDate = Calendar.getInstance();
toDate.set(<set-year>,<set-month>,<set-day>);
if(!toDate.before(nowDate)) {
//display your report
} else {
// don't display the report
}
There is no such functionality but you can use a temporary file by File.createTempFile().
File temp = File.createTempFile(prefix, suffix);
// tell system to delete it when vm terminates.
temp.deleteOnExit();
Normally, When you copy a cell you will find the below statement written down in the status bar (in the bottom of your sheet)
"Select destination and Press Enter or Choose Paste"
Then you press whether Enter or choose paste to paste the value of the cell.
If you didn't press Esc afterwards you will be able to paste the value of the cell several times
Application.CutCopyMode = False does the same like the Esc button, if you removed it from your code you will find that you are able to paste the cell value several times again.
And if you closed the Excel without pressing Esc you will get the warning 'There is a large amount of information on the Clipboard....'
SELECT
COUNT(CASE WHEN rsp_ind = 0 then 1 ELSE NULL END) as "New",
COUNT(CASE WHEN rsp_ind = 1 then 1 ELSE NULL END) as "Accepted"
from tb_a
You can see the output for this request HERE
If you are using Jersey for REST API's you can do as below
You don't have to change your webservices implementation.
I will explain for Jersey 2.x
1) First add a ResponseFilter as shown below
import java.io.IOException;
import javax.ws.rs.container.ContainerRequestContext;
import javax.ws.rs.container.ContainerResponseContext;
import javax.ws.rs.container.ContainerResponseFilter;
public class CorsResponseFilter implements ContainerResponseFilter {
@Override
public void filter(ContainerRequestContext requestContext, ContainerResponseContext responseContext)
throws IOException {
responseContext.getHeaders().add("Access-Control-Allow-Origin","*");
responseContext.getHeaders().add("Access-Control-Allow-Methods", "GET, POST, DELETE, PUT");
}
}
2) then in the web.xml , in the jersey servlet declaration add the below
<init-param>
<param-name>jersey.config.server.provider.classnames</param-name>
<param-value>YOUR PACKAGE.CorsResponseFilter</param-value>
</init-param>
If your string is all caps then below method will work
labelTitle.text = remarks?.lowercased().firstUppercased
This extension will helps you
extension StringProtocol {
var firstUppercased: String {
guard let first = first else { return "" }
return String(first).uppercased() + dropFirst()
}
}
Generate values from the uniform distribution on the interval [a, b].
r = a + (b-a).*rand(100,1);
Combining the answers of kiamlaluno and Mark, along with formatOnSave to autointent code for Python:
{
"editor.formatOnSave": true,
"editor.autoIndent": "advanced",
"editor.detectIndentation": true,
"files.insertFinalNewline": true,
"files.trimTrailingWhitespace": true,
"editor.formatOnPaste": true,
"editor.multiCursorModifier": "ctrlCmd",
"editor.snippetSuggestions": "top",
"editor.rulers": [
{
"column": 79,
"color": "#424142"
},
100, // <- a ruler in the default color or as customized at column 0
{
"column": 120,
"color": "#ff0000"
},
],
}
I found that you can detect the command key in the latest version of Safari (7.0: 9537.71) if it is pressed in conjunction with another key. For example, if you want to detect ?+x:, you can detect the x key AND check if event.metaKey is set to true. For example:
var key = event.keyCode || event.charCode || 0;
console.log(key, event.metaKey);
When pressing x on it's own, this will output 120, false
. When pressing ?+x, it will output 120, true
This only seems to work in Safari - not Chrome
I'd like to add to Adjorn Linkz's answer.
If you need multiple handlers, you could just use lambda references
void onViewCreated(View view, Bundle savedInstanceState)
{
view.setOnClickListener(this::handler);
}
void handler(View v)
{
...
}
The trick here is that handler
method's signature matches View.OnClickListener.onClick
signature. This way, you won't need the View.OnClickListener
interface.
Also, you won't need any switch statements.
Sadly, this method is only limited to interfaces that require a single method, or a lambda.
if using /bin/sh
you can use:
if [ <condition> ] && [ <condition> ]; then
...
fi
if using /bin/bash
you can use:
if [[ <condition> && <condition> ]]; then
...
fi
Is there a method equivalent to getJSONArray in org.json so that I have proper error handling in case it isn't an array?
It depends on your input; i.e. the stuff you fetch from the URL. If the value of the "datasets" attribute is an associative array rather than a plain array, you will get a ClassCastException
.
But then again, the correctness of your old version also depends on the input. In the situation where your new version throws a ClassCastException
, the old version will throw JSONException
. Reference: http://www.json.org/javadoc/org/json/JSONObject.html#getJSONArray(java.lang.String)
you can also quote string
''+document.location+''.substring(2,3);
$("#id").select2("val", null); //this will not work..you can try
You should actually do this...intialise and then set the value..well this is also the way it worked for me.
$("#id").select2().select2("val", null);
$("#id").select2().select2("val", 'oneofthevaluehere');
Only who are using reactive forms : For native HTML elements [attr.disabled] will work but for material elements we need to dynamically disable the element.
this.form.get('controlname').disable();
Otherwise it will show in console warning message.
Using:
apt HelloImpl.java -classpath /sac/tools/thirdparty/jaxws-ri/jaxws-ri-2.1.4/lib/jsr181-api.jar:.
works but it gives me another error, see new question
Incase if you don't want to have a separate button, here is a another way. Attached a gesture on imageView itself, where on tap of image a alert will popup with two option. You will have the option to choose either from gallery/photo library or to cancel the alert.
import UIKit
import CoreData
class AddDetailsViewController: UIViewController, UITextFieldDelegate, UIImagePickerControllerDelegate, UINavigationControllerDelegate {
@IBOutlet weak var imageView: UIImageView!
var picker:UIImagePickerController? = UIImagePickerController()
@IBAction func saveButton(sender: AnyObject) {
let managedContext = (UIApplication.sharedApplication().delegate as? AppDelegate)!.managedObjectContext
let entity = NSEntityDescription.entityForName("Person", inManagedObjectContext: managedContext)
let person = Person(entity: entity!, insertIntoManagedObjectContext: managedContext)
person.image = UIImageJPEGRepresentation(imageView.image!, 1.0) //imageView.image
do {
try person.managedObjectContext?.save()
//people.append(person)
} catch let error as NSError {
print("Could not save \(error)")
}
}
override func viewDidLoad() {
super.viewDidLoad()
let tapGesture = UITapGestureRecognizer(target: self, action: #selector(AddDetailsViewController.tapGesture(_:)))
imageView.addGestureRecognizer(tapGesture)
imageView.userInteractionEnabled = true
picker?.delegate = self
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func tapGesture(gesture: UIGestureRecognizer) {
let alert:UIAlertController = UIAlertController(title: "Profile Picture Options", message: nil, preferredStyle: UIAlertControllerStyle.ActionSheet)
let gallaryAction = UIAlertAction(title: "Open Gallary", style: UIAlertActionStyle.Default) {
UIAlertAction in self.openGallary()
}
let cancelAction = UIAlertAction(title: "Cancel", style: UIAlertActionStyle.Cancel) {
UIAlertAction in self.cancel()
}
alert.addAction(gallaryAction)
alert.addAction(cancelAction)
self.presentViewController(alert, animated: true, completion: nil)
}
func openGallary() {
picker!.allowsEditing = false
picker!.sourceType = UIImagePickerControllerSourceType.PhotoLibrary
presentViewController(picker!, animated: true, completion: nil)
}
func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : AnyObject]) {
if let pickedImage = info[UIImagePickerControllerOriginalImage] as? UIImage {
imageView.contentMode = .ScaleAspectFit
imageView.image = pickedImage
}
dismissViewControllerAnimated(true, completion: nil)
}
func cancel(){
print("Cancel Clicked")
}
}
Adding more to the question, implemented the logic to store images in CoreData.
Since Marco's answer is deprecated, you must use the following syntax (according jasonlfunk's comment) :
$client = new \GuzzleHttp\Client();
$response = $client->request('POST', 'http://www.example.com/user/create', [
'form_params' => [
'email' => '[email protected]',
'name' => 'Test user',
'password' => 'testpassword',
]
]);
$response = $client->request('POST', 'http://www.example.com/files/post', [
'multipart' => [
[
'name' => 'file_name',
'contents' => fopen('/path/to/file', 'r')
],
[
'name' => 'csv_header',
'contents' => 'First Name, Last Name, Username',
'filename' => 'csv_header.csv'
]
]
]);
// PUT
$client->put('http://www.example.com/user/4', [
'body' => [
'email' => '[email protected]',
'name' => 'Test user',
'password' => 'testpassword',
],
'timeout' => 5
]);
// DELETE
$client->delete('http://www.example.com/user');
Usefull for long server operations.
$client = new \GuzzleHttp\Client();
$promise = $client->requestAsync('POST', 'http://www.example.com/user/create', [
'form_params' => [
'email' => '[email protected]',
'name' => 'Test user',
'password' => 'testpassword',
]
]);
$promise->then(
function (ResponseInterface $res) {
echo $res->getStatusCode() . "\n";
},
function (RequestException $e) {
echo $e->getMessage() . "\n";
echo $e->getRequest()->getMethod();
}
);
According to documentation, you can set headers :
// Set various headers on a request
$client->request('GET', '/get', [
'headers' => [
'User-Agent' => 'testing/1.0',
'Accept' => 'application/json',
'X-Foo' => ['Bar', 'Baz']
]
]);
If you want more details information, you can use debug
option like this :
$client = new \GuzzleHttp\Client();
$response = $client->request('POST', 'http://www.example.com/user/create', [
'form_params' => [
'email' => '[email protected]',
'name' => 'Test user',
'password' => 'testpassword',
],
// If you want more informations during request
'debug' => true
]);
Documentation is more explicits about new possibilities.
If you want to make Django version comparison, you could use django-nine
(pip install django-nine). For example, if Django version installed in your environment is 1.7.4, then the following would be true.
from nine import versions
versions.DJANGO_1_7 # True
versions.DJANGO_LTE_1_7 # True
versions.DJANGO_GTE_1_7 # True
versions.DJANGO_GTE_1_8 # False
versions.DJANGO_GTE_1_4 # True
versions.DJANGO_LTE_1_6 # False
The simple and fastest way to count spaces
String fav="foo hello me hi";
for( int i=0; i<fav.length(); i++ ) {
if(fav.charAt(i) == ' ' ) {
counter++;
}
}
If you like a chained operation, you can also use compress
function:
test = pd.Series({
383: 3.000000,
663: 1.000000,
726: 1.000000,
737: 9.000000,
833: 8.166667
})
test.compress(lambda x: x != 1)
# 383 3.000000
# 737 9.000000
# 833 8.166667
# dtype: float64
From the Posix man page of math.h:
The <math.h> header shall provide for the following constants. The
values are of type double and are accurate within the precision of the
double type.
M_PI Value of pi
M_PI_2 Value of pi/2
M_PI_4 Value of pi/4
M_1_PI Value of 1/pi
M_2_PI Value of 2/pi
M_2_SQRTPI
Value of 2/ sqrt pi
OK, I don't think the official snippet mentioned by galuszkak should be used everywhere, we should concern the case that some bug may be triggered during the handler such as hello_world
function. Whether the response is correct or uncorrect, the Access-Control-Allow-Origin
header is what we should concern. So, thing is very simple, just like bellow:
@blueprint.after_request # blueprint can also be app~~
def after_request(response):
header = response.headers
header['Access-Control-Allow-Origin'] = '*'
return response
That is all~~
Make sure that in the path to the project there is no foldername having whitespace. While creating a project the specified path folders must not contain any space in their naming.
A call to EntityManager.flush();
will force the data to be persist in the database immediately as EntityManager.persist()
will not (depending on how the EntityManager is configured : FlushModeType (AUTO or COMMIT) by default it's set to AUTO and a flush will be done automatically by if it's set to COMMIT the persitence of the data to the underlying database will be delayed when the transaction is commited).
import java.security.AlgorithmParameters;
import java.security.SecureRandom;
import java.security.spec.KeySpec;
import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.PBEKeySpec;
import javax.crypto.spec.SecretKeySpec;
class SecurityUtils {
private static final byte[] salt = { (byte) 0xA4, (byte) 0x0B, (byte) 0xC8,
(byte) 0x34, (byte) 0xD6, (byte) 0x95, (byte) 0xF3, (byte) 0x13 };
private static int BLOCKS = 128;
public static byte[] encryptAES(String seed, String cleartext)
throws Exception {
byte[] rawKey = getRawKey(seed.getBytes("UTF8"));
SecretKeySpec skeySpec = new SecretKeySpec(rawKey, "AES");
Cipher cipher = Cipher.getInstance("AES");
cipher.init(Cipher.ENCRYPT_MODE, skeySpec);
return cipher.doFinal(cleartext.getBytes("UTF8"));
}
public static byte[] decryptAES(String seed, byte[] data) throws Exception {
byte[] rawKey = getRawKey(seed.getBytes("UTF8"));
SecretKeySpec skeySpec = new SecretKeySpec(rawKey, "AES");
Cipher cipher = Cipher.getInstance("AES");
cipher.init(Cipher.DECRYPT_MODE, skeySpec);
return cipher.doFinal(data);
}
private static byte[] getRawKey(byte[] seed) throws Exception {
KeyGenerator kgen = KeyGenerator.getInstance("AES");
SecureRandom sr = SecureRandom.getInstance("SHA1PRNG");
sr.setSeed(seed);
kgen.init(BLOCKS, sr); // 192 and 256 bits may not be available
SecretKey skey = kgen.generateKey();
byte[] raw = skey.getEncoded();
return raw;
}
private static byte[] pad(byte[] seed) {
byte[] nseed = new byte[BLOCKS / 8];
for (int i = 0; i < BLOCKS / 8; i++)
nseed[i] = 0;
for (int i = 0; i < seed.length; i++)
nseed[i] = seed[i];
return nseed;
}
public static byte[] encryptPBE(String password, String cleartext)
throws Exception {
SecretKeyFactory factory = SecretKeyFactory
.getInstance("PBKDF2WithHmacSHA1");
KeySpec spec = new PBEKeySpec(password.toCharArray(), salt, 1024, 256);
SecretKey tmp = factory.generateSecret(spec);
SecretKey secret = new SecretKeySpec(tmp.getEncoded(), "AES");
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
cipher.init(Cipher.ENCRYPT_MODE, secret);
AlgorithmParameters params = cipher.getParameters();
byte[] iv = params.getParameterSpec(IvParameterSpec.class).getIV();
return cipher.doFinal(cleartext.getBytes("UTF-8"));
}
public static String decryptPBE(SecretKey secret, String ciphertext,
byte[] iv) throws Exception {
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
cipher.init(Cipher.DECRYPT_MODE, secret, new IvParameterSpec(iv));
return new String(cipher.doFinal(ciphertext.getBytes()), "UTF-8");
}
}
var audio = new Audio('audio_file.mp3');
function post()
{
var tval=document.getElementById("mess").value;
var inhtml=document.getElementById("chat_div");
inhtml.innerHTML=inhtml.innerHTML+"<p class='me'>Me:-"+tval+"</p>";
inhtml.innerHTML=inhtml.innerHTML+"<p class='demo'>Demo:-Hi! how are you</p>";
audio.play();
}
this code is from talkerscode For complete tutorial visit http://talkerscode.com/webtricks/play-sound-on-notification-using-javascript-and-php.php
For greater clarity, I want to add a clear example and running
openFileDialog1.FileName = "Select File";
openFileDialog1.DefaultExt = ".xls";
openFileDialog1.Filter = "Excel documents (.xls)|*.xls";
DialogResult result = openFileDialog1.ShowDialog();
if (result==DialogResult.OK)
{
string filename = openFileDialog1.FileName;
Excel.Application xlApp;
Excel.Workbook xlWorkBook;
Excel.Worksheet xlWorkSheet;
object misValue = System.Reflection.Missing.Value;
xlApp = new Excel.Application();
xlApp.Visible = false;
xlApp.DisplayAlerts = false;
xlWorkBook = xlApp.Workbooks.Open(filename, 0, true, 5, "", "", true, Microsoft.Office.Interop.Excel.XlPlatform.xlWindows, "\t", false, false, 0, true, 1, 0);
xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);
var numRows = xlWorkSheet.Range["A1"].Offset[xlWorkSheet.Rows.Count - 1, 0].End[Excel.XlDirection.xlUp].Row;
MessageBox.Show("Number of max row is : "+ numRows.ToString());
xlWorkBook.Close(true, misValue, misValue);
xlApp.Quit();
}
Maybe this answer is not quite what you're looking for, but it will fomat any language with the same keyboard shortcut. The solution are language specific keyboard shortcuts.
For every language you want to format, you must find and download a plugin for that, for example a html formatter and a C# formatter. And then you map the command for every plugin to the same key, but with a differnt context (see the link).
Greets
Try using ctypes to get the size of a void pointer:
import ctypes
print ctypes.sizeof(ctypes.c_voidp)
It'll be 4 for 32 bit or 8 for 64 bit.
I had a similar problem.
I think the problem is that when you try to enclose two or more functions that deals with an array type of variable, php will return an error.
Let's say for example this one.
$data = array('key1' => 'Robert', 'key2' => 'Pedro', 'key3' => 'Jose');
// This function returns the last key of an array (in this case it's $data)
$lastKey = array_pop(array_keys($data));
// Output is "key3" which is the last array.
// But php will return “Strict Standards: Only variables should
// be passed by reference” error.
// So, In order to solve this one... is that you try to cut
// down the process one by one like this.
$data1 = array_keys($data);
$lastkey = array_pop($data1);
echo $lastkey;
There you go!
I downgrade the support
previously it was
implementation 'com.android.support:appcompat-v7:27.0.2'
Use it
implementation 'com.android.support:appcompat-v7:27.1.0'
implementation 'com.android.support:design:27.1.0'
Its Working Happy Codng
There are at least five different ways to rename specific columns in pandas, and I have listed them below along with links to the original answers. I also timed these methods and found them to perform about the same (though YMMV depending on your data set and scenario). The test case below is to rename columns A
M
N
Z
to A2
M2
N2
Z2
in a dataframe with columns A
to Z
containing a million rows.
# Import required modules
import numpy as np
import pandas as pd
import timeit
# Create sample data
df = pd.DataFrame(np.random.randint(0,9999,size=(1000000, 26)), columns=list('ABCDEFGHIJKLMNOPQRSTUVWXYZ'))
# Standard way - https://stackoverflow.com/a/19758398/452587
def method_1():
df_renamed = df.rename(columns={'A': 'A2', 'M': 'M2', 'N': 'N2', 'Z': 'Z2'})
# Lambda function - https://stackoverflow.com/a/16770353/452587
def method_2():
df_renamed = df.rename(columns=lambda x: x + '2' if x in ['A', 'M', 'N', 'Z'] else x)
# Mapping function - https://stackoverflow.com/a/19758398/452587
def rename_some(x):
if x=='A' or x=='M' or x=='N' or x=='Z':
return x + '2'
return x
def method_3():
df_renamed = df.rename(columns=rename_some)
# Dictionary comprehension - https://stackoverflow.com/a/58143182/452587
def method_4():
df_renamed = df.rename(columns={col: col + '2' for col in df.columns[
np.asarray([i for i, col in enumerate(df.columns) if 'A' in col or 'M' in col or 'N' in col or 'Z' in col])
]})
# Dictionary comprehension - https://stackoverflow.com/a/38101084/452587
def method_5():
df_renamed = df.rename(columns=dict(zip(df[['A', 'M', 'N', 'Z']], ['A2', 'M2', 'N2', 'Z2'])))
print('Method 1:', timeit.timeit(method_1, number=10))
print('Method 2:', timeit.timeit(method_2, number=10))
print('Method 3:', timeit.timeit(method_3, number=10))
print('Method 4:', timeit.timeit(method_4, number=10))
print('Method 5:', timeit.timeit(method_5, number=10))
Output:
Method 1: 3.650640267
Method 2: 3.163998427
Method 3: 2.998530871
Method 4: 2.9918436889999995
Method 5: 3.2436501520000007
Use the method that is most intuitive to you and easiest for you to implement in your application.
for i=1,#target do
game.Players.target[i].Character:BreakJoints()
end
Is incorrect, if "target" contains "FakeNameHereSoNoStalkers" then the run code would be:
game.Players.target.1.Character:BreakJoints()
Which is completely incorrect.
c = game.Players:GetChildren()
Never use "Players:GetChildren()", it is not guaranteed to return only players.
Instead use:
c = Game.Players:GetPlayers()
if msg:lower()=="me" then
table.insert(people, source)
return people
Here you add the player's name in the list "people", where you in the other places adds the player object.
Fixed code:
local Admins = {"FakeNameHereSoNoStalkers"}
function Kill(Players)
for i,Player in ipairs(Players) do
if Player.Character then
Player.Character:BreakJoints()
end
end
end
function IsAdmin(Player)
for i,AdminName in ipairs(Admins) do
if Player.Name:lower() == AdminName:lower() then return true end
end
return false
end
function GetPlayers(Player,Msg)
local Targets = {}
local Players = Game.Players:GetPlayers()
if Msg:lower() == "me" then
Targets = { Player }
elseif Msg:lower() == "all" then
Targets = Players
elseif Msg:lower() == "others" then
for i,Plr in ipairs(Players) do
if Plr ~= Player then
table.insert(Targets,Plr)
end
end
else
for i,Plr in ipairs(Players) do
if Plr.Name:lower():sub(1,Msg:len()) == Msg then
table.insert(Targets,Plr)
end
end
end
return Targets
end
Game.Players.PlayerAdded:connect(function(Player)
if IsAdmin(Player) then
Player.Chatted:connect(function(Msg)
if Msg:lower():sub(1,6) == ":kill " then
Kill(GetPlayers(Player,Msg:sub(7)))
end
end)
end
end)
Don't use height property in input field.
Example:
.heighttext{
display:inline-block;
padding:15px 10px;
line-height:140%;
}
Always use padding and line-height css property. Its work perfect for all mobile device and all browser.
At the time you emit the very first line,
Artist Title Price Genre Disc Sale Tax Cash
to achieve "alignment", you have to know "in advance" how wide each column will need to be (otherwise, alignment is impossible). Once you do know the needed width for each column (there are several possible ways to achieve that depending on where your data's coming from), then the setw
function mentioned in the other answer will help, or (more brutally;-) you could emit carefully computed number of extra spaces (clunky, to be sure), etc. I don't recommend tabs anyway as you have no real control on how the final output device will render those, in general.
Back to the core issue, if you have each column's value in a vector<T>
of some sort, for example, you can do a first formatting pass to determine the maximum width of the column, for example (be sure to take into account the width of the header for the column, too, of course).
If your rows are coming "one by one", and alignment is crucial, you'll have to cache or buffer the rows as they come in (in memory if they fit, otherwise on a disk file that you'll later "rewind" and re-read from the start), taking care to keep updated the vector of "maximum widths of each column" as the rows do come. You can't output anything (not even the headers!), if keeping alignment is crucial, until you've seen the very last row (unless you somehow magically have previous knowledge of the columns' widths, of course;-).
>>> from collections import deque
>>> my_list = deque()
>>> my_list.append(1) # append right
>>> my_list.append(2) # append right
>>> my_list.append(3) # append right
>>> my_list.appendleft(100) # append left
>>> my_list
deque([100, 1, 2, 3])
>>> my_list[0]
100
[NOTE]:
collections.deque
is faster than Python pure list
in a loop Relevant-Post.
Did you install the drivers? See the Arduino installation instructions under #4. I don't know that machine but I doubt it doesn't have any COM ports.