Your vncserver have a configuration file somewher that set the display number. To do it automaticaly, one solution is to parse this file, extract the number and set it correctly. A simpler (better) is to have this display number set in a config script and use it in both your VNC server config and in your init scripts.
Note that RFC 6266 supersedes the RFCs referenced below. Section 7 outlines some of the related security concerns.
The authority on the content-disposition header is RFC 1806 and RFC 2183. People have also devised content-disposition hacking. It is important to note that the content-disposition header is not part of the HTTP 1.1 standard.
The HTTP 1.1 Standard (RFC 2616) also mentions the possible security side effects of content disposition:
15.5 Content-Disposition Issues
RFC 1806 [35], from which the often implemented Content-Disposition
(see section 19.5.1) header in HTTP is derived, has a number of very
serious security considerations. Content-Disposition is not part of
the HTTP standard, but since it is widely implemented, we are
documenting its use and risks for implementors. See RFC 2183 [49]
(which updates RFC 1806) for details.
Array indexes in JavaScript start at zero for the first item, so try this:
var firstArrayItem = myValues[0]
Of course, if you actually want the second item in the array at index 1, then it's myValues[1]
.
See Accessing array elements for more info.
For manually resetting the password in Wordpress DB, a simple MD5 hash is sufficient. (see reason below)
To prevent breaking backwards compatibility, MD5-hashed passwords stored in the database are still valid. When a user logs in with such a password, WordPress detects MD5 was used, rehashes the password using the more secure method, and stores the new hash in the database.
Source: http://eamann.com/tech/wordpress-password-hashing/
Update: this was an answer posted in 2014. I don't know if it still works for the latest version of WP since I don't work with WP anymore.
You need to do deep search if you use groups in options:
options={[
{ value: 'all', label: 'All' },
{
label: 'Specific',
options: [
{ value: 'one', label: 'One' },
{ value: 'two', label: 'Two' },
{ value: 'three', label: 'Three' },
],
},
]}
const deepSearch = (options, value, tempObj = {}) => {
if (options && value != null) {
options.find((node) => {
if (node.value === value) {
tempObj.found = node;
return node;
}
return deepSearch(node.options, value, tempObj);
});
if (tempObj.found) {
return tempObj.found;
}
}
return undefined;
};
Have you tried to access your page by typing "http://localhost:8012" (after restarting the apache)?
This does not need jquery, you could set a variable inside the if and use it in html or pass it thru your template system if any
<?php
$showDivFlag=false
$query3 = mysql_query($query3);
$numrows = mysql_num_rows($query3);
if ($numrows > 0){
$fvisit = mysql_fetch_array($result3);
$showDivFlag=true;
}else {
}
?>
later in html
<div id="results" <?php if ($showDivFlag===false){?>style="display:none"<?php } ?>>
After formatting the previous answer to my own code, I have found an efficient way to copy all necessary data if you are attempting to paste the values returned via AutoFilter
to a separate sheet.
With .Range("A1:A" & LastRow)
.Autofilter Field:=1, Criteria1:="=*" & strSearch & "*"
.Offset(1,0).SpecialCells(xlCellTypeVisible).Cells.Copy
Sheets("Sheet2").activate
DestinationRange.PasteSpecial
End With
In this block, the AutoFilter
finds all of the rows that contain the value of strSearch
and filters out all of the other values. It then copies the cells (using offset in case there is a header), opens the destination sheet and pastes the values to the specified range on the destination sheet.
The public keyword is an access specifier, which allows the programmer to control the visibility of class members. When a class member is preceded by public, then that member may be accessed by code outside the class in which it is declared. (The opposite of public is private, which prevents a member from being used by code defined outside of its class.)
In this case, main( )
must be declared as public, since it must be called by code outside of its class when the program is started.
The keyword static allows main( )
to be called without having to instantiate a particular instance of the class. This is necessary since main( )
is called by the Java interpreter before any objects are made.
The keyword void simply tells the compiler that main( )
does not return a value. As you will see, methods may also return values.
The static keyword, when applied to a class, tells the compiler to create a single instance of that class. It is not then possible to 'new' one or more instance of the class. All methods in a static class must themselves be declared static.
It is possible, And often desirable, to have static methods of a non-static class. For example a factory method when creates an instance of another class is often declared static as this means that a particular instance of the class containing the factor method is not required.
For a good explanation of how, when and where see MSDN
Recently i had the same problem (Compiling OpenCV with CMake and Qt/MinGW on WIN764)
And I think I solve this including on my environment variable PATH (through Control Panel\All Control Panel Items\System\Advanced Sytem Settings
) with the %MINGW_DIR%\bin and %CMAKE_DIR%/bin
Furthermore, I installed cmake2.8 on an easy directory (without blanks on it)
" In computer networking, a network host, Internet host, host, or Internet node is a computer connected to the Internet - or more generically - to any type of data network. A network host can host information resources as well as application software for providing network services. "-Wikipedia
Local host is a special name given to the local machine or that you are working on, ussually its IP Address is 127.0.0.1. However you can define it to be anything.
There are multiple Network services running on each host for example Apache/IIS( Http Web Server),Mail Clients, FTP clients etc. Each service has a specific port associated with it. You can think of it as this.
In every home, there is one mailbox and multiple people. The mailbox is a host. Your own home mailbox is a localhost. Each person in a home has a room. All letters for that person are sent to his room, hence the room number is a port.
You have use the SqlQuery function and indicate the entity to mapping the result.
I send an example as to perform this:
var oficio= new SqlParameter
{
ParameterName = "pOficio",
Value = "0001"
};
using (var dc = new PCMContext())
{
return dc.Database
.SqlQuery<ProyectoReporte>("exec SP_GET_REPORTE @pOficio",
oficio)
.ToList();
}
We can declare static methods with same signature in subclass, but it is not considered overriding as there won’t be any run-time polymorphism.Because since all static members of a class are loaded at the time of class loading so it decide at compile time(overriding at run time) Hence the answer is ‘No’.
Just develop a normal app and then add a couple of lines to the app's manifest file.
First you need to add the following attribute to your activity:
android:launchMode="singleTask"
Then add two categories to the intent filter :
<category android:name="android.intent.category.DEFAULT" />
<category android:name="android.intent.category.HOME" />
The result could look something like this:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.dummy.app"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="11"
android:targetSdkVersion="19" />
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name="com.dummy.app.MainActivity"
android:launchMode="singleTask"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
<category android:name="android.intent.category.DEFAULT" />
<category android:name="android.intent.category.HOME" />
</intent-filter>
</activity>
</application>
</manifest>
It's that simple!
php ini
filememory_limit = -1
create a view for each subquery is the way to go. Got it working like a charm.
You need to precede the lines starting with gcc
and rm
with a hard tab. Commands in make rules are required to start with a tab (unless they follow a semicolon on the same line).
The result should look like this:
PROG = semsearch
all: $(PROG)
%: %.c
gcc -o $@ $< -lpthread
clean:
rm $(PROG)
Note that some editors may be configured to insert a sequence of spaces instead of a hard tab. If there are spaces at the start of these lines you'll also see the "missing separator" error. If you do have problems inserting hard tabs, use the semicolon way:
PROG = semsearch
all: $(PROG)
%: %.c ; gcc -o $@ $< -lpthread
clean: ; rm $(PROG)
quite possibly the simplest method ...
<?php
$change = array('key1' => $var1, 'key2' => $var2, 'key3' => $var3);
echo json_encode(change);
?>
Then the jquery script ...
<script>
$.get("location.php", function(data){
var duce = jQuery.parseJSON(data);
var art1 = duce.key1;
var art2 = duce.key2;
var art3 = duce.key3;
});
</script>
Just look at this solution, make sure you've turned access on to less secure apps on your google account :javax.mail.MessagingException: Could not connect to SMTP host: localhost, port: 25
Basic counting is done as was stated in other answers, and in the pig documentation:
logs = LOAD 'log';
all_logs_in_a_bag = GROUP logs ALL;
log_count = FOREACH all_logs_in_a_bag GENERATE COUNT(logs);
dump log_count
You are right that counting is inefficient, even when using pig's builtin COUNT because this will use one reducer. However, I had a revelation today that one of the ways to speed it up would be to reduce the RAM utilization of the relation we're counting.
In other words, when counting a relation, we don't actually care about the data itself so let's use as little RAM as possible. You were on the right track with your first iteration of the count script.
logs = LOAD 'log'
ones = FOREACH logs GENERATE 1 AS one:int;
counter_group = GROUP ones ALL;
log_count = FOREACH counter_group GENERATE COUNT(ones);
dump log_count
This will work on much larger relations than the previous script and should be much faster. The main difference between this and your original script is that we don't need to sum anything.
This also doesn't have the same problem as other solutions where null values would impact the count. This will count all the rows, regardless of if the first column is null or not.
As mentioned here, you might need to disable the loopback
Loopback check can be removed by adding a registry entry as follows:
I created a fiddle using only CSS.
.wrapper {_x000D_
width: 100px; /* Set the size of the progress bar */_x000D_
height: 100px;_x000D_
position: absolute; /* Enable clipping */_x000D_
clip: rect(0px, 100px, 100px, 50px); /* Hide half of the progress bar */_x000D_
}_x000D_
/* Set the sizes of the elements that make up the progress bar */_x000D_
.circle {_x000D_
width: 80px;_x000D_
height: 80px;_x000D_
border: 10px solid green;_x000D_
border-radius: 50px;_x000D_
position: absolute;_x000D_
clip: rect(0px, 50px, 100px, 0px);_x000D_
}_x000D_
/* Using the data attributes for the animation selectors. */_x000D_
/* Base settings for all animated elements */_x000D_
div[data-anim~=base] {_x000D_
-webkit-animation-iteration-count: 1; /* Only run once */_x000D_
-webkit-animation-fill-mode: forwards; /* Hold the last keyframe */_x000D_
-webkit-animation-timing-function:linear; /* Linear animation */_x000D_
}_x000D_
_x000D_
.wrapper[data-anim~=wrapper] {_x000D_
-webkit-animation-duration: 0.01s; /* Complete keyframes asap */_x000D_
-webkit-animation-delay: 3s; /* Wait half of the animation */_x000D_
-webkit-animation-name: close-wrapper; /* Keyframes name */_x000D_
}_x000D_
_x000D_
.circle[data-anim~=left] {_x000D_
-webkit-animation-duration: 6s; /* Full animation time */_x000D_
-webkit-animation-name: left-spin;_x000D_
}_x000D_
_x000D_
.circle[data-anim~=right] {_x000D_
-webkit-animation-duration: 3s; /* Half animation time */_x000D_
-webkit-animation-name: right-spin;_x000D_
}_x000D_
/* Rotate the right side of the progress bar from 0 to 180 degrees */_x000D_
@-webkit-keyframes right-spin {_x000D_
from {_x000D_
-webkit-transform: rotate(0deg);_x000D_
}_x000D_
to {_x000D_
-webkit-transform: rotate(180deg);_x000D_
}_x000D_
}_x000D_
/* Rotate the left side of the progress bar from 0 to 360 degrees */_x000D_
@-webkit-keyframes left-spin {_x000D_
from {_x000D_
-webkit-transform: rotate(0deg);_x000D_
}_x000D_
to {_x000D_
-webkit-transform: rotate(360deg);_x000D_
}_x000D_
}_x000D_
/* Set the wrapper clip to auto, effectively removing the clip */_x000D_
@-webkit-keyframes close-wrapper {_x000D_
to {_x000D_
clip: rect(auto, auto, auto, auto);_x000D_
}_x000D_
}
_x000D_
<div class="wrapper" data-anim="base wrapper">_x000D_
<div class="circle" data-anim="base left"></div>_x000D_
<div class="circle" data-anim="base right"></div>_x000D_
</div>
_x000D_
Also check this fiddle here (CSS only)
@import url(http://fonts.googleapis.com/css?family=Josefin+Sans:100,300,400);_x000D_
_x000D_
.arc1 {_x000D_
width: 160px;_x000D_
height: 160px;_x000D_
background: #00a0db;_x000D_
-webkit-transform-origin: -31% 61%;_x000D_
margin-left: -30px;_x000D_
margin-top: 20px;_x000D_
-webkit-transform: translate(-54px,50px);_x000D_
-moz-transform: translate(-54px,50px);_x000D_
-o-transform: translate(-54px,50px);_x000D_
}_x000D_
.arc2 {_x000D_
width: 160px;_x000D_
height: 160px;_x000D_
background: #00a0db;_x000D_
-webkit-transform: skew(45deg,0deg);_x000D_
-moz-transform: skew(45deg,0deg);_x000D_
-o-transform: skew(45deg,0deg);_x000D_
margin-left: -180px;_x000D_
margin-top: -90px;_x000D_
position: absolute;_x000D_
-webkit-transition: all .5s linear;_x000D_
-moz-transition: all .5s linear;_x000D_
-o-transition: all .5s linear;_x000D_
}_x000D_
_x000D_
.arc-container:hover .arc2 {_x000D_
margin-left: -50px;_x000D_
-webkit-transform: skew(-20deg,0deg);_x000D_
-moz-transform: skew(-20deg,0deg);_x000D_
-o-transform: skew(-20deg,0deg);_x000D_
}_x000D_
_x000D_
.arc-wrapper {_x000D_
width: 150px;_x000D_
height: 150px;_x000D_
border-radius:150px;_x000D_
background: #424242;_x000D_
overflow:hidden;_x000D_
left: 50px;_x000D_
top: 50px;_x000D_
position: absolute;_x000D_
}_x000D_
.arc-hider {_x000D_
width: 150px;_x000D_
height: 150px;_x000D_
border-radius: 150px;_x000D_
border: 50px solid #e9e9e9;_x000D_
position:absolute;_x000D_
z-index:5;_x000D_
box-shadow:inset 0px 0px 20px rgba(0,0,0,0.7);_x000D_
}_x000D_
_x000D_
.arc-inset {_x000D_
font-family: "Josefin Sans";_x000D_
font-weight: 100;_x000D_
position: absolute;_x000D_
font-size: 413px;_x000D_
margin-top: -64px;_x000D_
z-index: 5;_x000D_
left: 30px;_x000D_
line-height: 327px;_x000D_
height: 280px;_x000D_
-webkit-mask-image: -webkit-linear-gradient(top, rgba(0,0,0,1), rgba(0,0,0,0.2));_x000D_
}_x000D_
.arc-lowerInset {_x000D_
font-family: "Josefin Sans";_x000D_
font-weight: 100;_x000D_
position: absolute;_x000D_
font-size: 413px;_x000D_
margin-top: -64px;_x000D_
z-index: 5;_x000D_
left: 30px;_x000D_
line-height: 327px;_x000D_
height: 280px;_x000D_
color: white;_x000D_
-webkit-mask-image: -webkit-linear-gradient(top, rgba(0,0,0,0.2), rgba(0,0,0,1));_x000D_
}_x000D_
.arc-overlay {_x000D_
width: 100px;_x000D_
height: 100px;_x000D_
background-image: linear-gradient(bottom, rgb(217,217,217) 10%, rgb(245,245,245) 90%, rgb(253,253,253) 100%);_x000D_
background-image: -o-linear-gradient(bottom, rgb(217,217,217) 10%, rgb(245,245,245) 90%, rgb(253,253,253) 100%);_x000D_
background-image: -moz-linear-gradient(bottom, rgb(217,217,217) 10%, rgb(245,245,245) 90%, rgb(253,253,253) 100%);_x000D_
background-image: -webkit-linear-gradient(bottom, rgb(217,217,217) 10%, rgb(245,245,245) 90%, rgb(253,253,253) 100%);_x000D_
_x000D_
padding-left: 32px;_x000D_
box-sizing: border-box;_x000D_
-moz-box-sizing: border-box;_x000D_
line-height: 100px;_x000D_
font-family: sans-serif;_x000D_
font-weight: 400;_x000D_
text-shadow: 0 1px 0 #fff;_x000D_
font-size: 22px;_x000D_
border-radius: 100px;_x000D_
position: absolute;_x000D_
z-index: 5;_x000D_
top: 75px;_x000D_
left: 75px;_x000D_
box-shadow:0px 0px 20px rgba(0,0,0,0.7);_x000D_
}_x000D_
.arc-container {_x000D_
position: relative;_x000D_
background: #e9e9e9;_x000D_
height: 250px;_x000D_
width: 250px;_x000D_
}
_x000D_
<div class="arc-container">_x000D_
<div class="arc-hider"></div>_x000D_
<div class="arc-inset">_x000D_
o_x000D_
</div>_x000D_
<div class="arc-lowerInset">_x000D_
o_x000D_
</div>_x000D_
<div class="arc-overlay">_x000D_
35%_x000D_
</div>_x000D_
<div class="arc-wrapper">_x000D_
<div class="arc2"></div>_x000D_
<div class="arc1"></div>_x000D_
</div>_x000D_
</div>
_x000D_
Or this beautiful round progress bar with HTML5, CSS3 and JavaScript.
Check your real my.ini
file location and set --defaults-file="location"
with this command
mysql --defaults-file="C:\MYSQL\my.ini" -u root -p
This solution is permanently for your cmd Screen.
This should work and protect your form from being submitted if the number of files is greater then max_file_number.
$(function() {
var // Define maximum number of files.
max_file_number = 3,
// Define your form id or class or just tag.
$form = $('form'),
// Define your upload field class or id or tag.
$file_upload = $('#image_upload', $form),
// Define your submit class or id or tag.
$button = $('.submit', $form);
// Disable submit button on page ready.
$button.prop('disabled', 'disabled');
$file_upload.on('change', function () {
var number_of_images = $(this)[0].files.length;
if (number_of_images > max_file_number) {
alert(`You can upload maximum ${max_file_number} files.`);
$(this).val('');
$button.prop('disabled', 'disabled');
} else {
$button.prop('disabled', false);
}
});
});
I think you're looking for the intersect function
array array_intersect ( array $array1 , array $array2 [, array $ ... ] )
array_intersect()
returns an array containing all values of array1 that are
present in all the arguments. Note that keys are preserved.
The best source is probably Apple's official documentation. The specific variable you are looking for is CONFIGURATION.
Simple use text = text + string2
error_reporting(E_ALL ^ E_WARNING);
:)
You should change subject to "How to fix warning from date() in PHP"...
var startTime = getTime(document.getElementById('startTime').value);
var endTime = getTime(document.getElementById('endTime').value);
var sts = startTime.split(":");
var ets = endTime.split(":");
var stMin = (parseInt(sts[0]) * 60 + parseInt(sts[1]));
var etMin = (parseInt(ets[0]) * 60 + parseInt(ets[1]));
if( etMin > stMin) {
// do your stuff...
}
Use the modern version of the Fisher–Yates shuffle algorithm:
/**
* Shuffles array in place.
* @param {Array} a items An array containing the items.
*/
function shuffle(a) {
var j, x, i;
for (i = a.length - 1; i > 0; i--) {
j = Math.floor(Math.random() * (i + 1));
x = a[i];
a[i] = a[j];
a[j] = x;
}
return a;
}
/**
* Shuffles array in place. ES6 version
* @param {Array} a items An array containing the items.
*/
function shuffle(a) {
for (let i = a.length - 1; i > 0; i--) {
const j = Math.floor(Math.random() * (i + 1));
[a[i], a[j]] = [a[j], a[i]];
}
return a;
}
Note however, that swapping variables with destructuring assignment causes significant performance loss, as of October 2017.
var myArray = ['1','2','3','4','5','6','7','8','9'];
shuffle(myArray);
Using Object.defineProperty
(method taken from this SO answer) we can also implement this function as a prototype method for arrays, without having it show up in loops such as for (i in arr)
. The following will allow you to call arr.shuffle()
to shuffle the array arr
:
Object.defineProperty(Array.prototype, 'shuffle', {
value: function() {
for (let i = this.length - 1; i > 0; i--) {
const j = Math.floor(Math.random() * (i + 1));
[this[i], this[j]] = [this[j], this[i]];
}
return this;
}
});
I have added the following on my excel sheet
=VLOOKUP(B2,Res_partner!$A$2:$C$21208,1,FALSE)
Still doesn't seem to work. I get an #N/A
BUT
=VLOOKUP(B2,Res_partner!$C$2:$C$21208,1,FALSE)
Works
I got the same issue while working on a maven project, so I recreate the configuration file spring.xml
in src/main/java
and it worked for me.
In the old days, when we could assume that most computers used ASCII, we would just do
int i = c[0] - '0';
But in these days of Unicode, it's not a good idea. It was never a good idea if your code had to run on a non-ASCII computer.
Edit: Although it looks hackish, evidently it is guaranteed by the standard to work. Thanks @Earwicker.
I dont know about XamGrid
but that's what i'll do with a standard wpf DataGrid
:
<DataGrid>
<DataGrid.Columns>
<DataGridTemplateColumn>
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<TextBlock Text="{Binding DataContext.MyProperty, RelativeSource={RelativeSource AncestorType=MyUserControl}}"/>
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
<DataGridTemplateColumn.CellEditingTemplate>
<DataTemplate>
<TextBox Text="{Binding DataContext.MyProperty, RelativeSource={RelativeSource AncestorType=MyUserControl}}"/>
</DataTemplate>
</DataGridTemplateColumn.CellEditingTemplate>
</DataGridTemplateColumn>
</DataGrid.Columns>
</DataGrid>
Since the TextBlock
and the TextBox
specified in the cell templates will be part of the visual tree, you can walk up and find whatever control you need.
For straight HTML, with no JavaScript required:
<a href="#something">Add '#something' to URL</a>
Or, to take your question more literally, to just add '#' to the URL:
<a href="#">Add '#' to URL</a>
where T : struct
The type argument must be a value type. Any value type except Nullable can be specified. See Using Nullable Types (C# Programming Guide) for more information.
where T : class
The type argument must be a reference type, including any class, interface, delegate, or array type. (See note below.)
where T : new() The type argument must have a public parameterless constructor. When used in conjunction with other constraints, the new() constraint must be specified last.
where T : [base class name]
The type argument must be or derive from the specified base class.
where T : [interface name]
The type argument must be or implement the specified interface. Multiple interface constraints can be specified. The constraining interface can also be generic.
where T : U
The type argument supplied for T must be or derive from the argument supplied for U. This is called a naked type constraint.
Create your partial view something like:
@model YourModelType
<div>
<!-- HTML to render your object -->
</div>
Then in your view use:
@Html.Partial("YourPartialViewName", Model)
If you do not want a strongly typed partial view remove the @model YourModelType
from the top of the partial view and it will default to a dynamic
type.
Update
The default view engine will search for partial views in the same folder as the view calling the partial and then in the ~/Views/Shared folder. If your partial is located in a different folder then you need to use the full path. Note the use of ~/
in the path below.
@Html.Partial("~/Views/Partials/SeachResult.cshtml", Model)
the new version of ExcelPackage is here http://EPPlus.codeplex.com
I'm still fighting with the export to excel function since my application should export some data to excel-template 2007
this project seems fine to me, and the developer is very responsive to bugs and issues.
You can implement the functionality yourself:
Use a global (string)stack and at start of each function push the function name and such other values (eg parameters) onto this stack; at exit of function pop it again.
Write a function that will printout the stack content when it is called, and use this in the function where you want to see the callstack.
This may sound like a lot of work but is quite useful.
The easiest way I found is just to redirect the requests that trigger 404 to the client. This is done by adding an hashtag even when $locationProvider.html5Mode(true)
is set.
This trick works for environments with more Web Application on the same Web Site and requiring URL integrity constraints (E.G. external authentication). Here is step by step how to do
Set the <base>
element properly
<base href="@(Request.ApplicationPath + "/")">
First redirect 404 to a custom page, for example "Home/Error"
<system.web>
<customErrors mode="On">
<error statusCode="404" redirect="~/Home/Error" />
</customErrors>
</system.web>
Implement a simple ActionResult
to "translate" input in a clientside route.
public ActionResult Error(string aspxerrorpath) {
return this.Redirect("~/#/" + aspxerrorpath);
}
This is the simplest way.
It is possible (advisable?) to enhance the Error function with some improved logic to redirect 404 to client only when url is valid and let the 404 trigger normally when nothing will be found on client. Let's say you have these angular routes
.when("/", {
templateUrl: "Base/Home",
controller: "controllerHome"
})
.when("/New", {
templateUrl: "Base/New",
controller: "controllerNew"
})
.when("/Show/:title", {
templateUrl: "Base/Show",
controller: "controllerShow"
})
It makes sense to redirect URL to client only when it start with "/New" or "/Show/"
public ActionResult Error(string aspxerrorpath) {
// get clientside route path
string clientPath = aspxerrorpath.Substring(Request.ApplicationPath.Length);
// create a set of valid clientside path
string[] validPaths = { "/New", "/Show/" };
// check if clientPath is valid and redirect properly
foreach (string validPath in validPaths) {
if (clientPath.StartsWith(validPath)) {
return this.Redirect("~/#/" + clientPath);
}
}
return new HttpNotFoundResult();
}
This is just an example of improved logic, of course every web application has different needs
For a small range, the simplest thing is to have a map array, where, eg, the 80th entry would have the value 82 in it, to use your example. For a much larger, sparse range, probably the way to go is a binary search.
With a query language you could query for values some distance either side of your input number and then sort through the resulting reduced list. But SQL doesn't have a good concept of "next" or "previous", to give you a "clean" solution.
I successfully installed python3 kernel on macOS El Capitan (ipython version: 4.1.0) with following commands.
python3 -m pip install ipykernel
python3 -m ipykernel install --user
You can see all installed kernels with jupyter kernelspec list
.
More info is available here
request.getRequestURI().substring(request.getContextPath().length())
A shorter answer from here, adapted to this question:
var arr = $('.requiredText');
arr.each(function(index, item) {
var is_last_item = (index == (arr.length - 1));
});
Just for completeness.
There are two ways you can do this; with patch and with patch.object
Patch assumes that you are not directly importing the object but that it is being used by the object you are testing as in the following
#foo.py
def some_fn():
return 'some_fn'
class Foo(object):
def method_1(self):
return some_fn()
#bar.py
import foo
class Bar(object):
def method_2(self):
tmp = foo.Foo()
return tmp.method_1()
#test_case_1.py
import bar
from mock import patch
@patch('foo.some_fn')
def test_bar(mock_some_fn):
mock_some_fn.return_value = 'test-val-1'
tmp = bar.Bar()
assert tmp.method_2() == 'test-val-1'
mock_some_fn.return_value = 'test-val-2'
assert tmp.method_2() == 'test-val-2'
If you are directly importing the module to be tested, you can use patch.object as follows:
#test_case_2.py
import foo
from mock import patch
@patch.object(foo, 'some_fn')
def test_foo(test_some_fn):
test_some_fn.return_value = 'test-val-1'
tmp = foo.Foo()
assert tmp.method_1() == 'test-val-1'
test_some_fn.return_value = 'test-val-2'
assert tmp.method_1() == 'test-val-2'
In both cases some_fn will be 'un-mocked' after the test function is complete.
Edit: In order to mock multiple functions, just add more decorators to the function and add arguments to take in the extra parameters
@patch.object(foo, 'some_fn')
@patch.object(foo, 'other_fn')
def test_foo(test_other_fn, test_some_fn):
...
Note that the closer the decorator is to the function definition, the earlier it is in the parameter list.
DOUBLE columns are not the same as DECIMAL columns, and you will get in trouble if you use DOUBLE columns for financial data.
DOUBLE is actually just a double precision (64 bit instead of 32 bit) version of FLOAT. Floating point numbers are approximate representations of real numbers and they are not exact. In fact, simple numbers like 0.01 do not have an exact representation in FLOAT or DOUBLE types.
DECIMAL columns are exact representations, but they take up a lot more space for a much smaller range of possible numbers. To create a column capable of holding values from 0.0001 to 99.9999 like you asked you would need the following statement
CREATE TABLE your_table
(
your_column DECIMAL(6,4) NOT NULL
);
The column definition follows the format DECIMAL(M, D) where M is the maximum number of digits (the precision) and D is the number of digits to the right of the decimal point (the scale).
This means that the previous command creates a column that accepts values from -99.9999 to 99.9999. You may also create an UNSIGNED DECIMAL column, ranging from 0.0000 to 99.9999.
For more information on MySQL DECIMAL the official docs are always a great resource.
Bear in mind that all of this information is true for versions of MySQL 5.0.3 and greater. If you are using previous versions, you really should upgrade.
console.log( $('#'+d) ); // single quotes only
console.log( $("#"+d) ); // double quotes only
Your selector results like this, which is overkill with the quotes:
$('"#abc"') // -> it'll try to find <div id='"#abc"'>
// In css, this would be the equivalent:
"#abc"{ /* Wrong */ } // instead of:
#abc{ /* Right */ }
I think it's worth putting a few timings up here for some perspective.
All timings done on OS-X 10.5.8 with python2.7
John Clement's answer:
python -m timeit -s 'my_list = range(1000)[::-1]; from operator import itemgetter' 'min(enumerate(my_list),key=itemgetter(1))'
1000 loops, best of 3: 239 usec per loop
David Wolever's answer:
python -m timeit -s 'my_list = range(1000)[::-1]' 'min((val, idx) for (idx, val) in enumerate(my_list))
1000 loops, best of 3: 345 usec per loop
OP's answer:
python -m timeit -s 'my_list = range(1000)[::-1]' 'my_list.index(min(my_list))'
10000 loops, best of 3: 96.8 usec per loop
Note that I'm purposefully putting the smallest item last in the list to make .index
as slow as it could possibly be. It would be interesting to see at what N the iterate once answers would become competitive with the iterate twice answer we have here.
Of course, speed isn't everything and most of the time, it's not even worth worrying about ... choose the one that is easiest to read unless this is a performance bottleneck in your code (and then profile on your typical real-world data -- preferably on your target machines).
Below code gives a basic idea. This is not best solution though.
public static String splitJoin(String sourceStr, String delim,boolean trim,boolean ignoreEmpty){
return join(Arrays.asList(sourceStr.split(delim)), delim, ignoreEmpty);
}
public static String join(List<?> list, String delim, boolean ignoreEmpty) {
int len = list.size();
if (len == 0)
return "";
StringBuilder sb = new StringBuilder(list.get(0).toString());
for (int i = 1; i < len; i++) {
if (ignoreEmpty && !StringUtils.isBlank(list.get(i).toString())) {
sb.append(delim);
sb.append(list.get(i).toString().trim());
}
}
return sb.toString();
}
You need to loop over loadDT.Columns
, like this:
foreach (DataColumn column in loadDT.Columns)
{
Console.Write("Item: ");
Console.Write(column.ColumnName);
Console.Write(" ");
Console.WriteLine(row[column]);
}
For Saturday and Sunday You can do something like this
$('#orderdate').datepicker({
daysOfWeekDisabled: [0,6]
});
perhaps, you can first determine if the DOM does really exists,
function walkmydog() {
//when the user starts entering
var dom = document.getElementById('WallSearch');
if(dom == null){
alert('sorry, WallSearch DOM cannot be found');
return false;
}
if(dom.value.length == 0){
alert("nothing");
}
}
if (document.addEventListener){
document.addEventListener("DOMContentLoaded", walkmydog, false);
}
git branch --sort=-committerdate | head -5
For any one interested in getting just the top 5 branch names sorted based on committer date.
Adding only android-support-v7-appcompat.jar
to library dependencies is not enough, you have also to import in your project the module that you can find in your SDK at the path \android-sdk\extras\android\support\v7\appcompat
and after that add module dependencies configuring the project structure in this way
otherwise are included only the class files of support library and the app is not able to load the other resources causing the error.
In addition as reVerse suggested replace this
public CustomActionBarDrawerToggle(Activity mActivity,
DrawerLayout mDrawerLayout) {
super(mActivity, mDrawerLayout,new Toolbar(MyActivity.this) ,
R.string.ns_menu_open, R.string.ns_menu_close);
}
with
public CustomActionBarDrawerToggle(Activity mActivity,
DrawerLayout mDrawerLayout) {
super(mActivity, mDrawerLayout, R.string.ns_menu_open, R.string.ns_menu_close);
}
Two ways to do that..
Option 1:
1. Go to "Start" -> "Run".
2. Write "CMD" and press on "Enter" key.
3. Write the command "net statistics server" and press on "Enter" key.
4. The line that start with "Statistics since …" provides the time that the server was up from.
The command "net stats srv" can be use instead.
Option 2:
Uptime.exe Tool Allows You to Estimate Server Availability with Windows NT 4.0 SP4 or Higher
http://support.microsoft.com/kb/232243
Hope it helped you!!
There is only so much you can do with rm() and gc(). As suggested by Gavin Simpson, even if you free the actual memory in R, Windows often won't reclaim it until you close R or it is needed because all the apparent Windows memory fills up.
This usually isn't a problem. However, if you are running large loops this can sometimes lead to fragmented memory in the long term, such that even if you free the memory and restart R - the fragmented memory may prevent you allocating large chunks of memory. Especially if other applications were allocated fragmented memory while you were running R. rm() and gc() may delay the inevitable, but more RAM is better.
Here is the script in Python.
You cannot click on elements in selenium that are hidden. However, you can execute JavaScript to click on the hidden element for you.
element = driver.find_element_by_id(buttonID)
driver.execute_script("$(arguments[0]).click();", element)
bundle exec rake db:rollback
rails destroy model <model_name>
When you generate a model, it creates a database migration. If you run 'destroy' on that model, it will delete the migration file, but not the database table. So before run
bundle exec rake db:rollback
If you can support it CSS Grid is probably the cleanest way for making a one-dimensional list into a two column layout with responsive interiors.
ul {_x000D_
max-width: 400px;_x000D_
display: grid;_x000D_
grid-template-columns: 50% 50%;_x000D_
padding-left: 0;_x000D_
border: 1px solid blue;_x000D_
}_x000D_
_x000D_
li {_x000D_
list-style: inside;_x000D_
border: 1px dashed red;_x000D_
padding: 10px;_x000D_
}
_x000D_
<ul>_x000D_
<li>1</li>_x000D_
<li>2</li>_x000D_
<li>3</li>_x000D_
<li>4</li>_x000D_
<li>5</li>_x000D_
<li>6</li>_x000D_
<li>7</li>_x000D_
<li>8</li>_x000D_
<li>9</li>_x000D_
<ul>
_x000D_
These are the two key lines which will give you your 2 column layout
display: grid;
grid-template-columns: 50% 50%;
You need to get a list of all the keys, loop over them and add them to your map as shown in the example below:
String s = "{menu:{\"1\":\"sql\", \"2\":\"android\", \"3\":\"mvc\"}}";
JSONObject jObject = new JSONObject(s);
JSONObject menu = jObject.getJSONObject("menu");
Map<String,String> map = new HashMap<String,String>();
Iterator iter = menu.keys();
while(iter.hasNext()){
String key = (String)iter.next();
String value = menu.getString(key);
map.put(key,value);
}
for linux (bash) following code works for me:
System.out.print("\033[31mERROR \033[0m");
the \033[31m will switch the color to red and \033[0m will switch it back to normal.
Better option is use SQLQuery#addScalar than casting to Long
or BigDecimal
.
Here is modified query that returns count
column as Long
Query query = session
.createSQLQuery("SELECT COUNT(*) as count
FROM SpyPath
WHERE DATE(time)>=DATE_SUB(CURDATE(),INTERVAL 6 DAY)
GROUP BY DATE(time)
ORDER BY time;")
.addScalar("count", LongType.INSTANCE);
Then
List<Long> result = query.list(); //No ClassCastException here
Related link
Hibernate.LONG
, remember it has been deprecated since Hibernate version 3.6.XLongType.INSTANCE
just two commands save my life
1. This will list down all previous HEADs
git reflog
2. This will revert the HEAD to commit that you deleted.
git reset --hard <your deleted commit>
ex. git reset --hard b4b2c02
NULL
is not a keyword. It's an identifier defined in some standard headers. You can include
#include <cstddef>
To have it in scope, including some other basics, like std::size_t
.
MSTest (v2) now has an Assert.ThrowsException function which can be used like this:
Assert.ThrowsException<System.FormatException>(() =>
{
Story actual = PersonalSite.Services.Content.ExtractHeader(String.Empty);
});
You can install it with nuget: Install-Package MSTest.TestFramework
As mentioned in comments above, the general case is a pain. It is fairly easy if all items are hashable or all items are sortable. However I have recently had to try solve the general case. Here is my solution. I realised after posting that this is a duplicate to a solution above that I missed on the first pass. Anyway, if you use slices rather than list.remove() you can compare immutable sequences.
def sequences_contain_same_items(a, b):
for item in a:
try:
i = b.index(item)
except ValueError:
return False
b = b[:i] + b[i+1:]
return not b
This header is getting somehow deprecated. You can read more about it here - X-XSS-Protection
- Chrome has removed their XSS Auditor
- Firefox has not, and will not implement X-XSS-Protection
- Edge has retired their XSS filter
This means that if you do not need to support legacy browsers, it is recommended that you use Content-Security-Policy without allowing unsafe-inline scripts instead.
I've just come across this, and thought I'd add my thoughts. As others have suggested, I'd recommend manually adding IDs, but if you really want something close to what you've described, you could use this:
var objectId = (function () {
var allObjects = [];
var f = function(obj) {
if (allObjects.indexOf(obj) === -1) {
allObjects.push(obj);
}
return allObjects.indexOf(obj);
}
f.clear = function() {
allObjects = [];
};
return f;
})();
You can get any object's ID by calling objectId(obj)
. Then if you want the id to be a property of the object, you can either extend the prototype:
Object.prototype.id = function () {
return objectId(this);
}
or you can manually add an ID to each object by adding a similar function as a method.
The major caveat is that this will prevent the garbage collector from destroying objects when they drop out of scope... they will never drop out of the scope of the allObjects
array, so you might find memory leaks are an issue. If your set on using this method, you should do so for debugging purpose only. When needed, you can do objectId.clear()
to clear the allObjects
and let the GC do its job (but from that point the object ids will all be reset).
There is no straight forward way of doing this.
What you can do is load the script on demand. (again uses something similar to what Ignacio mentioned,but much cleaner).
Check this link out for multiple ways of doing this: http://ajaxpatterns.org/On-Demand_Javascript
My favorite is(not applicable always):
<script src="dojo.js" type="text/javascript">
dojo.require("dojo.aDojoPackage");
Google's closure also provides similar functionality.
From Google documentation:
You can hide the navigation bar on Android 4.0 and higher using the SYSTEM_UI_FLAG_HIDE_NAVIGATION flag. This snippet hides both the navigation bar and the status bar:
View decorView = getWindow().getDecorView();
// Hide both the navigation bar and the status bar.
// SYSTEM_UI_FLAG_FULLSCREEN is only available on Android 4.1 and higher, but as
// a general rule, you should design your app to hide the status bar whenever you
// hide the navigation bar.
int uiOptions = View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
| View.SYSTEM_UI_FLAG_FULLSCREEN;
decorView.setSystemUiVisibility(uiOptions);
http://developer.android.com/training/system-ui/navigation.html
You should include a path to your command, since cron runs with an extensively cut-down environment. You won't have all the environment variables you have in your interactive shell session.
It's a good idea to specify an absolute path to your script/binary, or define PATH in the crontab itself. To help debug any issues I would also redirect stdout/err to a log file.
I stumbled upon this question via a Google search for a very similar one (using the serial port on a server from a Linux client over TCP/IP), so, even though this is not an answer to exact original question, some of the code might be useful to the original poster, I think:
From the Twitter FAQ:
Most integrations with the API will require you to identify your application to Twitter by way of an API key. On the Twitter platform, the term "API key" usually refers to what's called an OAuth consumer key. This string identifies your application when making requests to the API. In OAuth 1.0a, your "API keys" probably refer to the combination of this consumer key and the "consumer secret," a string that is used to securely "sign" your requests to Twitter.
If eclipse Java build path is mapped to 7, 8 and in Project pom.xml Maven properties java.version is mentioned higher Java version(9,10,11, etc..,) than 7,8 you need to update in pom.xml file.
In Eclipse if Java is mapped to Java version 11 and in pom.xml it is mapped to Java version 8. Update Eclipse support to Java 11 by go through below steps in eclipse IDE Help -> Install New Software ->
Paste following link http://download.eclipse.org/eclipse/updates/4.9-P-builds at Work With
or
Add (Popup window will open) ->
Name:
Java 11 support
Location:
http://download.eclipse.org/eclipse/updates/4.9-P-builds
then update Java version in Maven properties of pom.xml file as below
<java.version>11</java.version>
<maven.compiler.source>${java.version}</maven.compiler.source>
<maven.compiler.target>${java.version}</maven.compiler.target>
Finally do right click on project Debug as -> Maven clean, Maven build steps
If you are using a DbContext, use the following constructor to set the command timeout:
public class MyContext : DbContext
{
public MyContext ()
{
var adapter = (IObjectContextAdapter)this;
var objectContext = adapter.ObjectContext;
objectContext.CommandTimeout = 1 * 60; // value in seconds
}
}
word.matches("^[0-9,;]+$");
you were almost there
You should be able to "MINUS" or "EXCEPT" depending on the flavor of SQL used by your DBMS.
select * from tableA
minus
select * from tableB
If the query returns no rows then the data is exactly the same.
//best way to deal with this is sqlbulkcopy
//but if you dont like it you can do it like this
//read current sql table in an adapter
//add rows of datatable , I have mentioned a simple way of it
//and finally updating changes
Dim cnn As New SqlConnection("connection string")
cnn.Open()
Dim cmd As New SqlCommand("select * from sql_server_table", cnn)
Dim da As New SqlDataAdapter(cmd)
Dim ds As New DataSet()
da.Fill(ds, "sql_server_table")
Dim cb As New SqlCommandBuilder(da)
//for each datatable row
ds.Tables("sql_server_table").Rows.Add(COl1, COl2)
da.Update(ds, "sql_server_table")
Since Python is open source you can read the source code.
To find out what file a particular module or function is implemented in you can usually print the __file__
attribute. Alternatively, you may use the inspect
module, see the section Retrieving Source Code in the documentation of inspect
.
For built-in classes and methods this is not so straightforward since inspect.getfile
and inspect.getsource
will return a type error stating that the object is built-in. However, many of the built-in types can be found in the Objects
sub-directory of the Python source trunk. For example, see here for the implementation of the enumerate class or here for the implementation of the list
type.
I would recommend to use this since I have the same issue which got fixed.
$('input:text').focus(
function(){
$(this).val('');
});
Because you tried to access an element in a collection, using a numeric index that exceeds the collection's boundaries.
The first element in a collection is generally located at index 0
. The last element is at index n-1
, where n
is the Size
of the collection (the number of elements it contains). If you attempt to use a negative number as an index, or a number that is larger than Size-1
, you're going to get an error.
When you declare an array like this:
var array = new int[6]
The first and last elements in the array are
var firstElement = array[0];
var lastElement = array[5];
So when you write:
var element = array[5];
you are retrieving the sixth element in the array, not the fifth one.
Typically, you would loop over an array like this:
for (int index = 0; index < array.Length; index++)
{
Console.WriteLine(array[index]);
}
This works, because the loop starts at zero, and ends at Length-1
because index
is no longer less than Length
.
This, however, will throw an exception:
for (int index = 0; index <= array.Length; index++)
{
Console.WriteLine(array[index]);
}
Notice the <=
there? index
will now be out of range in the last loop iteration, because the loop thinks that Length
is a valid index, but it is not.
Lists work the same way, except that you generally use Count
instead of Length
. They still start at zero, and end at Count - 1
.
for (int index = 0; i < list.Count; index++)
{
Console.WriteLine(list[index]);
}
However, you can also iterate through a list using foreach
, avoiding the whole problem of indexing entirely:
foreach (var element in list)
{
Console.WriteLine(element.ToString());
}
You cannot index an element that hasn't been added to a collection yet.
var list = new List<string>();
list.Add("Zero");
list.Add("One");
list.Add("Two");
Console.WriteLine(list[3]); // Throws exception.
You can use indexOf
But not working well in the last version of internet explorer.
Code:
function isInArray(value, array) {
return array.indexOf(value) > -1;
}
Execution:
isInArray(1, [1,2,3]); // true
I suggest you use the following code:
function inArray(needle, haystack) {
var length = haystack.length;
for (var i = 0; i < length; i++) {
if (haystack[i] == needle)
return true;
}
return false;
}
With EF Core in .NET Core you can use the keyword ThenInclude
:
return DatabaseContext.Applications
.Include(a => a.Children).ThenInclude(c => c.ChildRelationshipType);
Include childs from childrens collection :
return DatabaseContext.Applications
.Include(a => a.Childrens).ThenInclude(cs => cs.ChildRelationshipType1)
.Include(a => a.Childrens).ThenInclude(cs => cs.ChildRelationshipType2);
If number
could be None
or a number, and you wanted to include 0
, filter on None
instead:
if number is not None:
If number
can be any number of types, test for the type; you can test for just int
or a combination of types with a tuple:
if isinstance(number, int): # it is an integer
if isinstance(number, (int, float)): # it is an integer or a float
or perhaps:
from numbers import Number
if isinstance(number, Number):
to allow for integers, floats, complex numbers, Decimal
and Fraction
objects.
If you do not use any placeholders (as the "exactly" seems to imply), how about string comparison instead?
If you do use placeholders, ^
and $
match the beginning and the end of a string, respectively.
Official WhatsApp doc Says-:
https://api.whatsapp.com/send?phone=countrycode+phonenumber&text=urlencodedtext
Use: https://api.whatsapp.com/send?phone=15551234567&text=urlencodedtext
Don't use: https://api.whatsapp.com/send?phone=+001-(555)1234567
Add "new":
var movies = _db.Movies.OrderBy( m => new { m.CategoryID, m.Name })
That works on my box. It does return something that can be used to sort. It returns an object with two values.
Similar, but different to sorting by a combined column, as follows.
var movies = _db.Movies.OrderBy( m => (m.CategoryID.ToString() + m.Name))
Clean way with ExecutorService
List<Future<Void>> results = null;
try {
List<Callable<Void>> tasks = new ArrayList<>();
ExecutorService executorService = Executors.newFixedThreadPool(4);
results = executorService.invokeAll(tasks);
} catch (InterruptedException ex) {
...
} catch (Exception ex) {
...
}
if you don't want to use a link, use button. you can add image to button as well:
<button type="button" onclick="location.href='@Url.Action("Create", "Company")'" >
Create New
<img alt="New" title="New" src="~/Images/Button/plus.png">
</button>
type="button" performs your action instead of submitting form.
Having struggled with ImageIO
a lot in the past years, I think Andrew Taylor's solution is by far the best compromise (fast: not using ImageIO#read
, and versatile). Thanks man!!
But I was a little frustrated to be compelled to use a local file (File/String), especially in cases where you want to check image sizes coming from, say, a multipart/form-data request where you usually retrieve InputPart
/InputStream
's. So I quickly made a variant that accepts File
, InputStream
and RandomAccessFile
, based on the ability of ImageIO#createImageInputStream
to do so.
Of course, such a method with Object input
, may only remain private and you shall create as many polymorphic methods as needed, calling this one. You can also accept Path
with Path#toFile()
and URL
with URL#openStream()
prior to passing to this method:
private static Dimension getImageDimensions(Object input) throws IOException {
try (ImageInputStream stream = ImageIO.createImageInputStream(input)) { // accepts File, InputStream, RandomAccessFile
if(stream != null) {
IIORegistry iioRegistry = IIORegistry.getDefaultInstance();
Iterator<ImageReaderSpi> iter = iioRegistry.getServiceProviders(ImageReaderSpi.class, true);
while (iter.hasNext()) {
ImageReaderSpi readerSpi = iter.next();
if (readerSpi.canDecodeInput(stream)) {
ImageReader reader = readerSpi.createReaderInstance();
try {
reader.setInput(stream);
int width = reader.getWidth(reader.getMinIndex());
int height = reader.getHeight(reader.getMinIndex());
return new Dimension(width, height);
} finally {
reader.dispose();
}
}
}
throw new IllegalArgumentException("Can't find decoder for this image");
} else {
throw new IllegalArgumentException("Can't open stream for this image");
}
}
}
Iterators are objects that implement the iter and next methods. If those methods are defined, we can use for loop or comprehensions.
class Squares:
def __init__(self, length):
self.length = length
self.i = 0
def __iter__(self):
print('calling __iter__') # this will be called first and only once
return self
def __next__(self):
print('calling __next__') # this will be called for each iteration
if self.i >= self.length:
raise StopIteration
else:
result = self.i ** 2
self.i += 1
return result
Iterators get exhausted. It means after you iterate over items, you cannot reiterate, you have to create a new object. Let's say you have a class, which holds the cities properties and you want to iterate over.
class Cities:
def __init__(self):
self._cities = ['Brooklyn', 'Manhattan', 'Prag', 'Madrid', 'London']
self._index = 0
def __iter__(self):
return self
def __next__(self):
if self._index >= len(self._cities):
raise StopIteration
else:
item = self._cities[self._index]
self._index += 1
return item
Instance of class Cities is an iterator. However if you want to reiterate over cities, you have to create a new object which is an expensive operation. You can separate the class into 2 classes: one returns cities and second returns an iterator which gets the cities as init param.
class Cities:
def __init__(self):
self._cities = ['New York', 'Newark', 'Istanbul', 'London']
def __len__(self):
return len(self._cities)
class CityIterator:
def __init__(self, city_obj):
# cities is an instance of Cities
self._city_obj = city_obj
self._index = 0
def __iter__(self):
return self
def __next__(self):
if self._index >= len(self._city_obj):
raise StopIteration
else:
item = self._city_obj._cities[self._index]
self._index += 1
return item
Now if we need to create a new iterator, we do not have to create the data again, which is cities. We creates cities object and pass it to the iterator. But we are still doing extra work. We could implement this by creating only one class.
Iterable is a Python object that implements the iterable protocol. It requires only __iter__()
that returns a new instance of iterator object.
class Cities:
def __init__(self):
self._cities = ['New York', 'Newark', 'Istanbul', 'Paris']
def __len__(self):
return len(self._cities)
def __iter__(self):
return self.CityIterator(self)
class CityIterator:
def __init__(self, city_obj):
self._city_obj = city_obj
self._index = 0
def __iter__(self):
return self
def __next__(self):
if self._index >= len(self._city_obj):
raise StopIteration
else:
item = self._city_obj._cities[self._index]
self._index += 1
return item
Iterators has __iter__
and __next__
, iterables have __iter__
, so we can say Iterators are also iterables but they are iterables that get exhausted. Iterables on the other hand never become exhausted
because they always return a new iterator that is then used to iterate
You notice that the main part of the iterable code is in the iterator, and the iterable itself is nothing more than an extra layer that allows us to create and access the iterator.
Python has a built function iter() which calls the __iter__()
. When we iterate over an iterable, Python calls the iter() which returns an iterator, then it starts using __next__()
of iterator to iterate over the data.
NOte that in the above example, Cities creates an iterable but it is not a sequence type, it means we cannot get a city by an index. To fix this we should just add __get_item__
to the Cities class.
class Cities:
def __init__(self):
self._cities = ['New York', 'Newark', 'Budapest', 'Newcastle']
def __len__(self):
return len(self._cities)
def __getitem__(self, s): # now a sequence type
return self._cities[s]
def __iter__(self):
return self.CityIterator(self)
class CityIterator:
def __init__(self, city_obj):
self._city_obj = city_obj
self._index = 0
def __iter__(self):
return self
def __next__(self):
if self._index >= len(self._city_obj):
raise StopIteration
else:
item = self._city_obj._cities[self._index]
self._index += 1
return item
Also look at log4net, which makes logging to 1 or more event stores — whether it's the console, the Windows event log, a text file, a network pipe, a SQL database, etc. — pretty trivial. You can even filter stuff in its configuration, for instance, so that only log records of a particular severity (say ERROR or FATAL) from a single component or assembly are directed to a particular event store.
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>_x000D_
<script>_x000D_
$(document).ready(function(){_x000D_
var form=$("#myForm");_x000D_
$("#smt").click(function(){_x000D_
$.ajax({_x000D_
type:"POST",_x000D_
url:form.attr("action"),_x000D_
data:form.serialize(),_x000D_
success: function(response){_x000D_
console.log(response); _x000D_
}_x000D_
});_x000D_
});_x000D_
});_x000D_
</script>
_x000D_
This is perfect code , there is no problem.. You have to check that in php script.
this fails:
DECLARE @vPortalUID NVARCHAR(32)
SET @vPortalUID='2A66057D-F4E5-4E2B-B2F1-38C51A96D385'
DECLARE @nPortalUID AS UNIQUEIDENTIFIER
SET @nPortalUID = CAST(@vPortalUID AS uniqueidentifier)
PRINT @nPortalUID
this works
DECLARE @vPortalUID NVARCHAR(36)
SET @vPortalUID='2A66057D-F4E5-4E2B-B2F1-38C51A96D385'
DECLARE @nPortalUID AS UNIQUEIDENTIFIER
SET @nPortalUID = CAST(@vPortalUID AS UNIQUEIDENTIFIER)
PRINT @nPortalUID
the difference is NVARCHAR(36)
, your input parameter is too small!
Quote:
The "-a" operator also doesn't work:
if [ $STATUS -ne 200 ] -a [[ "$STRING" != "$VALUE" ]]
For a more elaborate explanation: [
and ]
are not Bash reserved words. The if
keyword introduces a conditional to be evaluated by a job (the conditional is true if the job's return value is 0
or false otherwise).
For trivial tests, there is the test
program (man test
).
As some find lines like if test -f filename; then foo bar; fi
, etc. annoying, on most systems you find a program called [
which is in fact only a symlink to the test
program. When test
is called as [
, you have to add ]
as the last positional argument.
So if test -f filename
is basically the same (in terms of processes spawned) as if [ -f filename ]
. In both cases the test
program will be started, and both processes should behave identically.
Here's your mistake: if [ $STATUS -ne 200 ] -a [[ "$STRING" != "$VALUE" ]]
will parse to if
+ some job, the job being everything except the if
itself. The job is only a simple command (Bash speak for something which results in a single process), which means the first word ([
) is the command and the rest its positional arguments. There are remaining arguments after the first ]
.
Also not, [[
is indeed a Bash keyword, but in this case it's only parsed as a normal command argument, because it's not at the front of the command.
final Pattern pattern = Pattern.compile("tag\\](.+?)\\[/tag");
final Matcher matcher = pattern.matcher("[tag]String I want to extract[/tag]");
matcher.find();
System.out.println(matcher.group(1));
I'd use datediff
, and not care about format conversions:
SELECT *
FROM mytable
WHERE DATEDIFF(MONTH, my_date_column, GETDATE()) <= 3
The three constants have similar functions nowadays, but different historical origins, and very occasionally you may be required to use one or the other.
You need to think back to the days of old manual typewriters to get the origins of this. There are two distinct actions needed to start a new line of text:
In computers, these two actions are represented by two different characters - carriage return is CR
, ASCII character 13, vbCr
; line feed is LF
, ASCII character 10, vbLf
. In the old days of teletypes and line printers, the printer needed to be sent these two characters -- traditionally in the sequence CRLF
-- to start a new line, and so the CRLF
combination -- vbCrLf
-- became a traditional line ending sequence, in some computing environments.
The problem was, of course, that it made just as much sense to only use one character to mark the line ending, and have the terminal or printer perform both the carriage return and line feed actions automatically. And so before you knew it, we had 3 different valid line endings: LF
alone (used in Unix and Macintoshes), CR
alone (apparently used in older Mac OSes) and the CRLF
combination (used in DOS, and hence in Windows). This in turn led to the complications of DOS / Windows programs having the option of opening files in text mode
, where any CRLF
pair read from the file was converted to a single CR
(and vice versa when writing).
So - to cut a (much too) long story short - there are historical reasons for the existence of the three separate line separators, which are now often irrelevant: and perhaps the best course of action in .NET is to use Environment.NewLine
which means someone else has decided for you which to use, and future portability issues should be reduced.
In order to avoid the modulo bias (suggested in other answers) you can always use:
arc4random_uniform(MAX-MIN)+MIN
Where "MAX" is the upper bound and "MIN" is lower bound. For example, for numbers between 10 and 20:
arc4random_uniform(20-10)+10
arc4random_uniform(10)+10
Simple solution and better than using "rand() % N".
I usually use typedef to do it, but it may be overkill, if you do not have to use the function pointer too often..
//assuming bool is available (where I come from it is an enum)
typedef bool (*pmyfun_t)();
pmyfun_t pMyFun;
pMyFun=A; //pMyFun=&A is actually same
pMyFun();
First response - wanted to finally give back to a helpful community...
Wanted to add this to the responses for people still looking for simple a solution. I'm using a free product by Foxit Software - FoxItReader.
Here is the link to the version that works with the silent print - newer versions the silent print feature is still not working.
FoxitReader623.815_Setup
FOR %%f IN (*.pdf) DO ("C:\Program Files (x86)\Foxit Software\Foxit Reader\FoxitReader.exe" /t %%f "SPST-SMPICK" %%f & del %%f)
I simply created a command to loop through the directory and for each pdf file (FOR %%f IN *.pdf) open the reader silently (/t) get the next PDF (%%f) and send it to the print queue (SPST-SMPICK), then delete each PDF after I send it to the print queue (del%%f). Shashank showed an example of moving the files to another directory if that what you need to do
FOR %%X in ("%dir1%*.pdf") DO (move "%%~dpnX.pdf" p/)
Personally, I do not accept a whitespace ($STR3) as being 'not empty'.
When a variable that only contains whitespaces is passed onto a parameter, it will often error that the parameters value may not be '$null', instead of saying it may not be a whitespace, some remove commands might remove a root folder instead of a subfolder if the subfolder name is a "white space", all the reason not to accept a string containing whitespaces in many cases.
I find this is the best way to accomplish it:
$STR1 = $null
IF ([string]::IsNullOrWhitespace($STR1)){'empty'} else {'not empty'}
Empty
$STR2 = ""
IF ([string]::IsNullOrWhitespace($STR2)){'empty'} else {'not empty'}
Empty
$STR3 = " "
IF ([string]::IsNullOrWhitespace($STR3)){'empty !! :-)'} else {'not Empty :-('}
Empty!! :-)
$STR4 = "Nico"
IF ([string]::IsNullOrWhitespace($STR4)){'empty'} else {'not empty'}
Not empty
As you have already stated in your question you have more than one option. A very basic approach would be using the tag referencing your PHP file in the method attribute. However as esoteric as it may sound AJAX is a more complete approach. Considering that an AJAX call (in combination with jQuery) can be as simple as:
$.post("yourfile.php", {data : "This can be as long as you want"});
And you get a more flexible solution, for example triggering a function after the server request is completed. Hope this helps.
you can also use VSCommands 2010 to run as different user:
None of these answers were correct in my case.. the order seems dependent on the alphabetical ordering of the <id> tag, which is an arbitrary string. Hence this forced repo search order:
<repository>
<id>1_maven.apache.org</id>
<releases> <enabled>true</enabled> </releases>
<snapshots> <enabled>true</enabled> </snapshots>
<url>https://repo.maven.apache.org/maven2</url>
<layout>default</layout>
</repository>
<repository>
<id>2_maven.oracle.com</id>
<releases> <enabled>true</enabled> </releases>
<snapshots> <enabled>false</enabled> </snapshots>
<url>https://maven.oracle.com</url>
<layout>default</layout>
</repository>
for multiple databases:
mysqldump -u user -p --ignore-table=db1.tbl1 --ignore-table=db2.tbl1 --databases db1 db2 ..
In IDP Init SSO (Unsolicited Web SSO) the Federation process is initiated by the IDP sending an unsolicited SAML Response to the SP. In SP-Init, the SP generates an AuthnRequest that is sent to the IDP as the first step in the Federation process and the IDP then responds with a SAML Response. IMHO ADFSv2 support for SAML2.0 Web SSO SP-Init is stronger than its IDP-Init support re: integration with 3rd Party Fed products (mostly revolving around support for RelayState) so if you have a choice you'll want to use SP-Init as it'll probably make life easier with ADFSv2.
Here are some simple SSO descriptions from the PingFederate 8.0 Getting Started Guide that you can poke through that may help as well -- https://documentation.pingidentity.com/pingfederate/pf80/index.shtml#gettingStartedGuide/task/idpInitiatedSsoPOST.html
For methods which may fail, that is you specify boolean as return type, I would use the prefix try
:
if (tryCreateFreshSnapshot())
{
// ...
}
For all other cases use prefixes like is..
has..
was..
can..
allows..
..
I have found these solutions that at least work for properly configured Terminus FE 1.1 USB hub chip:
1.To turn off power on all USB ports of a hub, you may unbind the hub from kernel using:
echo "1-4.4.4" > /sys/bus/usb/drivers/usb/unbind
to turn power back on - you may bind it back using
echo "1-4.4.4" > /sys/bus/usb/drivers/usb/bind
2.Switching power at each port individually is trickier: I was able to use hubpower to control each port - but it comes with a downside: hubpower first disconnects the usbdevfs wich causes all of the USB devices to disconect from system, at least on ubuntu:
usb_ioctl.ioctl_code = USBDEVFS_DISCONNECT;
rc = ioctl(fd, USBDEVFS_IOCTL, &usb_ioctl);
With this ioctl
disabled I was able to switch off individual port power without detaching all devices - but the power goes back on immediately (probably due to kernel seeing an uninitialized device) which causes USB device just to do a "cold restart" which is what I generally wanted to do. My patched hubpower is here
There is a command for this delicate task (permanently deleting untracked files)
git clean -i
Then git pull
will do.
That's not the behavior I'm seeing:
irb(main):001:0> metrics = {"sitea.com" => 745, "siteb.com" => 9, "sitec.com" =>
10 }
=> {"siteb.com"=>9, "sitec.com"=>10, "sitea.com"=>745}
irb(main):002:0> metrics.sort {|a1,a2| a2[1]<=>a1[1]}
=> [["sitea.com", 745], ["sitec.com", 10], ["siteb.com", 9]]
Is it possible that somewhere along the line your numbers are being converted to strings? Is there more code you're not posting?
You can also type "top" and look at the list of running processes.
Try it this way, I just made some light changes:
MailMessage msg = new MailMessage();
msg.From = new MailAddress("[email protected]");
msg.To.Add("[email protected]");
msg.Subject = "test";
msg.Body = "Test Content";
//msg.Priority = MailPriority.High;
using (SmtpClient client = new SmtpClient())
{
client.EnableSsl = true;
client.UseDefaultCredentials = false;
client.Credentials = new NetworkCredential("[email protected]", "mypassword");
client.Host = "smtp.gmail.com";
client.Port = 587;
client.DeliveryMethod = SmtpDeliveryMethod.Network;
client.Send(msg);
}
Also please show your app.config file, if you have mail settings there.
To embed a signature on an email, I would use the long version:
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
The reason is that not many email readers use html5, so it's always better use old html styles. Actually, it's better to use tables than divs + css as well.
But why stop with MessageBox-specific implementation? Use the class below like this:
private void OnFormClosing(object sender, FormClosingEventArgs e)
{
DialogResult dg;
using (DialogCenteringService centeringService = new DialogCenteringService(this)) // center message box
{
dg = MessageBox.Show(this, "Are you sure?", "Confirm exit", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
}
if (dg == DialogResult.No)
{
e.Cancel = true;
}
}
The code that you can use with anything that shows dialog windows, even if they're owned by another thread (our app has multiple UI threads):
(Here is the updated code which takes monitor working areas into account, so that the dialog isn't centered between two monitors or is partly off-screen. With it you'll need enum SetWindowPosFlags
, which is below)
public class DialogCenteringService : IDisposable
{
private readonly IWin32Window owner;
private readonly HookProc hookProc;
private readonly IntPtr hHook = IntPtr.Zero;
public DialogCenteringService(IWin32Window owner)
{
if (owner == null) throw new ArgumentNullException("owner");
this.owner = owner;
hookProc = DialogHookProc;
hHook = SetWindowsHookEx(WH_CALLWNDPROCRET, hookProc, IntPtr.Zero, GetCurrentThreadId());
}
private IntPtr DialogHookProc(int nCode, IntPtr wParam, IntPtr lParam)
{
if (nCode < 0)
{
return CallNextHookEx(hHook, nCode, wParam, lParam);
}
CWPRETSTRUCT msg = (CWPRETSTRUCT)Marshal.PtrToStructure(lParam, typeof(CWPRETSTRUCT));
IntPtr hook = hHook;
if (msg.message == (int)CbtHookAction.HCBT_ACTIVATE)
{
try
{
CenterWindow(msg.hwnd);
}
finally
{
UnhookWindowsHookEx(hHook);
}
}
return CallNextHookEx(hook, nCode, wParam, lParam);
}
public void Dispose()
{
UnhookWindowsHookEx(hHook);
}
private void CenterWindow(IntPtr hChildWnd)
{
Rectangle recChild = new Rectangle(0, 0, 0, 0);
bool success = GetWindowRect(hChildWnd, ref recChild);
if (!success)
{
return;
}
int width = recChild.Width - recChild.X;
int height = recChild.Height - recChild.Y;
Rectangle recParent = new Rectangle(0, 0, 0, 0);
success = GetWindowRect(owner.Handle, ref recParent);
if (!success)
{
return;
}
Point ptCenter = new Point(0, 0);
ptCenter.X = recParent.X + ((recParent.Width - recParent.X) / 2);
ptCenter.Y = recParent.Y + ((recParent.Height - recParent.Y) / 2);
Point ptStart = new Point(0, 0);
ptStart.X = (ptCenter.X - (width / 2));
ptStart.Y = (ptCenter.Y - (height / 2));
//MoveWindow(hChildWnd, ptStart.X, ptStart.Y, width, height, false);
Task.Factory.StartNew(() => SetWindowPos(hChildWnd, (IntPtr)0, ptStart.X, ptStart.Y, width, height, SetWindowPosFlags.SWP_ASYNCWINDOWPOS | SetWindowPosFlags.SWP_NOSIZE | SetWindowPosFlags.SWP_NOACTIVATE | SetWindowPosFlags.SWP_NOOWNERZORDER | SetWindowPosFlags.SWP_NOZORDER));
}
// some p/invoke
// ReSharper disable InconsistentNaming
public delegate IntPtr HookProc(int nCode, IntPtr wParam, IntPtr lParam);
public delegate void TimerProc(IntPtr hWnd, uint uMsg, UIntPtr nIDEvent, uint dwTime);
private const int WH_CALLWNDPROCRET = 12;
// ReSharper disable EnumUnderlyingTypeIsInt
private enum CbtHookAction : int
// ReSharper restore EnumUnderlyingTypeIsInt
{
// ReSharper disable UnusedMember.Local
HCBT_MOVESIZE = 0,
HCBT_MINMAX = 1,
HCBT_QS = 2,
HCBT_CREATEWND = 3,
HCBT_DESTROYWND = 4,
HCBT_ACTIVATE = 5,
HCBT_CLICKSKIPPED = 6,
HCBT_KEYSKIPPED = 7,
HCBT_SYSCOMMAND = 8,
HCBT_SETFOCUS = 9
// ReSharper restore UnusedMember.Local
}
[DllImport("kernel32.dll")]
static extern int GetCurrentThreadId();
[DllImport("user32.dll")]
private static extern bool GetWindowRect(IntPtr hWnd, ref Rectangle lpRect);
[DllImport("user32.dll")]
private static extern int MoveWindow(IntPtr hWnd, int X, int Y, int nWidth, int nHeight, bool bRepaint);
[DllImport("user32.dll")]
[return: MarshalAs(UnmanagedType.Bool)]
private static extern bool SetWindowPos(IntPtr hWnd, IntPtr hWndInsertAfter, int x, int y, int cx, int cy, SetWindowPosFlags uFlags);
[DllImport("User32.dll")]
public static extern UIntPtr SetTimer(IntPtr hWnd, UIntPtr nIDEvent, uint uElapse, TimerProc lpTimerFunc);
[DllImport("User32.dll")]
public static extern IntPtr SendMessage(IntPtr hWnd, int Msg, IntPtr wParam, IntPtr lParam);
[DllImport("user32.dll")]
public static extern IntPtr SetWindowsHookEx(int idHook, HookProc lpfn, IntPtr hInstance, int threadId);
[DllImport("user32.dll")]
public static extern int UnhookWindowsHookEx(IntPtr idHook);
[DllImport("user32.dll")]
public static extern IntPtr CallNextHookEx(IntPtr idHook, int nCode, IntPtr wParam, IntPtr lParam);
[DllImport("user32.dll")]
public static extern int GetWindowTextLength(IntPtr hWnd);
[DllImport("user32.dll")]
public static extern int GetWindowText(IntPtr hWnd, StringBuilder text, int maxLength);
[DllImport("user32.dll")]
public static extern int EndDialog(IntPtr hDlg, IntPtr nResult);
[StructLayout(LayoutKind.Sequential)]
public struct CWPRETSTRUCT
{
public IntPtr lResult;
public IntPtr lParam;
public IntPtr wParam;
public uint message;
public IntPtr hwnd;
};
// ReSharper restore InconsistentNaming
}
[Flags]
public enum SetWindowPosFlags : uint
{
// ReSharper disable InconsistentNaming
/// <summary>
/// If the calling thread and the thread that owns the window are attached to different input queues, the system posts the request to the thread that owns the window. This prevents the calling thread from blocking its execution while other threads process the request.
/// </summary>
SWP_ASYNCWINDOWPOS = 0x4000,
/// <summary>
/// Prevents generation of the WM_SYNCPAINT message.
/// </summary>
SWP_DEFERERASE = 0x2000,
/// <summary>
/// Draws a frame (defined in the window's class description) around the window.
/// </summary>
SWP_DRAWFRAME = 0x0020,
/// <summary>
/// Applies new frame styles set using the SetWindowLong function. Sends a WM_NCCALCSIZE message to the window, even if the window's size is not being changed. If this flag is not specified, WM_NCCALCSIZE is sent only when the window's size is being changed.
/// </summary>
SWP_FRAMECHANGED = 0x0020,
/// <summary>
/// Hides the window.
/// </summary>
SWP_HIDEWINDOW = 0x0080,
/// <summary>
/// Does not activate the window. If this flag is not set, the window is activated and moved to the top of either the topmost or non-topmost group (depending on the setting of the hWndInsertAfter parameter).
/// </summary>
SWP_NOACTIVATE = 0x0010,
/// <summary>
/// Discards the entire contents of the client area. If this flag is not specified, the valid contents of the client area are saved and copied back into the client area after the window is sized or repositioned.
/// </summary>
SWP_NOCOPYBITS = 0x0100,
/// <summary>
/// Retains the current position (ignores X and Y parameters).
/// </summary>
SWP_NOMOVE = 0x0002,
/// <summary>
/// Does not change the owner window's position in the Z order.
/// </summary>
SWP_NOOWNERZORDER = 0x0200,
/// <summary>
/// Does not redraw changes. If this flag is set, no repainting of any kind occurs. This applies to the client area, the nonclient area (including the title bar and scroll bars), and any part of the parent window uncovered as a result of the window being moved. When this flag is set, the application must explicitly invalidate or redraw any parts of the window and parent window that need redrawing.
/// </summary>
SWP_NOREDRAW = 0x0008,
/// <summary>
/// Same as the SWP_NOOWNERZORDER flag.
/// </summary>
SWP_NOREPOSITION = 0x0200,
/// <summary>
/// Prevents the window from receiving the WM_WINDOWPOSCHANGING message.
/// </summary>
SWP_NOSENDCHANGING = 0x0400,
/// <summary>
/// Retains the current size (ignores the cx and cy parameters).
/// </summary>
SWP_NOSIZE = 0x0001,
/// <summary>
/// Retains the current Z order (ignores the hWndInsertAfter parameter).
/// </summary>
SWP_NOZORDER = 0x0004,
/// <summary>
/// Displays the window.
/// </summary>
SWP_SHOWWINDOW = 0x0040,
// ReSharper restore InconsistentNaming
}
I use Linq to clean up filenames. You can easily extend this to check for valid paths as well.
private static string CleanFileName(string fileName)
{
return Path.GetInvalidFileNameChars().Aggregate(fileName, (current, c) => current.Replace(c.ToString(), string.Empty));
}
Some comments indicate this method is not working for them so I've included a link to a DotNetFiddle snippet so you may validate the method.
the solution is to give the Android enough time to proccess cookies. You can find more information here: http://code.walletapp.net/post/46414301269/passing-cookie-to-webview
With WinForms you can use the ErrorProvider in conjunction with the Validating
event to handle the validation of user input. The Validating
event provides the hook to perform the validation and ErrorProvider gives a nice consistent approach to providing the user with feedback on any error conditions.
http://msdn.microsoft.com/en-us/library/system.windows.forms.errorprovider.aspx
If you want to persist data on the client machine permanently -or at least until browser cache is emptied completely, use Javascript local storage:
https://developer.mozilla.org/en-US/docs/DOM/Storage#localStorage
Do not use session storage, as it will be cleared just like a cookie with a maximum age of Zero.
If all else fails (or perhaps before then) you may want to check and see if NuGet is a package source. I installed VS2017, and it was NOT there by default. I thought it was kind of odd.
$mysearch="Your Search Name";
$query = mysql_query("SELECT * FROM table");
$c=0;
// set array
$array = array();
// look through query
while($row = mysql_fetch_assoc($query)){
// add each row returned into an array
$array[] = $row;
$c++;
}
for($i=0;$i=$c;$i++)
{
if($array[i]['username']==$mysearch)
{
// name found
}
}
Actually something like
function scrollTo(prop){
$('html,body').animate({scrollTop: $("#"+prop).offset().top +
parseInt($("#"+prop).css('padding-top'),10) },'slow');
}
will work nicely and support padding. You can also support margins easily - for completion see below
function scrollTo(prop){
$('html,body').animate({scrollTop: $("#"+prop).offset().top
+ parseInt($("#"+prop).css('padding-top'),10)
+ parseInt($("#"+prop).css('margin-top'),10) +},'slow');
}
Chiming in to recommend the use of the xmltodict library. It handled your xml text pretty well and I've used it for ingesting an xml file with almost a million records.
You cannot use next() in this scenario, if you look at the documentation it says:
Next() Get the immediately following sibling of each element in the set of matched elements. If a selector is provided, it retrieves the next sibling that matches the selector.
so if the second DIV was in the same TD then you could code:
// Won't work in your case
$(obj).next().filter('.class');
$(obj).parents('table').find('.class')
Handling key events consistently is not at all easy.
Firstly, there are two different types of codes: keyboard codes (a number representing the key on the keyboard the user pressed) and character codes (a number representing a Unicode character). You can only reliably get character codes in the keypress
event. Do not try to get character codes for keyup
and keydown
events.
Secondly, you get different sets of values in a keypress
event to what you get in a keyup
or keydown
event.
I recommend this page as a useful resource. As a summary:
If you're interested in detecting a user typing a character, use the keypress
event. IE bizarrely only stores the character code in keyCode
while all other browsers store it in which
. Some (but not all) browsers also store it in charCode
and/or keyCode
. An example keypress handler:
function(evt) {
evt = evt || window.event;
var charCode = evt.which || evt.keyCode;
var charStr = String.fromCharCode(charCode);
alert(charStr);
}
If you're interested in detecting a non-printable key (such as a cursor key), use the keydown
event. Here keyCode
is always the property to use. Note that keyup
events have the same properties.
function(evt) {
evt = evt || window.event;
var keyCode = evt.keyCode;
// Check for left arrow key
if (keyCode == 37) {
alert("Left arrow");
}
}
This also works
SELECT *
FROM tableB
WHERE ID NOT IN (
SELECT ID FROM tableA
);
Using AspNetCore 2.x, you have to go a little different way:
[AttributeUsage(AttributeTargets.Method | AttributeTargets.Class, Inherited = true, AllowMultiple = true)]
public class AuthorizeRoleAttribute : AuthorizeAttribute
{
public AuthorizeRoleAttribute(params YourEnum[] roles)
{
Policy = string.Join(",", roles.Select(r => r.GetDescription()));
}
}
just use it like this:
[Authorize(YourEnum.Role1, YourEnum.Role2)]
Using functions with the ellipses is not very safe. If performance is not critical for log function consider using operator overloading as in boost::format. You could write something like this:
#include <sstream>
#include <boost/format.hpp>
#include <iostream>
using namespace std;
class formatted_log_t {
public:
formatted_log_t(const char* msg ) : fmt(msg) {}
~formatted_log_t() { cout << fmt << endl; }
template <typename T>
formatted_log_t& operator %(T value) {
fmt % value;
return *this;
}
protected:
boost::format fmt;
};
formatted_log_t log(const char* msg) { return formatted_log_t( msg ); }
// use
int main ()
{
log("hello %s in %d-th time") % "world" % 10000000;
return 0;
}
The following sample demonstrates possible errors with ellipses:
int x = SOME_VALUE;
double y = SOME_MORE_VALUE;
printf( "some var = %f, other one %f", y, x ); // no errors at compile time, but error at runtime. compiler do not know types you wanted
log( "some var = %f, other one %f" ) % y % x; // no errors. %f only for compatibility. you could write %1% instead.
On my VS install (VS 2008) #if RELEASE
does not work. However you could just use #if !DEBUG
Example:
#if !DEBUG
SendTediousEmail()
#endif
PHP uses weak typing (which it calls 'type juggling'), which is a bad idea (though that's a conversation for another time). When you try to use a variable in a context that requires a boolean, it will convert whatever your variable is into a boolean, according to some mostly arbitrary rules available here: http://www.php.net/manual/en/language.types.boolean.php#language.types.boolean.casting
Here it is a solution using map function:
>>> a = [3, 7, 19]
>>> map(lambda x: (x, a[x]), range(len(a)))
[(0, 3), (1, 7), (2, 19)]
And a solution using list comprehensions:
>>> a = [3,7,19]
>>> [(x, a[x]) for x in range(len(a))]
[(0, 3), (1, 7), (2, 19)]
Accepted answer doesn't work with "use strict" as the "with" statement throws an error. So instead:
$.post(url, function (data) {
var w = window.open('about:blank', 'windowname');
w.document.write(data);
w.document.close();
});
Also, make sure 'windowname' doesn't have any spaces in it because that will fail in IE :)
<input type="text" formControlName="gsm" (input)="formatGsm($event.target.value)">
formatGsm(inputValue: String): String {
const value = inputValue.replace(/[^0-9]/g, ''); // remove except digits
let format = '(***) *** ** **'; // You can change format
for (let i = 0; i < value.length; i++) {
format = format.replace('*', value.charAt(i));
}
if (format.indexOf('*') >= 0) {
format = format.substring(0, format.indexOf('*'));
}
return format.trim();
}
If you want to target a device then just write min-device-width
. For example:
@media only screen and (min-device-width: 480px){}
@media only screen and (min-device-width: 768px){}
Here are some good articles:
Use JSON.
In the following example $php_variable
can be any PHP variable.
<script type="text/javascript">
var obj = <?php echo json_encode($php_variable); ?>;
</script>
In your code, you could use like the following:
drawChart(600/50, <?php echo json_encode($day); ?>, ...)
In cases where you need to parse out an object from JSON-string (like in an AJAX request), the safe way is to use JSON.parse(..)
like the below:
var s = "<JSON-String>";
var obj = JSON.parse(s);
I was facing same issue and resolved using following steps
1) Go to your paython package and rename "python37._pth" to python37._pth.save
2) curl https://bootstrap.pypa.io/get-pip.py -o get-pip.py
3) then run python get-pip.py
4) pip install django
Hope this help
I would suggest Travis for Open source project. It's just simple to configure and use.
Simple steps to setup:
.travis.yml
file in root of your project. Add Travis as service in your repository settings page.Now every time you commit into your repository Travis will build your project. You can follow simple steps to get started with Travis CI.
Click in the grid so it has focus.
Ctrl+End
This will force the rest of the records back into the grid.
All credit to http://www.thatjeffsmith.com/archive/2012/03/how-to-export-sql-developer-query-results-without-re-running-the-query/
If the array is a global, static, or automatic variable (int array[10];
), then sizeof(array)/sizeof(array[0])
works.
If it is a dynamically allocated array (int* array = malloc(sizeof(int)*10);
) or passed as a function argument (void f(int array[])
), then you cannot find its size at run-time. You will have to store the size somewhere.
Note that sizeof(array)/sizeof(array[0])
compiles just fine even for the second case, but it will silently produce the wrong result.
document.location.href = newUrl;
https://developer.mozilla.org/en-US/docs/Web/API/document.location
This is the same method I have been using for a couple of years now and I haven't seen or found anything better. As people have said, PHP is single threaded, so there isn't much else you can do.
I have actually added one extra level to this and that's getting and storing the process id. This allows me to redirect to another page and have the user sit on that page, using AJAX to check if the process is complete (process id no longer exists). This is useful for cases where the length of the script would cause the browser to timeout, but the user needs to wait for that script to complete before the next step. (In my case it was processing large ZIP files with CSV like files that add up to 30 000 records to the database after which the user needs to confirm some information.)
I have also used a similar process for report generation. I'm not sure I'd use "background processing" for something such as an email, unless there is a real problem with a slow SMTP. Instead I might use a table as a queue and then have a process that runs every minute to send the emails within the queue. You would need to be warry of sending emails twice or other similar problems. I would consider a similar queueing process for other tasks as well.
You can use the .complete property of the Javascript image class.
I have an application where I store a number of Image objects in an array, that will be dynamically added to the screen, and as they're loading I write updates to another div on the page. Here's a code snippet:
var gAllImages = [];
function makeThumbDivs(thumbnailsBegin, thumbnailsEnd)
{
gAllImages = [];
for (var i = thumbnailsBegin; i < thumbnailsEnd; i++)
{
var theImage = new Image();
theImage.src = "thumbs/" + getFilename(globals.gAllPageGUIDs[i]);
gAllImages.push(theImage);
setTimeout('checkForAllImagesLoaded()', 5);
window.status="Creating thumbnail "+(i+1)+" of " + thumbnailsEnd;
// make a new div containing that image
makeASingleThumbDiv(globals.gAllPageGUIDs[i]);
}
}
function checkForAllImagesLoaded()
{
for (var i = 0; i < gAllImages.length; i++) {
if (!gAllImages[i].complete) {
var percentage = i * 100.0 / (gAllImages.length);
percentage = percentage.toFixed(0).toString() + ' %';
userMessagesController.setMessage("loading... " + percentage);
setTimeout('checkForAllImagesLoaded()', 20);
return;
}
}
userMessagesController.setMessage(globals.defaultTitle);
}
Python3 + Using boto3 API approach.
By using S3.Client.download_fileobj API and Python file-like object, S3 Object content can be retrieved to memory.
Since the retrieved content is bytes, in order to convert to str, it need to be decoded.
import io
import boto3
client = boto3.client('s3')
bytes_buffer = io.BytesIO()
client.download_fileobj(Bucket=bucket_name, Key=object_key, Fileobj=bytes_buffer)
byte_value = bytes_buffer.getvalue()
str_value = byte_value.decode() #python3, default decoding is utf-8
day1= (int)ClockInfoFromSystem.DayOfWeek;
TextView textView = (TextView) spinActSubTask.getSelectedView().findViewById(R.id.tvProduct);
String subItem = textView.getText().toString();
Yes, I read all the answers. However, if you are me and have been pulling out all of what's left of your hair, then try checking the \bin folder. Like most proj files might have several configurations grouped under the XML element PropertyGroup
, then I changed the OutputPath
value from 'bin\Debug' to remove the '\Debug' part and Rebuild. This placed the files in the \bin folder allowing the Express IIS to find and load the build. I am left wondering what is the correct way to manage these different builds so that a local debug deploy is able to find and load the target environment.
$('#id').removeAttr('required');?????
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
_x000D_
I belong to the generation who flipped switches to enter a boot program. In the early 1980s, I worked on a microcomputer called Micro-78, developed by Electronics Corporation of India Ltd (ECIL). It was a sort of clone of Altair 8800. I distinctly remember what happens when a small boot program was entered using the toggle switches and executed by pressing a button. The program reads a second boot program contained in the 1st track of the floppy disk and overwrites it on itself in such a way that the second boot program starts executing to load a disk operating system. I think the term "bootstrap" refers to this process of the first boot program reading and overwriting the second boot program on itself, in a way "pulling itself up" with the additional functionality of the second boot program. That may be the origin of the original meaning of "the bootstrap program".
A follow up to vincent's answer.
Not a direct answer to the question since the question is using a form.
For me, it wasn't the name of the input tag that was used, but the name when appending the file to the formData.
front end file
var formData = new FormData();
formData.append('<NAME>',this.new_attachments)
web service file:
app.post('/upload', upload.single('<NAME>'),...
You can conditionally redirect to some page within a php file....
if (/*Condition to redirect*/){
//You need to redirect
header("Location: http://www.yourwebsite.com/user.php"); /* Redirect browser */
exit();
}
else{
// do some
}
As you pointed out in your question it is a documented behavior. I still find it strange though. I use to repopulate the test database and even though I do not rely on the values of identity fields it was a bit of annoying to have different values when populating the database for the first time from scratch and after removing all data and populating again.
A possible solution is to use truncate to clean the table instead of delete. But then you need to drop all the constraints and recreate them afterwards
In that way it always behaves as a newly created table and there is no need to call DBCC CHECKIDENT. The first identity value will be the one specified in the table definition and it will be the same no matter if you insert the data for the first time or for the N-th
There is a simple way to implement communication between fragments of an activity using architectural components. Data can be passed between fragments of an activity using ViewModel and LiveData.
Fragments involved in communication need to use the same view model objects which is tied to activity life cycle. The view model object contains livedata object to which data is passed by one fragment and the second fragment listens for changes on LiveData and receives the data sent from fragment one.
For complete example see http://www.zoftino.com/passing-data-between-android-fragments-using-viewmodel
It works for me.
Inject $window
service in to your controller.
$window.open("somepath/", "_blank")
For laravel 8 in local it was ok but in production I had the problem. To solve it I used POST method and removed a simple slash at final of url. I changed it from:
/my/url/
to:
/my/url
and it works.
I don't know the reason. Perhaps somebody could explain it.
Chrome on Android makes it possible to use the Chrome developer tools on the desktop to inspect the HTML that was loaded from the Chrome application on the Android device.
See: https://developers.google.com/chrome-developer-tools/docs/remote-debugging
Depending on your table type, locking will perform differently, but so will a SELECT count. For MyISAM tables a simple SELECT count(*) FROM table should not lock the table since it accesses meta data to pull the record count. Innodb will take longer since it has to grab the table in a snapshot to count the records, but it shouldn't cause locking.
You should at least have concurrent_insert set to 1 (default). Then, if there are no "gaps" in the data file for the table to fill, inserts will be appended to the file and SELECT and INSERTs can happen simultaneously with MyISAM tables. Note that deleting a record puts a "gap" in the data file which will attempt to be filled with future inserts and updates.
If you rarely delete records, then you can set concurrent_insert equal to 2, and inserts will always be added to the end of the data file. Then selects and inserts can happen simultaneously, but your data file will never get smaller, no matter how many records you delete (except all records).
The bottom line, if you have a lot of updates, inserts and selects on a table, you should make it InnoDB. You can freely mix table types in a system though.
please see this article http://netjunky.net/sed-replace-path-with-slash-separators/
Just using | instead of /
This error "Could not load file or assembly 'example' or one of its dependencies. An attempt was made to load a program with an incorrect format" is typically caused by an incorrect application pool configuration.
The best way to send data from a parent component to a child is using props.
props
props
(array or object) in the child<child :name="variableOnParent">
See demo below:
Vue.component('child-comp', {
props: ['message'], // declare the props
template: '<p>At child-comp, using props in the template: {{ message }}</p>',
mounted: function () {
console.log('The props are also available in JS:', this.message);
}
})
new Vue({
el: '#app',
data: {
variableAtParent: 'DATA FROM PARENT!'
}
})
_x000D_
<script src="https://unpkg.com/[email protected]/dist/vue.min.js"></script>
<div id="app">
<p>At Parent: {{ variableAtParent }}<br>And is reactive (edit it) <input v-model="variableAtParent"></p>
<child-comp :message="variableAtParent"></child-comp>
</div>
_x000D_
An important point that the other answers forgot, is that "@keyword" is compiled into "keyword" in the CIL.
So if you have a framework that was made in, say, F#, which requires you to define a class with a property named "class", you can actually do it.
It is not that useful in practice, but not having it would prevent C# from some forms of language interop.
I usually see it used not for interop, but to avoid the keyword restrictions (usually on local variable names, where this is the only effect) ie.
private void Foo(){
int @this = 2;
}
but I would strongly discourage that! Just find another name, even if the 'best' name for the variable is one of the reserved names.
this code can be useful for you.
example of cursor use in sql server
DECLARE sampleCursor CURSOR FOR
SELECT K.Id FROM TableA K WHERE ....;
OPEN sampleCursor
FETCH NEXT FROM sampleCursor INTO @Id
WHILE @@FETCH_STATUS <> -1
BEGIN
UPDATE TableB
SET
...
If anyone comes here after me, this is the answer that worked for me.
NOTE: please make to read the comments before using this, this not complete. The best advice for update queries I can give is to switch to SqlServer ;)
update mytable t
set z = (
with comp as (
select b.*, 42 as computed
from mytable t
where bs_id = 1
)
select c.computed
from comp c
where c.id = t.id
)
Good luck,
GJ
One of the best approach if you do not want to return any columns from table2
is to use the NOT EXISTS
SELECT table1.id
FROM table1 T1
WHERE
NOT EXISTS (SELECT *
FROM table2 T2
WHERE T1.id = T2.user_one
OR T1.id = T2.user_two)
Semantically this says what you want to query: Select every row where there is no matching record in the second table.
MySQL is optimized for EXISTS
: It returns as soon as it finds the first matching record.
OpenPyxl
is quite a nice library, built to read/write Excel 2010 xlsx/xlsm files:
https://openpyxl.readthedocs.io/en/stable
The other answer, referring to it is using the deperciated function (get_sheet_by_name
). This is how to do it without it:
import openpyxl
wbkName = 'New.xlsx' #The file should be created before running the code.
wbk = openpyxl.load_workbook(wbkName)
wks = wbk['test1']
someValue = 1337
wks.cell(row=10, column=1).value = someValue
wbk.save(wbkName)
wbk.close
Since you ask for other better ways to handle the problem, here's another way using data.table
:
require(data.table) ## 1.9.2+
setDT(df)
df[a %in% c(0,1,3,4) | c == 4, g := 3L]
df[a %in% c(2,5,7) | (a==1 & b==4), g := 2L]
Note the order of conditional statements is reversed to get g
correctly. There's no copy of g
made, even during the second assignment - it's replaced in-place.
On larger data this would have better performance than using nested if-else
, as it can evaluate both 'yes' and 'no' cases, and nesting can get harder to read/maintain IMHO.
Here's a benchmark on relatively bigger data:
# R version 3.1.0
require(data.table) ## 1.9.2
require(dplyr)
DT <- setDT(lapply(1:6, function(x) sample(7, 1e7, TRUE)))
setnames(DT, letters[1:6])
# > dim(DT)
# [1] 10000000 6
DF <- as.data.frame(DT)
DT_fun <- function(DT) {
DT[(a %in% c(0,1,3,4) | c == 4), g := 3L]
DT[a %in% c(2,5,7) | (a==1 & b==4), g := 2L]
}
DPLYR_fun <- function(DF) {
mutate(DF, g = ifelse(a %in% c(2,5,7) | (a==1 & b==4), 2L,
ifelse(a %in% c(0,1,3,4) | c==4, 3L, NA_integer_)))
}
BASE_fun <- function(DF) { # R v3.1.0
transform(DF, g = ifelse(a %in% c(2,5,7) | (a==1 & b==4), 2L,
ifelse(a %in% c(0,1,3,4) | c==4, 3L, NA_integer_)))
}
system.time(ans1 <- DT_fun(DT))
# user system elapsed
# 2.659 0.420 3.107
system.time(ans2 <- DPLYR_fun(DF))
# user system elapsed
# 11.822 1.075 12.976
system.time(ans3 <- BASE_fun(DF))
# user system elapsed
# 11.676 1.530 13.319
identical(as.data.frame(ans1), as.data.frame(ans2))
# [1] TRUE
identical(as.data.frame(ans1), as.data.frame(ans3))
# [1] TRUE
Not sure if this is an alternative you'd asked for, but I hope it helps.
On newer versions of Windows (Windows 10 and Windows Server 2016) the tasks you create are located in C:\Windows\Tasks
. They will have the extension .job
For example if you create the task "DoWork" it will create the task in
C:\Windows\Tasks\DoWork.job
I was using npm (5.5.1) updating it to latest version solved my problem.
var leg= $scope.name.length;
$log.info(leg);
you can declare an empty array like below
String[] arr = new String[]{}; // declare an empty array
String[] arr2 = {"A", "B"}; // declare and assign values to an array
arr = arr2; // assign valued array to empty array
you can't assign values to above empty array like below
arr[0] = "A"; // you can't do this
It's a part of ISO-8601 date representation. It's incomplete because a complete date representation in this pattern should also contains the date:
2015-03-04T00:00:00.000Z //Complete ISO-8601 date
If you try to parse this date as it is you will receive an Invalid Date
error:
new Date('T00:00:00.000Z'); // Invalid Date
So, I guess the way to parse a timestamp in this format is to concat with any date
new Date('2015-03-04T00:00:00.000Z'); // Valid Date
Then you can extract only the part you want (timestamp part)
var d = new Date('2015-03-04T00:00:00.000Z');
console.log(d.getUTCHours()); // Hours
console.log(d.getUTCMinutes());
console.log(d.getUTCSeconds());
You can try this
$('div.easy_editor').css({'border-width':'9px', 'border-style':'solid', 'border-color':'red'});
The $('div.easy_editor')
refers to a collection of all divs that have the class easy editor already. There is no need to use each() unless there was some function that you wanted to run on each. The css() method actually applies to all the divs you find.
Here's an example for rotating about an arbitrary point (x,y) using only openCV
def rotate_about_point(x, y, degree, image):
rot_mtx = cv.getRotationMatrix2D((x, y), angle, 1)
abs_cos = abs(rot_mtx[0, 0])
abs_sin = abs(rot_mtx[0, 1])
rot_wdt = int(frm_hgt * abs_sin + frm_wdt * abs_cos)
rot_hgt = int(frm_hgt * abs_cos + frm_wdt * abs_sin)
rot_mtx += np.asarray([[0, 0, -lftmost_x],
[0, 0, -topmost_y]])
rot_img = cv.warpAffine(image, rot_mtx, (rot_wdt, rot_hgt),
borderMode=cv.BORDER_CONSTANT)
return rot_img
hi @JackSlayer94 please find the below example to understand how to make an array of size 5.
class Hero {_x000D_
name: string;_x000D_
constructor(text: string) {_x000D_
this.name = text;_x000D_
}_x000D_
_x000D_
display() {_x000D_
return "Hello, " + this.name;_x000D_
}_x000D_
_x000D_
}_x000D_
_x000D_
let heros:Hero[] = new Array(5);_x000D_
for (let i = 0; i < 5; i++){_x000D_
heros[i] = new Hero("Name: " + i);_x000D_
}_x000D_
_x000D_
for (let i = 0; i < 5; i++){_x000D_
console.log(heros[i].display());_x000D_
}
_x000D_
Since Firebase SDKs for JavaScript release 6.1, iOS release 6.4, and Android release version 18.1 all have a method to list files.
The documentation is a bit sparse so far, so I recommend checking out Rosário's answer for details.
Previous answer, since this approach can still be useful at times:
There currently is no API call in the Firebase SDK to list all files in a Cloud Storage folder from within an app. If you need such functionality, you should store the metadata of the files (such as the download URLs) in a place where you can list them. The Firebase Realtime Database and Cloud Firestore are perfect for this and allows you to also easily share the URLs with others.
You can find a good (but somewhat involved) sample of this in our FriendlyPix sample app. The relevant code for the web version is here, but there are also versions for iOS and Android.
If the server accessible with RPC (basically, if you can access a shared folder on it), you could free some memory and thus let the RDP service work properly. The following windows native commands can be used:
To get the list of memory consuming tasks:
tasklist /S <remote_server> /V /FI "MEMUSAGE gt 10000"
To kill a task by its name:
taskkill /S <remote_server> /IM <process_image_name> /F
To show the list of desktop sessions:
qwinsta.exe /SERVER:<remote_server>
To close an old abandoned desktop session:
logoff <session_id> /SERVER:<remote_server>
After some memory is freed, the RDP should start working.
Try this code to watch for, and report, a possible net::ERR_INSECURE_RESPONSE
I was having this issue as well, using a self-signed certificate, which I have chosen not to save into the Chrome Settings. After accessing the https domain and accepting the certificate, the ajax call works fine. But once that acceptance has timed-out or before it has first been accepted, the jQuery.ajax()
call fails silently: the timeout
parameter does not seem help and the error()
function never gets called.
As such, my code never receives a success()
or error()
call and therefore hangs. I believe this is a bug in jquery's handling of this error. My solution is to force the error()
call after a specified timeout.
This code does assume a jquery ajax call of the form jQuery.ajax({url: required, success: optional, error: optional, others_ajax_params: optional})
.
Note: You will likely want to change the function within the setTimeout
to integrate best with your UI: rather than calling alert()
.
const MS_FOR_HTTPS_FAILURE = 5000;
$.orig_ajax = $.ajax;
$.ajax = function(params)
{
var complete = false;
var success = params.success;
var error = params.error;
params.success = function() {
if(!complete) {
complete = true;
if(success) success.apply(this,arguments);
}
}
params.error = function() {
if(!complete) {
complete = true;
if(error) error.apply(this,arguments);
}
}
setTimeout(function() {
if(!complete) {
complete = true;
alert("Please ensure your self-signed HTTPS certificate has been accepted. "
+ params.url);
if(params.error)
params.error( {},
"Connection failure",
"Timed out while waiting to connect to remote resource. " +
"Possibly could not authenticate HTTPS certificate." );
}
}, MS_FOR_HTTPS_FAILURE);
$.orig_ajax(params);
}
I had a similar problem with PHP:
1) Check your error logs. Eliminate EVERY error before continuing. 2) Consider modifying your apache configuration to eliminate unused modules - this will reduce the footprint needed by PHP - here's a great link for this - it's specific to Wordpress but should still be very useful http://thethemefoundry.com/blog/optimize-apache-wordpress/
To give you an idea of the kind of bug I found, I had some code that was trying to post content to Facebook, Facebook then modified their API so this broke, I also used a 'content expirator' which basically meant that it kept retrying to post this content to Facebook and leaving loads of objects lying in memory.
Methods can only declare local variables. That is why the compiler reports an error when you try to declare it as public.
In the case of local variables you can not use any kind of accessor (public, protected or private).
You should also know what the static keyword means. In method checkYourself
, you use the Integer array locations
.
The static keyword distinct the elements that are accessible with object creation. Therefore they are not part of the object itself.
public class Test { //Capitalized name for classes are used in Java
private final init[] locations; //key final mean that, is must be assigned before object is constructed and can not be changed later.
public Test(int[] locations) {
this.locations = locations;//To access to class member, when method argument has the same name use `this` key word.
}
public boolean checkYourSelf(int value) { //This method is accessed only from a object.
for(int location : locations) {
if(location == value) {
return true; //When you use key word return insied of loop you exit from it. In this case you exit also from whole method.
}
}
return false; //Method should be simple and perform one task. So you can get more flexibility.
}
public static int[] locations = {1,2,3};//This is static array that is not part of object, but can be used in it.
public static void main(String[] args) { //This is declaration of public method that is not part of create object. It can be accessed from every place.
Test test = new Test(Test.locations); //We declare variable test, and create new instance (object) of class Test.
String result;
if(test.checkYourSelf(2)) {//We moved outside the string
result = "Hurray";
} else {
result = "Try again"
}
System.out.println(result); //We have only one place where write is done. Easy to change in future.
}
}
Maybe you can try the followings $indent -kr -i8 *.c
Hope it's useful for you!
There should be only one localhost defined, check sites-enabled or nginx.conf.
Parsing the output of git branch
is not recommended, and not a good answer for future readers on Stack Overflow.
git branch
is what is known as a porcelain command. Porcelain commands are not designed to be machine parsed and the output may change between different versions of Git. git
branch
in a way that makes it difficult to parse (for instance, colorization). If a user has set color.branch
then you will get control codes in the output, this will lead to error: branch 'foo' not found.
if you attempt to pipe it into another command. You can bypass this with the --no-color
flag to git branch
, but who knows what other user configurations might break things.git branch
may do other things that are annoying to parse, like
put an asterisk next to the currently checked out branchThe maintainer of git has this to say about scripting around git branch
output
To find out what the current branch is, casual/careless users may have scripted around git branch, which is wrong. We actively discourage against use of any Porcelain command, including git branch, in scripts, because the output from the command is subject to change to help human consumption use case.
Answers that suggest manually editing files in the .git
directory (like .git/refs/heads) are similarly problematic (refs may be in .git/packed-refs instead, or Git may change their internal layout in the future).
Git provides the for-each-ref
command to retrieve a list of branches.
Git 2.7.X will introduce the --merged
option to so you could do something like the below to find and delete all branches merged into HEAD
for mergedBranch in $(git for-each-ref --format '%(refname:short)' --merged HEAD refs/heads/)
do
git branch -d ${mergedBranch}
done
Git 2.6.X and older, you will need to list all local branches and then test them individually to see if they have been merged (which will be significantly slower and slightly more complicated).
for branch in $(git for-each-ref --format '%(refname:short)' refs/heads/)
do
git merge-base --is-ancestor ${branch} HEAD && git branch -d ${branch}
done
You can use >>
to print in another file.
echo "hello" >> logfile.txt
as a single line:
long value_ms = std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::time_point_cast<std::chrono::milliseconds>(std::chrono::high_resolution_clock::now()).time_since_epoch()).count();
I've found that this can happen due to a number of various reasons.
In my case when I scroll to the end of the SQL import "Report", under the "Post-execute (Success)" heading it will tell me how many rows were copied and it's usually the next row in sheet which has the issue. Also you can tell which column by the import messages (in your case it was "Copy of F2") so you can generally find out which was the offending cell in Excel.
I've seen this happen for very silly reasons such as the date format in Excel being different than previous rows. For example cell A2 being "05/02/2017" while A3 being "5/2/2017" or even "05-02-2017". It seems the import wants things to be perfectly consistent.
It even happens if the Excel formats are different so if B2 is "512" but an Excel "Number" format and B3 is "512" but an Excel "Text" format then the Cell will cause an error.
I've also had situations where I literally had to delete all the "empty" rows below my data rows in the Excel sheet. Sometimes they appear empty but Excel considers them having "blank" data or something like that so the import tries to import them as well. This usually happens if you've had previous data in your Excel sheet which you've cleared but haven't properly deleted the rows.
And then there's the obvious reasons of trying to import text value into an integer column or insert a NULL into a NOT NULL column as mentioned by the others.
You need to run pip list
in bash not in python.
pip list
DEPRECATION: Python 2.6 is no longer supported by the Python core team, please upgrade your Python. A future version of pip will drop support for Python 2.6
argparse (1.4.0)
Beaker (1.3.1)
cas (0.15)
cups (1.0)
cupshelpers (1.0)
decorator (3.0.1)
distribute (0.6.10)
---and other modules
Try This code:
public class GenericCompare<T> : IEqualityComparer<T> where T : class
{
private Func<T, object> _expr { get; set; }
public GenericCompare(Func<T, object> expr)
{
this._expr = expr;
}
public bool Equals(T x, T y)
{
var first = _expr.Invoke(x);
var sec = _expr.Invoke(y);
if (first != null && first.Equals(sec))
return true;
else
return false;
}
public int GetHashCode(T obj)
{
return obj.GetHashCode();
}
}
Example of its use would be
collection = collection
.Except(ExistedDataEles, new GenericCompare<DataEle>(x=>x.Id))
.ToList();
Usually I just check if the index is less than the array size
if (index < list.size()) {
...
}
If you are also concerned of index being a negative value, use following
if (index >= 0 && index < list.size()) {
...
}
You should use HTML5 data attributes. You can create your own attributes and save different values in them.
Here is the solution for Rest API
class Program
{
static void Main(string[] args)
{
BaseClient clientbase = new BaseClient("https://website.com/api/v2/", "username", "password");
BaseResponse response = new BaseResponse();
BaseResponse response = clientbase.GetCallV2Async("Candidate").Result;
}
public async Task<BaseResponse> GetCallAsync(string endpoint)
{
try
{
HttpResponseMessage response = await client.GetAsync(endpoint + "/").ConfigureAwait(false);
if (response.IsSuccessStatusCode)
{
baseresponse.ResponseMessage = await response.Content.ReadAsStringAsync();
baseresponse.StatusCode = (int)response.StatusCode;
}
else
{
baseresponse.ResponseMessage = await response.Content.ReadAsStringAsync();
baseresponse.StatusCode = (int)response.StatusCode;
}
return baseresponse;
}
catch (Exception ex)
{
baseresponse.StatusCode = 0;
baseresponse.ResponseMessage = (ex.Message ?? ex.InnerException.ToString());
}
return baseresponse;
}
}
public class BaseResponse
{
public int StatusCode { get; set; }
public string ResponseMessage { get; set; }
}
public class BaseClient
{
readonly HttpClient client;
readonly BaseResponse baseresponse;
public BaseClient(string baseAddress, string username, string password)
{
HttpClientHandler handler = new HttpClientHandler()
{
Proxy = new WebProxy("http://127.0.0.1:8888"),
UseProxy = false,
};
client = new HttpClient(handler);
client.BaseAddress = new Uri(baseAddress);
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
var byteArray = Encoding.ASCII.GetBytes(username + ":" + password);
client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Basic", Convert.ToBase64String(byteArray));
baseresponse = new BaseResponse();
}
}
I recently upgraded from SQL 2008 R2 to SQL 2012 and had a similar issue. The problem was the firewall, but more specifically the firewall rule for SQL SERVER. The custom rule was pointed to the prior version of SQL Server. Try this, open Windows Firewall>Advanced setting. Find the SQL Server Rule (it may have a custom name). Right-Click and go to properties, then Programs and Services Tab. If Programs-This program is selected, you should browse for the proper version of sqlserver.exe.
I believe you are misinterpreting the JSON format for key values. You should store your string as
NSString *jsonString = @"{\"ID\":{\"Content\":268,\"type\":\"text\"},\"ContractTemplateID\":{\"Content\":65,\"type\":\"text\"}}";
NSData *data = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
id json = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
Now if you do following NSLog statement
NSLog(@"%@",[json objectForKey:@"ID"]);
Result would be another NSDictionary.
{
Content = 268;
type = text;
}
Hope this helps to get clear understanding.
Considering larsks' answer, you can get it working with a single command with "--force":
git mv --force myfile MyFile
This is quite old and @SinkingPoint already gave a great answer above. Now, with functional idioms available in Java 8 we could give it one more twist. You would have two lambdas:
Function<String, Boolean> hasLowerCase = s -> s.chars().filter(c -> Character.isLowerCase(c)).count() > 0;
Function<String, Boolean> hasUpperCase = s -> s.chars().filter(c -> Character.isUpperCase(c)).count() > 0;
Then in code we could check password rules like this:
if (!hasUppercase.apply(password)) System.out.println("Must have an uppercase Character");
if (!hasLowercase.apply(password)) System.out.println("Must have a lowercase Character");
As to the other checks:
Function<String,Boolean> isAtLeast8 = s -> s.length() >= 8; //Checks for at least 8 characters
Function<String,Boolean> hasSpecial = s -> !s.matches("[A-Za-z0-9 ]*");//Checks at least one char is not alpha numeric
Function<String,Boolean> noConditions = s -> !(s.contains("AND") || s.contains("NOT"));//Check that it doesn't contain AND or NOT
In some cases, it is arguable, whether creating the lambda adds value in terms of communicating intent, but the good thing about lambdas is that they are functional.
Another difference is that <import>
allows importing by referring to another namespace. <include>
only allows importing by referring to a URI of intended include schema. That is definitely another difference than inter-intra namespace importing.
For example, the xml schema validator may already know the locations of all schemas by namespace already. Especially considering that referring to XML namespaces by URI may be problematic on different systems where classpath:// means nothing, or where http:// isn't allowed, or where some URI doesn't point to the same thing as it does on another system.
Code sample of valid and invalid imports and includes:
Valid:
<xsd:import namespace="some/name/space"/>
<xsd:import schemaLocation="classpath://mine.xsd"/>
<xsd:include schemaLocation="classpath://mine.xsd"/>
Invalid:
<xsd:include namespace="some/name/space"/>
Here's a reworking of your sample to get you started.
your sample has a static event - it's more usual for an event to come from a class instance, but I've left it static below.
the sample below also uses the more standard naming OnXxx for the method that raises the event.
the sample below does not consider thread-safety, which may well be more of an issue if you insist on your event being static.
.
public enum MyEvents{
Event1
}
public class MyEventArgs : EventArgs
{
public MyEventArgs(MyEvents myEvents)
{
MyEvents = myEvents;
}
public MyEvents MyEvents { get; private set; }
}
public static class MyClass
{
public static event EventHandler<MyEventArgs> EventTriggered;
public static void Trigger(MyEvents myEvents)
{
OnMyEvent(new MyEventArgs(myEvents));
}
protected static void OnMyEvent(MyEventArgs e)
{
if (EventTriggered != null)
{
// Normally the first argument (sender) is "this" - but your example
// uses a static event, so I'm passing null instead.
// EventTriggered(this, e);
EventTriggered(null, e);
}
}
}
First, don't do it that way. The best approach is to use find -exec
properly:
# this is safe
find test -type d -exec echo '{}' +
The other safe approach is to use NUL-terminated list, though this requires that your find support -print0
:
# this is safe
while IFS= read -r -d '' n; do
printf '%q\n' "$n"
done < <(find test -mindepth 1 -type d -print0)
You can also populate an array from find, and pass that array later:
# this is safe
declare -a myarray
while IFS= read -r -d '' n; do
myarray+=( "$n" )
done < <(find test -mindepth 1 -type d -print0)
printf '%q\n' "${myarray[@]}" # printf is an example; use it however you want
If your find doesn't support -print0
, your result is then unsafe -- the below will not behave as desired if files exist containing newlines in their names (which, yes, is legal):
# this is unsafe
while IFS= read -r n; do
printf '%q\n' "$n"
done < <(find test -mindepth 1 -type d)
If one isn't going to use one of the above, a third approach (less efficient in terms of both time and memory usage, as it reads the entire output of the subprocess before doing word-splitting) is to use an IFS
variable which doesn't contain the space character. Turn off globbing (set -f
) to prevent strings containing glob characters such as []
, *
or ?
from being expanded:
# this is unsafe (but less unsafe than it would be without the following precautions)
(
IFS=$'\n' # split only on newlines
set -f # disable globbing
for n in $(find test -mindepth 1 -type d); do
printf '%q\n' "$n"
done
)
Finally, for the command-line parameter case, you should be using arrays if your shell supports them (i.e. it's ksh, bash or zsh):
# this is safe
for d in "$@"; do
printf '%s\n' "$d"
done
will maintain separation. Note that the quoting (and the use of $@
rather than $*
) is important. Arrays can be populated in other ways as well, such as glob expressions:
# this is safe
entries=( test/* )
for d in "${entries[@]}"; do
printf '%s\n' "$d"
done