Try this option:
radio1.Items.FindByValue("1").Selected = true;
Even though, the best approach for this situation is set custom CSS styles - an alternative could be:
Width
property and set the percentaje as you see more suitable for your purposes.In my desired scenario, I need set (2) radiobuttons/items as follows:
o Item 1 | o Item 2 |
Example:
<asp:RadioButtonList ID="rbtnLstOptionsGenerateCertif" runat="server"
BackColor="Transparent" BorderColor="Transparent" RepeatDirection="Horizontal"
EnableTheming="False" Width="40%">
<asp:ListItem Text="Item 1" Value="0" />
<asp:ListItem Text="Item 2" Value="1" />
</asp:RadioButtonList>
Rendered result:
<table id="ctl00_ContentPlaceHolder_rbtnLstOptionsGenerateCertif" class="chxbx2" border="0" style="background-color:Transparent;border-color:Transparent;width:40%;">
<tbody>
<tr>
<td>
<input id="ctl00_ContentPlaceHolder_rbtnLstOptionsGenerateCertif_0" type="radio" name="ctl00$ContentPlaceHolder$rbtnLstOptionsGenerateCertif" value="0" checked="checked">
<label for="ctl00_ContentPlaceHolder_rbtnLstOptionsGenerateCertif_0">Item 1</label>
</td>
<td>
<input id="ctl00_ContentPlaceHolder_rbtnLstOptionsGenerateCertif_1" type="radio" name="ctl00$ContentPlaceHolder$rbtnLstOptionsGenerateCertif" value="1">
<label for="ctl00_ContentPlaceHolder_rbtnLstOptionsGenerateCertif_1">Item 2</label>
</td>
</tr>
</tbody>
</table>
_x000D_
To trigger the onClick event on a radio-button invoke the click()
method on the DOM element:
document.getElementById("radioButton").click()
using jquery:
$("#radioButton").click()
AngularJs:
angular.element('#radioButton').trigger('click')
Here's my version of that nice CSS solution JS Fiddle example posted above.
HTML
<div id="donate">
<label class="blue"><input type="radio" name="toggle"><span>$20</span></label>
<label class="green"><input type="radio" name="toggle"><span>$50</span></label>
<label class="yellow"><input type="radio" name="toggle"><span>$100</span></label>
<label class="pink"><input type="radio" name="toggle"><span>$500</span></label>
<label class="purple"><input type="radio" name="toggle"><span>$1000</span></label>
</div>
CSS
body {
font-family:sans-serif;
}
#donate {
margin:4px;
float:left;
}
#donate label {
float:left;
width:170px;
margin:4px;
background-color:#EFEFEF;
border-radius:4px;
border:1px solid #D0D0D0;
overflow:auto;
}
#donate label span {
text-align:center;
font-size: 32px;
padding:13px 0px;
display:block;
}
#donate label input {
position:absolute;
top:-20px;
}
#donate input:checked + span {
background-color:#404040;
color:#F7F7F7;
}
#donate .yellow {
background-color:#FFCC00;
color:#333;
}
#donate .blue {
background-color:#00BFFF;
color:#333;
}
#donate .pink {
background-color:#FF99FF;
color:#333;
}
#donate .green {
background-color:#A3D900;
color:#333;
}
#donate .purple {
background-color:#B399FF;
color:#333;
}
Styled with coloured buttons :)
Use:
:wq!
The exclamation mark is used for overriding read-only mode.
I don't think that there are any neat tricks you can do storing this as you can do for example with an MD5 hash.
I think your best bet is to store it as a CHAR(60)
as it is always 60 chars long
How about this way:
List<int> myList = new List<int>(){1, 2, 3, 4}; //or any other type
myList.Sort();
int greatestValue = myList[ myList.Count - 1 ];
You basically let the Sort()
method to do the job for you instead of writing your own method. Unless you don't want to sort your collection.
1). You can use getter methods from WC_Order
and WC_Abstract_Order
classes on the WC_Order
object instance like:
// Get an instance of the WC_Order Object from the Order ID (if required)
$order = wc_get_order( $order_id );
// Get the Customer ID (User ID)
$customer_id = $order->get_customer_id(); // Or $order->get_user_id();
// Get the WP_User Object instance
$user = $order->get_user();
// Get the WP_User roles and capabilities
$user_roles = $user->roles;
// Get the Customer billing email
$billing_email = $order->get_billing_email();
// Get the Customer billing phone
$billing_phone = $order->get_billing_phone();
// Customer billing information details
$billing_first_name = $order->get_billing_first_name();
$billing_last_name = $order->get_billing_last_name();
$billing_company = $order->get_billing_company();
$billing_address_1 = $order->get_billing_address_1();
$billing_address_2 = $order->get_billing_address_2();
$billing_city = $order->get_billing_city();
$billing_state = $order->get_billing_state();
$billing_postcode = $order->get_billing_postcode();
$billing_country = $order->get_billing_country();
// Customer shipping information details
$shipping_first_name = $order->get_shipping_first_name();
$shipping_last_name = $order->get_shipping_last_name();
$shipping_company = $order->get_shipping_company();
$shipping_address_1 = $order->get_shipping_address_1();
$shipping_address_2 = $order->get_shipping_address_2();
$shipping_city = $order->get_shipping_city();
$shipping_state = $order->get_shipping_state();
$shipping_postcode = $order->get_shipping_postcode();
$shipping_country = $order->get_shipping_country();
2). You can also use the WC_Order
get_data()
method, to get an unprotected data array from Order meta data like:
// Get an instance of the WC_Order Object from the Order ID (if required)
$order = wc_get_order( $order_id );
// Get the Order meta data in an unprotected array
$data = $order->get_data(); // The Order data
$order_id = $data['id'];
$order_parent_id = $data['parent_id'];
// Get the Customer ID (User ID)
$customer_id = $data['customer_id'];
## BILLING INFORMATION:
$billing_email = $data['billing']['email'];
$billing_phone = $order_data['billing']['phone'];
$billing_first_name = $data['billing']['first_name'];
$billing_last_name = $data['billing']['last_name'];
$billing_company = $data['billing']['company'];
$billing_address_1 = $data['billing']['address_1'];
$billing_address_2 = $data['billing']['address_2'];
$billing_city = $data['billing']['city'];
$billing_state = $data['billing']['state'];
$billing_postcode = $data['billing']['postcode'];
$billing_country = $data['billing']['country'];
## SHIPPING INFORMATION:
$shipping_first_name = $data['shipping']['first_name'];
$shipping_last_name = $data['shipping']['last_name'];
$shipping_company = $data['shipping']['company'];
$shipping_address_1 = $data['shipping']['address_1'];
$shipping_address_2 = $data['shipping']['address_2'];
$shipping_city = $data['shipping']['city'];
$shipping_state = $data['shipping']['state'];
$shipping_postcode = $data['shipping']['postcode'];
$shipping_country = $data['shipping']['country'];
Now to get the user account data (from an Order ID):
1). You can use the methods from WC_Customer
Class:
// Get the user ID from an Order ID
$user_id = get_post_meta( $order_id, '_customer_user', true );
// Get an instance of the WC_Customer Object from the user ID
$customer = new WC_Customer( $user_id );
$username = $customer->get_username(); // Get username
$user_email = $customer->get_email(); // Get account email
$first_name = $customer->get_first_name();
$last_name = $customer->get_last_name();
$display_name = $customer->get_display_name();
// Customer billing information details (from account)
$billing_first_name = $customer->get_billing_first_name();
$billing_last_name = $customer->get_billing_last_name();
$billing_company = $customer->get_billing_company();
$billing_address_1 = $customer->get_billing_address_1();
$billing_address_2 = $customer->get_billing_address_2();
$billing_city = $customer->get_billing_city();
$billing_state = $customer->get_billing_state();
$billing_postcode = $customer->get_billing_postcode();
$billing_country = $customer->get_billing_country();
// Customer shipping information details (from account)
$shipping_first_name = $customer->get_shipping_first_name();
$shipping_last_name = $customer->get_shipping_last_name();
$shipping_company = $customer->get_shipping_company();
$shipping_address_1 = $customer->get_shipping_address_1();
$shipping_address_2 = $customer->get_shipping_address_2();
$shipping_city = $customer->get_shipping_city();
$shipping_state = $customer->get_shipping_state();
$shipping_postcode = $customer->get_shipping_postcode();
$shipping_country = $customer->get_shipping_country();
2). The WP_User
object (WordPress):
// Get the user ID from an Order ID
$user_id = get_post_meta( $order_id, '_customer_user', true );
// Get the WP_User instance Object
$user = new WP_User( $user_id );
$username = $user->username; // Get username
$user_email = $user->email; // Get account email
$first_name = $user->first_name;
$last_name = $user->last_name;
$display_name = $user->display_name;
// Customer billing information details (from account)
$billing_first_name = $user->billing_first_name;
$billing_last_name = $user->billing_last_name;
$billing_company = $user->billing_company;
$billing_address_1 = $user->billing_address_1;
$billing_address_2 = $user->billing_address_2;
$billing_city = $user->billing_city;
$billing_state = $user->billing_state;
$billing_postcode = $user->billing_postcode;
$billing_country = $user->billing_country;
// Customer shipping information details (from account)
$shipping_first_name = $user->shipping_first_name;
$shipping_last_name = $user->shipping_last_name;
$shipping_company = $user->shipping_company;
$shipping_address_1 = $user->shipping_address_1;
$shipping_address_2 = $user->shipping_address_2;
$shipping_city = $user->shipping_city;
$shipping_state = $user->shipping_state;
$shipping_postcode = $user->shipping_postcode;
$shipping_country = $user->shipping_country;
Related: How to get WooCommerce order details
static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
/* PUT THIS LINE IN YOUR CLASS PROGRAM MAIN() */
AppDomain.CurrentDomain.AssemblyResolve += (sender, arg) => { if (arg.Name.StartsWith("YOURDLL")) return Assembly.Load(Properties.Resources.YOURDLL); return null; };
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Form1());
}
}
First add the DLL´s to your project-Resources. Add a folder "Resources"
input {_x000D_
border:solid 1px #ddd;_x000D_
}_x000D_
input.search {_x000D_
padding-left:20px;_x000D_
background-repeat: no-repeat;_x000D_
background-position-y: 1px;_x000D_
background-image: url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABQAAAASCAYAAABb0P4QAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsMAAA7DAcdvqGQAAADbSURBVDhP5ZI9C4MwEIb7//+BEDgICA6C4OQgBJy6dRIEB6EgCNkEJ4e3iT2oHzH9wHbpAwfyJvfkJDnhYH4kHDVKlSAigSAQoCiBKjVGXvaxFXZnxBQYkSlBICII+22K4jM63rbHSthCSdsskVX9Y6KxR5XJSSpVy6GbpbBKp6aw0BzM0ShCe1iKihMXC6EuQtMQwukzPFu3fFd4+C+/cimUNxy6WQkNnmdzL3NYPfDmLVuhZf2wZYz80qDkKX1St3CXAfVMqq4cz3hTaGEpmctxDPmB0M/fCYEbAwZYyVKYcroAAAAASUVORK5CYII=);_x000D_
}
_x000D_
<input class="search">
_x000D_
Type
netsh wlan set hostednetwork mode=allow ssid=hotspotname key=123456789
perform all steps in proper order.. for more detail with image ,have a look..this might help to setup hotspot correctly.
http://www.infogeekers.com/turn-windows-8-into-wifi-hotspot/
I think all you need to do for your function is just add PtrSafe: i.e. the first line of your first function should look like this:
Private Declare PtrSafe Function swe_azalt Lib "swedll32.dll" ......
Here
$type='testing' //it's string
mysql_query("INSERT INTO contents (type, reporter, description) VALUES('$type', 'john', 'whatever')");//at that time u can use it(for string)
$type=12 //it's integer
mysql_query("INSERT INTO contents (type, reporter, description) VALUES($type, 'john', 'whatever')");//at that time u can use $type
This:
function myfunction()
{
if (a == 'stop') // How can I stop working of function here?
{
return;
}
}
One thing which is invariably true is that at this time, the device would be suffocating for some memory (which is usually the reason for GC to most likely get triggered).
As mentioned by almost all authors earlier, this issue surfaces when Android tries to run GC while the app is in background. In most of the cases where we observed it, user paused the app by locking their screen. This might also indicate memory leak somewhere in the application, or the device being too loaded already. So the only legitimate way to minimize it is:
I could do it like this
For case insensitive contains, use the following:
//a[contains(translate(text(),'PROGRAMMING','programming'), 'programming')]/@href
translate converts capital letters in PROGRAMMING to lower case programming.
If you are using Joseph's answer which is a great answer, and you run these back to back like this:
dim i = GetRandom(1, 1715)
dim o = GetRandom(1, 1715)
Then the result could come back the same over and over because it processes the call so quickly. This may not have been an issue in '08, but since the processors are much faster today, the function doesn't allow the system clock enough time to change prior to making the second call.
Since the System.Random() function is based on the system clock, we need to allow enough time for it to change prior to the next call. One way of accomplishing this is to pause the current thread for 1 millisecond. See example below:
Public Function GetRandom(ByVal min as Integer, ByVal max as Integer) as Integer
Static staticRandomGenerator As New System.Random
max += 1
Return staticRandomGenerator.Next(If(min > max, max, min), If(min > max, min, max))
End Function
It also helps you to stop using your mouse so much!
epoch is an iteration of subset of the samples for training, for example, the gradient descent algorithm in neutral network. A good reference is: http://neuralnetworksanddeeplearning.com/chap1.html
Note that the page has a code for the gradient descent algorithm which uses epoch
def SGD(self, training_data, epochs, mini_batch_size, eta,
test_data=None):
"""Train the neural network using mini-batch stochastic
gradient descent. The "training_data" is a list of tuples
"(x, y)" representing the training inputs and the desired
outputs. The other non-optional parameters are
self-explanatory. If "test_data" is provided then the
network will be evaluated against the test data after each
epoch, and partial progress printed out. This is useful for
tracking progress, but slows things down substantially."""
if test_data: n_test = len(test_data)
n = len(training_data)
for j in xrange(epochs):
random.shuffle(training_data)
mini_batches = [
training_data[k:k+mini_batch_size]
for k in xrange(0, n, mini_batch_size)]
for mini_batch in mini_batches:
self.update_mini_batch(mini_batch, eta)
if test_data:
print "Epoch {0}: {1} / {2}".format(
j, self.evaluate(test_data), n_test)
else:
print "Epoch {0} complete".format(j)
Look at the code. For each epoch, we randomly generate a subset of the inputs for the gradient descent algorithm. Why epoch is effective is also explained in the page. Please take a look.
Not the straight forward way, but probably much faster than a simple Python implementation:
line = subprocess.check_output(['tail', '-1', filename])
The $
symbol simply invokes the jQuery library's selector functionality. So $("#Text")
returns the jQuery object for the Text
div
which can then be modified.
It's unclear whether your question is asking for the get_or_create method (available from at least Django 1.3) or the update_or_create method (new in Django 1.7). It depends on how you want to update the user object.
Sample use is as follows:
# In both cases, the call will get a person object with matching
# identifier or create one if none exists; if a person is created,
# it will be created with name equal to the value in `name`.
# In this case, if the Person already exists, its existing name is preserved
person, created = Person.objects.get_or_create(
identifier=identifier, defaults={"name": name}
)
# In this case, if the Person already exists, its name is updated
person, created = Person.objects.update_or_create(
identifier=identifier, defaults={"name": name}
)
An example where things could go wrong with Shell=True is shown here
>>> from subprocess import call
>>> filename = input("What file would you like to display?\n")
What file would you like to display?
non_existent; rm -rf / # THIS WILL DELETE EVERYTHING IN ROOT PARTITION!!!
>>> call("cat " + filename, shell=True) # Uh-oh. This will end badly...
Check the doc here: subprocess.call()
Try using jQuery for the event listener, it will then work in Firefox.
myAudio = new Audio('someSound.ogg');
$(myAudio).bind('ended', function() {
myAudio.currentTime = 0;
myAudio.play();
});
myAudio.play();
Something like that.
I've heard stories that they were to be included close to the orignal Java release. Oak was the precursor to Java, and in some spec documents there was mention of usigned values. Unfortunately these never made it into the Java language. As far as anyone has been able to figure out they just didn't get implemented, likely due to a time constraint.
.loc
and .iloc
are used for indexing, i.e., to pull out portions of data. In essence, the difference is that .loc
allows label-based indexing, while .iloc
allows position-based indexing.
If you get confused by .loc
and .iloc
, keep in mind that .iloc
is based on the index (starting with i) position, while .loc
is based on the label (starting with l).
.loc
.loc
is supposed to be based on the index labels and not the positions, so it is analogous to Python dictionary-based indexing. However, it can accept boolean arrays, slices, and a list of labels (none of which work with a Python dictionary).
iloc
.iloc
does the lookup based on index position, i.e., pandas
behaves similarly to a Python list. pandas
will raise an IndexError
if there is no index at that location.
The following examples are presented to illustrate the differences between .iloc
and .loc
. Let's consider the following series:
>>> s = pd.Series([11, 9], index=["1990", "1993"], name="Magic Numbers")
>>> s
1990 11
1993 9
Name: Magic Numbers , dtype: int64
.iloc
Examples
>>> s.iloc[0]
11
>>> s.iloc[-1]
9
>>> s.iloc[4]
Traceback (most recent call last):
...
IndexError: single positional indexer is out-of-bounds
>>> s.iloc[0:3] # slice
1990 11
1993 9
Name: Magic Numbers , dtype: int64
>>> s.iloc[[0,1]] # list
1990 11
1993 9
Name: Magic Numbers , dtype: int64
.loc
Examples
>>> s.loc['1990']
11
>>> s.loc['1970']
Traceback (most recent call last):
...
KeyError: ’the label [1970] is not in the [index]’
>>> mask = s > 9
>>> s.loc[mask]
1990 11
Name: Magic Numbers , dtype: int64
>>> s.loc['1990':] # slice
1990 11
1993 9
Name: Magic Numbers, dtype: int64
Because s
has string index values, .loc
will fail when
indexing with an integer:
>>> s.loc[0]
Traceback (most recent call last):
...
KeyError: 0
"The project works on the laptop, but now having copied the updated source code onto the desktop ..."
I did something similar, creating two versions of a project and copying files between them. It gave me the same error.
My solution was to go into the project file, where I discovered that what had looked like this:
<Compile Include="App_Code\Common\Pair.cs" />
<Compile Include="App_Code\Common\QueryCommand.cs" />
Now looked like this:
<Content Include="App_Code\Common\Pair.cs">
<SubType>Code</SubType>
</Content>
<Content Include="App_Code\Common\QueryCommand.cs">
<SubType>Code</SubType>
</Content>
When I changed them back, Visual Studio was happy again.
Someone else suggested .PHONY which is definitely correct. .PHONY should be used for any rule for which a date comparison between the input and the output is invalid. Since you don't have any targets of the form output: input
you should use .PHONY for ALL of them!
All that said, you probably should define some variables at the top of your makefile for the various filenames, and define real make rules that have both input and output sections so you can use the benefits of make, namely that you'll only actually compile things that are necessary to copmile!
Edit: added example. Untested, but this is how you do .PHONY
.PHONY: clean
clean:
$(clean)
Something like this
String myTime = "14:10";
SimpleDateFormat df = new SimpleDateFormat("HH:mm");
Date d = df.parse(myTime);
Calendar cal = Calendar.getInstance();
cal.setTime(d);
cal.add(Calendar.MINUTE, 10);
String newTime = df.format(cal.getTime());
As a fair warning there might be some problems if daylight savings time is involved in this 10 minute period.
Well one thing you could do is if you have a switch:
switch(SomeEnum)
{
case SomeEnum.One:
DoThings(someUser);
break;
case SomeEnum.Two:
DoSomethingElse(someUser);
break;
}
And with the might power of actions you can turn that switch into a dictionary:
Dictionary<SomeEnum, Action<User>> methodList =
new Dictionary<SomeEnum, Action<User>>()
methodList.Add(SomeEnum.One, DoSomething);
methodList.Add(SomeEnum.Two, DoSomethingElse);
...
methodList[SomeEnum](someUser);
Or you could take this farther:
SomeOtherMethod(Action<User> someMethodToUse, User someUser)
{
someMethodToUse(someUser);
}
....
var neededMethod = methodList[SomeEnum];
SomeOtherMethod(neededMethod, someUser);
Just a couple of examples. Of course the more obvious use would be Linq extension methods.
This Solution is of O(n^2) complexity. O(1) is the space complexity.
public class longestPalindromeInAString {
public static void main(String[] args) {
String a = "xyMADAMpRACECARwl";
String res = "";
//String longest = a.substring(0,1);
//System.out.println("longest => " +longest);
for (int i = 0; i < a.length(); i++) {
String temp = helper(a,i,i);//even palindrome
if(temp.length() > res.length()) {res = temp ;}
temp = helper(a,i,i+1);// odd length palindrome
if(temp.length() > res.length()) { res = temp ;}
}//for
System.out.println(res);
System.out.println("length of " + res + " is " + res.length());
}
private static String helper(String a, int left, int right) {
while(left>= 0 && right <= a.length() -1 && a.charAt(left) == a.charAt(right)) {
left-- ;right++ ;
}
String curr = a.substring(left + 1 , right);
System.out.println("curr =>" +curr);
return curr ;
}
}
This example illustrate how to use AJAX to pull resourcess from any website. it works across browsers. i have tested it on IE8-IE10, safari, chrome, firefox, opera.
if (window.XDomainRequest) xmlhttp = new XDomainRequest();
else if (window.XMLHttpRequest) xmlhttp = new XMLHttpRequest();
else xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
xmlhttp.open("GET", "http://api.hostip.info/get_html.php", false);
xmlhttp.send();
hostipInfo = xmlhttp.responseText.split("\n");
var IP = false;
for (i = 0; hostipInfo.length >= i; i++) {
if (hostipInfo[i]) {
ipAddress = hostipInfo[i].split(":");
if (ipAddress[0] == "IP") {
IP = ipAddress[1];
}
}
}
return IP;
you should use the break statement
usually it's use this way
$i = 0;
foreach($data as $key => $row){
if(++$i > 2) break;
}
on the same fashion the continue statement exists if you need to skip some items.
jstat -gccapacity javapid (ex. stat -gccapacity 28745)
jstat -gccapacity javapid gaps frames (ex. stat -gccapacity 28745 550 10 )
Sample O/P of above command
NGCMN NGCMX NGC S0C
87040.0 1397760.0 1327616.0 107520.0
NGCMN Minimum new generation capacity (KB).
NGCMX Maximum new generation capacity (KB).
NGC Current new generation capacity (KB).
Get more details about this at http://docs.oracle.com/javase/1.5.0/docs/tooldocs/share/jstat.html
since strings can be compared directly in javascript, this will do the job
list.sort(function (a, b) {
return a.attr > b.attr ? 1: -1;
})
the subtraction in a sort function is used only when non alphabetical (numerical) sort is desired and of course it does not work with strings
This works in Bash:
for f in *.txt; do cat $f; echo; done
In contrast to answers with >>
(append), the output of this command can be piped into other programs.
Examples:
for f in File*.txt; do cat $f; echo; done > finalfile.txt
(for ... done) > finalfile.txt
(parens are optional)for ... done | less
(piping into less)for ... done | head -n -1
(this strips off the trailing blank line)There are ways of executing tests in a given order. Normally though, tests have to be repeatable and independent to guarantee it is testing only the desired functionality and is not dependent on side effects of code outside of what is being tested.
So, to answer your question, you'll need to provide more information such as WHY it is important to run tests in a specific order.
node.cloneNode() hardly seems like a hack. You can clone the node and append it to any desired parent element, and also manipulate it by manipulating individual properties, rather than having to e.g. run regular expressions on it, or add it in to the DOM, then manipulate it afterwords.
That said, you could also iterate over the attributes of the element to construct an HTML string representation of it. It seems likely this is how any outerHTML function would be implemented were jQuery to add one.
This video shows how to update a fork directly from GitHub
Steps:
Pull Requests
.New Pull Request
. By default, GitHub will compare the original with your fork, and there shouldn’t be anything to compare if you didn’t make any changes.switching the base
. Now GitHub will compare your fork with the original, and you should see all the latest changes.Create a pull request
for this comparison and assign a predictable name to your pull request (e.g., Update from original).Create pull request
.Merge pull request
and finally Confirm
merge. If your fork didn’t have any changes, you will be able to merge it automatically.mipadi's answer didn't quite work for me, I needed to do this :
git checkout --ours path/to/file.bin
or, to keep the version being merged in:
git checkout --theirs path/to/file.bin
then
git add path/to/file.bin
And then I was able to do "git mergetool" again and continue onto the next conflict.
var result = nullableproperty ?? defaultvalue;
The ??
(null-coalescing operator) means if the first argument is null
, return the second one instead.
set.seed
is a base function that it is able to generate (every time you want) together other functions (rnorm
, runif
, sample
) the same random value.
Below an example without set.seed
> set.seed(NULL)
> rnorm(5)
[1] 1.5982677 -2.2572974 2.3057461 0.5935456 0.1143519
> rnorm(5)
[1] 0.15135371 0.20266228 0.95084266 0.09319339 -1.11049182
> set.seed(NULL)
> runif(5)
[1] 0.05697712 0.31892399 0.92547023 0.88360393 0.90015169
> runif(5)
[1] 0.09374559 0.64406494 0.65817582 0.30179009 0.19760375
> set.seed(NULL)
> sample(5)
[1] 5 4 3 1 2
> sample(5)
[1] 2 1 5 4 3
Below an example with set.seed
> set.seed(123)
> rnorm(5)
[1] -0.56047565 -0.23017749 1.55870831 0.07050839 0.12928774
> set.seed(123)
> rnorm(5)
[1] -0.56047565 -0.23017749 1.55870831 0.07050839 0.12928774
> set.seed(123)
> runif(5)
[1] 0.2875775 0.7883051 0.4089769 0.8830174 0.9404673
> set.seed(123)
> runif(5)
[1] 0.2875775 0.7883051 0.4089769 0.8830174 0.9404673
> set.seed(123)
> sample(5)
[1] 3 2 5 4 1
> set.seed(123)
> sample(5)
[1] 3 2 5 4 1
Use DATE()
function:
select * from follow_queue group by DATE(follow_date)
Let's call keys
the list/iterator of keys that you are given to remove. I'd do this:
keys_to_remove = set(keys).intersection(set(mydict.keys()))
for key in keys_to_remove:
del mydict[key]
You calculate up front all the affected items and operate on them.
I prefer to create a new dictionary over mutating an existing one, so I would probably also consider this:
keys_to_keep = set(mydict.keys()) - set(keys)
new_dict = {k: v for k, v in mydict.iteritems() if k in keys_to_keep}
or:
keys_to_keep = set(mydict.keys()) - set(keys)
new_dict = {k: mydict[k] for k in keys_to_keep}
You can use stri_paste
function with collapse
parameter from stringi
package like this:
stri_paste(letters, collapse='')
## [1] "abcdefghijklmnopqrstuvwxyz"
And some benchmarks:
require(microbenchmark)
test <- stri_rand_lipsum(100)
microbenchmark(stri_paste(test, collapse=''), paste(test,collapse=''), do.call(paste, c(as.list(test), sep="")))
Unit: microseconds
expr min lq mean median uq max neval
stri_paste(test, collapse = "") 137.477 139.6040 155.8157 148.5810 163.5375 226.171 100
paste(test, collapse = "") 404.139 406.4100 446.0270 432.3250 442.9825 723.793 100
do.call(paste, c(as.list(test), sep = "")) 216.937 226.0265 251.6779 237.3945 264.8935 405.989 100
Not really, in the standard. Some implementations have a nonstandard itoa() function, and you could look up Boost's lexical_cast, but if you stick to the standard it's pretty much a choice between stringstream and sprintf() (snprintf() if you've got it).
The method described in the accepted answer didn't work for me even after applying changes mentioned in its comments. But the below simple code worked:
import matplotlib.pyplot as plt
plt.imsave(filename, np_array, cmap='Greys')
np_array could be either a 2D array with values from 0..1 floats o2 0..255 uint8, and in that case it needs cmap. For 3D arrays, cmap will be ignored.
For linux Ubuntu Open Terminal and Write :-
keytool -list -v -keystore ~/.android/debug.keystore -alias androiddebugkey -storepass android -keypass android
For fedora26 and postgres9.6
First, log as user root then enter to psql by the following commands
$ su postgres
then
$ psql
in psql
find location of hba_file ==> means pg_hba.conf
postgres=# show hba_file ;
hba_file
--------------------------------------
/etc/postgresql/9.6/main/pg_hba.conf
(1 row)
in file pg_hba.conf
change user access to this
host all all 127.0.0.1/32 md5
It looks like you just hard-coded the row and column; otherwise, a couple of small tweaks, and I think you're there:
Dim sh As Worksheet
Dim rw As Range
Dim RowCount As Integer
RowCount = 0
Set sh = ActiveSheet
For Each rw In sh.Rows
If sh.Cells(rw.Row, 1).Value = "" Then
Exit For
End If
RowCount = RowCount + 1
Next rw
MsgBox (RowCount)
I strongly recommend you to use virtual environments for python package installation. With virtualenv, you prevent any package conflict and total isolation from your python related userland commands.
To delete all your package follow this;
It's possible to uninstall packages installed with --user
flag. This one worked for me;
pip freeze --user | xargs pip uninstall -y
For python 3;
pip3 freeze --user | xargs pip3 uninstall -y
But somehow these commands don't uninstall setuptools and pip. After those commands (if you really want clean python) you may delete them with;
pip uninstall setuptools && pip uninstall pip
Working Concept :
if (isset($_POST['submit'])) {
$mailto = $_POST["mailTo"];
$from_mail = $_POST["fromEmail"];
$replyto = $_POST["fromEmail"];
$from_name = $_POST["fromName"];
$message = $_POST["message"];
$subject = $_POST["subject"];
$filename = $_FILES["fileAttach"]["name"];
$content = chunk_split(base64_encode(file_get_contents($_FILES["fileAttach"]["tmp_name"])));
$uid = md5(uniqid(time()));
$name = basename($file);
$header = "From: " . $from_name . " <" . $from_mail . ">\r\n";
$header .= "Reply-To: " . $replyto . "\r\n";
$header .= "MIME-Version: 1.0\r\n";
$header .= "Content-Type: multipart/mixed; boundary=\"" . $uid . "\"\r\n\r\n";
$header .= "This is a multi-part message in MIME format.\r\n";
$header .= "--" . $uid . "\r\n";
// You add html "Content-type: text/html; charset=utf-8\n" or for Text "Content-type:text/plain; charset=iso-8859-1\r\n" by I.khan
$header .= "Content-type:text/html; charset=utf-8\n";
$header .= "Content-Transfer-Encoding: 7bit\r\n\r\n";
// User Message you can add HTML if You Selected HTML content
$header .= "<div style='color: red'>" . $message . "</div>\r\n\r\n";
$header .= "--" . $uid . "\r\n";
$header .= "Content-Type: application/octet-stream; name=\"" . $filename . "\"\r\n"; // use different content types here
$header .= "Content-Transfer-Encoding: base64\r\n";
$header .= "Content-Disposition: attachment; filename=\"" . $filename . "\"\r\n\r\n"; // For Attachment
$header .= $content . "\r\n\r\n";
$header .= "--" . $uid . "--";
if (mail($mailto, $subject, "", $header)) {
echo "<script>alert('Success');</script>"; // or use booleans here
} else {
echo "<script>alert('Failed');</script>";
}
}
It's because the iterable is
(x > 0 for x in list)
Note that x > 0
returns either True
or False
and thus you have an iterable of booleans.
Under the Tools menu in Visual Studio 2008 (or 2005 if you have the right WCF stuff installed) there is an options called 'WCF Service Configuration Editor'.
From there you can change the binding options for both the client and the services, one of these options will be for time-outs.
First store that element in object, let's say element
and then write following code to click on that hidden element:
JavascriptExecutor js = (JavascriptExecutor)driver;
js.executeScript("arguments[0].click();", element);
With the step attribute specified to the precision of the decimals you want, and the lang attribute [which is set to a locale that formats decimals with period], your html5 numeric input will accept decimals. eg. to take values like 10.56; i mean 2 decimal place numbers, do this:
<input type="number" step="0.01" min="0" lang="en" value="1.99">
You can further specify the max attribute for the maximum allowable value.
Edit Add a lang attribute to the input element with a locale value that formats decimals with point instead of comma
As an extension to @VinaySajip answer. There are additional nargs
worth mentioning.
parser.add_argument('dir', nargs=1, default=os.getcwd())
N (an integer). N arguments from the command line will be gathered together into a list
parser.add_argument('dir', nargs='*', default=os.getcwd())
'*'. All command-line arguments present are gathered into a list. Note that it generally doesn't make much sense to have more than one positional argument with nargs='*'
, but multiple optional arguments with nargs='*'
is possible.
parser.add_argument('dir', nargs='+', default=os.getcwd())
'+'. Just like '*', all command-line args present are gathered into a list. Additionally, an error message will be generated if there wasn’t at least one command-line argument present.
parser.add_argument('dir', nargs=argparse.REMAINDER, default=os.getcwd())
argparse.REMAINDER
. All the remaining command-line arguments are gathered into a list. This is commonly useful for command line utilities that dispatch to other command line utilities
If the nargs
keyword argument is not provided, the number of arguments consumed is determined by the action. Generally this means a single command-line argument will be consumed and a single item (not a list) will be produced.
Edit (copied from a comment by @Acumenus) nargs='?'
The docs say: '?'. One argument will be consumed from the command line if possible and produced as a single item. If no command-line argument is present, the value from default will be produced.
Do you mean that you want to center it vertically or horizontally? You said you specified the height
to 800 pixels, and wanted the div not to stretch when the width
was greater than that...
To center horizontally, you can use the margin: auto;
attribute in CSS. Also, you'll have to make sure that the body
and html
elements don't have any margin or padding:
html, body { margin: 0; padding: 0; }
#centeredDiv { margin-right: auto; margin-left: auto; width: 800px; }
I only use MicrosoftAdvertising.Mobile and Microsoft.Advertising.Mobile.UI and I am served ads. The SDK should only add the DLLs not reference itself.
Note: You need to explicitly set width and height Make sure the phone dialer, and web browser capabilities are enabled
Followup note: Make sure that after you've removed the SDK DLL, that the xmlns references are not still pointing to it. The best route to take here is
Here is the xmlns reference:
xmlns:AdNamepace="clr-namespace:Microsoft.Advertising.Mobile.UI;assembly=Microsoft.Advertising.Mobile.UI"
Then the ad itself:
<AdNamespace:AdControl x:Name="myAd" Height="80" Width="480" AdUnitId="yourAdUnitIdHere" ApplicationId="yourIdHere"/>
If you have other parameters in the query, beyond the IN list, then the following extension to JG's answer may be useful.
ids = [1, 5, 7, 213]
sql = "select * from person where type=%s and id in (%s)"
in_ids = ', '.join(map(lambda x: '%s', ids))
sql = sql % ('%s', in_ids)
params = []
params.append(type)
params.extend(ids)
cursor.execute(sql, tuple(params))
That is, join all the params in a linear array, then pass it as a tuple to the execute method.
Actually, jQuery has a built in trim function:
var emailAdd = jQuery.trim($(this).text());
See here for details.
Updating node helped me, whether that be from the command line or just re-downloading it from the web
I was creating a JSON-LD to create a site review script.
**DECLARE @json VARCHAR(MAX);**
The actual JSON is about 94K.
I got this to work by using the CAST('' AS VARCHAR(MAX)) + @json, as explained by other contributors:-
so **SET @json = CAST('' AS VARCHAR(MAX)) + (SELECT .....**
2/ I also had to change the Query Options:- Query Options -> 'results' -> 'grid' -> 'Maximum Characters received' -> 'non-XML Data' SET to 2000000. (I left the 'results' -> 'text' -> 'Maximum number of characters displayed in each column' as the default)
All answers say "YES" but that also depend of the project, the doc says:
One key detail about package-lock.json is that it cannot be published, and it will be ignored if found in any place other than the toplevel package.
This mean that you don't need to publish on npm your package-lock.json
for dependency but you need to use package-lock.json
in your repo to lock the version of your test dependency, build dependencies…
However, If your are using lerna for managing projects with multiple packages, you should put the package.json
only on the root of your repo, not in each subpackage are created with npm init
. You will get something like that :
.git
lerna.json
package.json
package-lock.json <--- here
packages/a/package.json
packages/a/lib/index.js
packages/b/package.json
packages/b/lib/index.js
In short, yes. But there are times when you might favor one vs. the other. Google "case switch vs. if else". There are some discussions already on SO too. Also, here is a good video that talks about it in the context of MATLAB:
http://blogs.mathworks.com/pick/2008/01/02/matlab-basics-switch-case-vs-if-elseif/
Personally, when I have 3 or more cases, I usually just go with case/switch.
What I do when I mess up my local branch is I just rename my broken branch, and check out/branch the upstream branch again:
git branch -m branch branch-old
git fetch remote
git checkout -b branch remote/branch
Then if you're sure you don't want anything from your old branch, remove it:
git branch -D branch-old
But usually I leave the old branch around locally, just in case I had something in there.
SelectedText is to get or set the actual text in the string editor for the selected item in the combobox as documented here . This goes uneditable if you set:
comboBox1.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
Use:
comboBox1.SelectedItem = "test1";
or:
comboBox1.SelectedIndex = comboBox1.Items.IndexOf("test1");
something like below
var idList=new int[]{1, 2, 3, 4};
using (var db=new SomeDatabaseContext())
{
var friends= db.Friends.Where(f=>idList.Contains(f.ID)).ToList();
friends.ForEach(a=>a.msgSentBy='1234');
db.SaveChanges();
}
you can update multiple fields as below
friends.ForEach(a =>
{
a.property1 = value1;
a.property2 = value2;
});
Further reading for any of the topics here: The Definitive Guide to Linux System Calls
I verified these using GNU Assembler (gas) on Linux.
x86-32 aka i386 Linux System Call convention:
In x86-32 parameters for Linux system call are passed using registers. %eax
for syscall_number. %ebx, %ecx, %edx, %esi, %edi, %ebp are used for passing 6 parameters to system calls.
The return value is in %eax
. All other registers (including EFLAGS) are preserved across the int $0x80
.
I took following snippet from the Linux Assembly Tutorial but I'm doubtful about this. If any one can show an example, it would be great.
If there are more than six arguments,
%ebx
must contain the memory location where the list of arguments is stored - but don't worry about this because it's unlikely that you'll use a syscall with more than six arguments.
For an example and a little more reading, refer to http://www.int80h.org/bsdasm/#alternate-calling-convention. Another example of a Hello World for i386 Linux using int 0x80
: Hello, world in assembly language with Linux system calls?
There is a faster way to make 32-bit system calls: using sysenter
. The kernel maps a page of memory into every process (the vDSO), with the user-space side of the sysenter
dance, which has to cooperate with the kernel for it to be able to find the return address. Arg to register mapping is the same as for int $0x80
. You should normally call into the vDSO instead of using sysenter
directly. (See The Definitive Guide to Linux System Calls for info on linking and calling into the vDSO, and for more info on sysenter
, and everything else to do with system calls.)
x86-32 [Free|Open|Net|DragonFly]BSD UNIX System Call convention:
Parameters are passed on the stack. Push the parameters (last parameter pushed first) on to the stack. Then push an additional 32-bit of dummy data (Its not actually dummy data. refer to following link for more info) and then give a system call instruction int $0x80
http://www.int80h.org/bsdasm/#default-calling-convention
(Note: x86-64 Mac OS X is similar but different from Linux. TODO: check what *BSD does)
Refer to section: "A.2 AMD64 Linux Kernel Conventions" of System V Application Binary Interface AMD64 Architecture Processor Supplement. The latest versions of the i386 and x86-64 System V psABIs can be found linked from this page in the ABI maintainer's repo. (See also the x86 tag wiki for up-to-date ABI links and lots of other good stuff about x86 asm.)
Here is the snippet from this section:
- User-level applications use as integer registers for passing the sequence %rdi, %rsi, %rdx, %rcx, %r8 and %r9. The kernel interface uses %rdi, %rsi, %rdx, %r10, %r8 and %r9.
- A system-call is done via the
syscall
instruction. This clobbers %rcx and %r11 as well as the %rax return value, but other registers are preserved.- The number of the syscall has to be passed in register %rax.
- System-calls are limited to six arguments, no argument is passed directly on the stack.
- Returning from the syscall, register %rax contains the result of the system-call. A value in the range between -4095 and -1 indicates an error, it is
-errno
.- Only values of class INTEGER or class MEMORY are passed to the kernel.
Remember this is from the Linux-specific appendix to the ABI, and even for Linux it's informative not normative. (But it is in fact accurate.)
This 32-bit int $0x80
ABI is usable in 64-bit code (but highly not recommended). What happens if you use the 32-bit int 0x80 Linux ABI in 64-bit code? It still truncates its inputs to 32-bit, so it's unsuitable for pointers, and it zeros r8-r11.
x86-32 Function Calling convention:
In x86-32 parameters were passed on stack. Last parameter was pushed first on to the stack until all parameters are done and then call
instruction was executed. This is used for calling C library (libc) functions on Linux from assembly.
Modern versions of the i386 System V ABI (used on Linux) require 16-byte alignment of %esp
before a call
, like the x86-64 System V ABI has always required. Callees are allowed to assume that and use SSE 16-byte loads/stores that fault on unaligned. But historically, Linux only required 4-byte stack alignment, so it took extra work to reserve naturally-aligned space even for an 8-byte double
or something.
Some other modern 32-bit systems still don't require more than 4 byte stack alignment.
x86-64 System V passes args in registers, which is more efficient than i386 System V's stack args convention. It avoids the latency and extra instructions of storing args to memory (cache) and then loading them back again in the callee. This works well because there are more registers available, and is better for modern high-performance CPUs where latency and out-of-order execution matter. (The i386 ABI is very old).
In this new mechanism: First the parameters are divided into classes. The class of each parameter determines the manner in which it is passed to the called function.
For complete information refer to : "3.2 Function Calling Sequence" of System V Application Binary Interface AMD64 Architecture Processor Supplement which reads, in part:
Once arguments are classified, the registers get assigned (in left-to-right order) for passing as follows:
- If the class is MEMORY, pass the argument on the stack.
- If the class is INTEGER, the next available register of the sequence %rdi, %rsi, %rdx, %rcx, %r8 and %r9 is used
So %rdi, %rsi, %rdx, %rcx, %r8 and %r9
are the registers in order used to pass integer/pointer (i.e. INTEGER class) parameters to any libc function from assembly. %rdi is used for the first INTEGER parameter. %rsi for 2nd, %rdx for 3rd and so on. Then call
instruction should be given. The stack (%rsp
) must be 16B-aligned when call
executes.
If there are more than 6 INTEGER parameters, the 7th INTEGER parameter and later are passed on the stack. (Caller pops, same as x86-32.)
The first 8 floating point args are passed in %xmm0-7, later on the stack. There are no call-preserved vector registers. (A function with a mix of FP and integer arguments can have more than 8 total register arguments.)
Variadic functions (like printf
) always need %al
= the number of FP register args.
There are rules for when to pack structs into registers (rdx:rax
on return) vs. in memory. See the ABI for details, and check compiler output to make sure your code agrees with compilers about how something should be passed/returned.
Note that the Windows x64 function calling convention has multiple significant differences from x86-64 System V, like shadow space that must be reserved by the caller (instead of a red-zone), and call-preserved xmm6-xmm15. And very different rules for which arg goes in which register.
Others are correct in saying that setting button.enabled = false
doesn't prevent the button from triggering. However, I found that setting button.visible = false
does work. The button disappears and can't be clicked until you set visible
to true
again.
just posting in case anyone else has the same error...
I was using 'await' outside of an 'async' function and for whatever reason that results in a 'missing ) after argument list' error.
The solution was to make the function asynchronous
function functionName(args) {}
becomes
async function functionName(args) {}
This is suppose to be the safest and error pron query :
public void Load_Data()
{
using (SqlConnection connection = new SqlConnection(DatabaseServices.connectionString)) //use your connection string here
{
var bindingSource = new BindingSource();
string fetachSlidesRecentSQL = "select top (50) * from dbo.slides order by created_date desc";
using (SqlDataAdapter dataAdapter = new SqlDataAdapter(fetachSlidesRecentSQL, connection))
{
try
{
SqlCommandBuilder commandBuilder = new SqlCommandBuilder(dataAdapter);
DataTable table = new DataTable();
dataAdapter.Fill(table);
bindingSource.DataSource = table;
recent_slides_grd_view.ReadOnly = true;
recent_slides_grd_view.DataSource = bindingSource;
}
catch (SqlException ex)
{
MessageBox.Show(ex.Message.ToString(), "ERROR Loading");
}
finally
{
connection.Close();
}
}
}
}
You have about 98% right. The only issue is that you're trying to print out an String[] which does not print the way you'd like. Instead try this...
for (String[] s : myEntries) {
System.out.print("Next item: " + s[0]);
for(int i = 1; i < s.length; i++) {
System.out.print(", " + s[i]);
}
System.out.println("");
}
This way you're accessing each string in the array instead of the array itself.
Hope this helps!
lvalue
means "left value" -- it should be assignable. You cannot change the value of text
since it is an array, not a pointer.
Either declare it as char pointer (in this case it's better to declare it as const char*
):
const char *text;
if(number == 2)
text = "awesome";
else
text = "you fail";
Or use strcpy:
char text[60];
if(number == 2)
strcpy(text, "awesome");
else
strcpy(text, "you fail");
On Mac: /Library/PostgreSQL/9.0/data/base
The directory can't be entered, but you can look at the content via: sudo du -hc data
Each tablespace has one or more datafiles that it uses to store data.
The max size of a datafile depends on the block size of the database. I believe that, by default, that leaves with you with a max of 32gb per datafile.
To find out if the actual limit is 32gb, run the following:
select value from v$parameter where name = 'db_block_size';
Compare the result you get with the first column below, and that will indicate what your max datafile size is.
I have Oracle Personal Edition 11g r2 and in a default install it had an 8,192 block size (32gb per data file).
Block Sz Max Datafile Sz (Gb) Max DB Sz (Tb)
-------- -------------------- --------------
2,048 8,192 524,264
4,096 16,384 1,048,528
8,192 32,768 2,097,056
16,384 65,536 4,194,112
32,768 131,072 8,388,224
You can run this query to find what datafiles you have, what tablespaces they are associated with, and what you've currrently set the max file size to (which cannot exceed the aforementioned 32gb):
select bytes/1024/1024 as mb_size,
maxbytes/1024/1024 as maxsize_set,
x.*
from dba_data_files x
MAXSIZE_SET is the maximum size you've set the datafile to. Also relevant is whether you've set the AUTOEXTEND option to ON (its name does what it implies).
If your datafile has a low max size or autoextend is not on you could simply run:
alter database datafile 'path_to_your_file\that_file.DBF' autoextend on maxsize unlimited;
However if its size is at/near 32gb an autoextend is on, then yes, you do need another datafile for the tablespace:
alter tablespace system add datafile 'path_to_your_datafiles_folder\name_of_df_you_want.dbf' size 10m autoextend on maxsize unlimited;
public static string TruncateLongString(this string str, int maxLength)
{
if (string.IsNullOrEmpty(str)) return str;
return str.Substring(0, Math.Min(str.Length, maxLength));
}
filter_var($string, FILTER_VALIDATE_BOOLEAN, FILTER_NULL_ON_FAILURE);
$string = 1; // true
$string ='1'; // true
$string = 'true'; // true
$string = 'trUe'; // true
$string = 'TRUE'; // true
$string = 0; // false
$string = '0'; // false
$string = 'false'; // false
$string = 'False'; // false
$string = 'FALSE'; // false
$string = 'sgffgfdg'; // null
You must specify
FILTER_NULL_ON_FAILUREotherwise you'll get always false even if $string contains something else.
You can give simply hide this by giving a boolean parameter----->
debugShowCheckedModeBanner: false,
void main() {
Bloc.observer = SimpleBlocDelegate();
runApp(MyApp());
}
class MyApp extends StatelessWidget {
// This widget is the root of your application.
@override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
title: 'Prescription Writing Software',
theme: ThemeData(
primarySwatch: Colors.blue,
scaffoldBackgroundColor: Colors.white,
visualDensity: VisualDensity.adaptivePlatformDensity,
),
home: SplashScreen(),
);
}
}
preg_replace("/[[:blank:]]+/"," ",$input)
I had a problem where IntelliJ was unable to compile classes, claiming that dependencies between projects were missing. Reimporting the project as suggested in the answers of this question didn't solve the problem. The solution for me, was:
WARNING: on some projects, you might have to increment max memory for maven import (maven settings on maven tab / Importing / VM options for importer).
Ana alternative Solution for RSolgberg, which fires the 'onchange'
event if present:
$("#target").val($("#target option:first").val());
Transient :
First need to know where it needed how it bridge the gap.
1) An Access modifier transient is only applicable to variable component only. It will not used with method or class.
2) Transient keyword cannot be used along with static keyword.
3) What is serialization and where it is used? Serialization is the process of making the object's state persistent. That means the state of the object is converted into a stream of bytes to be used for persisting (e.g. storing bytes in a file) or transferring (e.g. sending bytes across a network). In the same way, we can use the deserialization to bring back the object's state from bytes. This is one of the important concepts in Java programming because serialization is mostly used in networking programming. The objects that need to be transmitted through the network have to be converted into bytes. Before understanding the transient keyword, one has to understand the concept of serialization. If the reader knows about serialization, please skip the first point.
Note 1) Transient is mainly use for serialzation process. For that the class must implement the java.io.Serializable interface. All of the fields in the class must be serializable. If a field is not serializable, it must be marked transient.
Note 2) When deserialized process taken place they get set to the default value - zero, false, or null as per type constraint.
Note 3) Transient keyword and its purpose? A field which is declare with transient modifier it will not take part in serialized process. When an object is serialized(saved in any state), the values of its transient fields are ignored in the serial representation, while the field other than transient fields will take part in serialization process. That is the main purpose of the transient keyword.
typedef
is a language construct that associates a name to a type.
You use it the same way you would use the original type, for instance
typedef int myinteger;
typedef char *mystring;
typedef void (*myfunc)();
using them like
myinteger i; // is equivalent to int i;
mystring s; // is the same as char *s;
myfunc f; // compile equally as void (*f)();
As you can see, you could just replace the typedefed name with its definition given above.
The difficulty lies in the pointer to functions syntax and readability in C and C++, and the typedef
can improve the readability of such declarations. However, the syntax is appropriate, since functions - unlike other simpler types - may have a return value and parameters, thus the sometimes lengthy and complex declaration of a pointer to function.
The readability may start to be really tricky with pointers to functions arrays, and some other even more indirect flavors.
To answer your three questions
Why is typedef used? To ease the reading of the code - especially for pointers to functions, or structure names.
The syntax looks odd (in the pointer to function declaration)
That syntax is not obvious to read, at least when beginning. Using a typedef
declaration instead eases the reading
Is a function pointer created to store the memory address of a function?
Yes, a function pointer stores the address of a function. This has nothing to do with the typedef
construct which only ease the writing/reading of a program ; the compiler just expands the typedef definition before compiling the actual code.
Example:
typedef int (*t_somefunc)(int,int);
int product(int u, int v) {
return u*v;
}
t_somefunc afunc = &product;
...
int x2 = (*afunc)(123, 456); // call product() to calculate 123*456
I wrote this function it does just the right thing. Interpolate a word starting with $
with the value of the variable of the same name.
private static String interpol1(String x){
Field[] ffield = Main.class.getDeclaredFields();
String[] test = x.split(" ") ;
for (String v : test ) {
for ( Field n: ffield ) {
if(v.startsWith("$") && ( n.getName().equals(v.substring(1)) )){
try {
x = x.replace("$" + v.substring(1), String.valueOf( n.get(null)));
}catch (Exception e){
System.out.println("");
}
}
}
}
return x;
}
Here's an algorithm that returns a unique readable filename based on the original supplied. If the original file exists, it incrementally tries to append an index to the filename until it finds one that doesn't exist. It reads the existing filenames into a HashSet to check for collisions so it's pretty quick (a few hundred filenames per second on my machine), it's thread safe too, and doesn't suffer from race conditions.
For example, if you pass it test.txt
, it will attempt to create files in this order:
test.txt
test (2).txt
test (3).txt
etc. You can specify the maximum attempts or just leave it at the default.
Here's a complete example:
class Program
{
static FileStream CreateFileWithUniqueName(string folder, string fileName,
int maxAttempts = 1024)
{
// get filename base and extension
var fileBase = Path.GetFileNameWithoutExtension(fileName);
var ext = Path.GetExtension(fileName);
// build hash set of filenames for performance
var files = new HashSet<string>(Directory.GetFiles(folder));
for (var index = 0; index < maxAttempts; index++)
{
// first try with the original filename, else try incrementally adding an index
var name = (index == 0)
? fileName
: String.Format("{0} ({1}){2}", fileBase, index, ext);
// check if exists
var fullPath = Path.Combine(folder, name);
if(files.Contains(fullPath))
continue;
// try to create the file
try
{
return new FileStream(fullPath, FileMode.CreateNew, FileAccess.Write);
}
catch (DirectoryNotFoundException) { throw; }
catch (DriveNotFoundException) { throw; }
catch (IOException)
{
// Will occur if another thread created a file with this
// name since we created the HashSet. Ignore this and just
// try with the next filename.
}
}
throw new Exception("Could not create unique filename in " + maxAttempts + " attempts");
}
static void Main(string[] args)
{
for (var i = 0; i < 500; i++)
{
using (var stream = CreateFileWithUniqueName(@"c:\temp\", "test.txt"))
{
Console.WriteLine("Created \"" + stream.Name + "\"");
}
}
Console.ReadKey();
}
}
The url portion of a request (GET and POST) can be limited by both the browser and the server - generally the safe size is 2KB as there are almost no browsers or servers that use a smaller limit.
The body of a request (POST) is normally* limited by the server on a byte size basis in order to prevent a type of DoS attack (note that this means character escaping can increase the byte size of the body). The most common server setting is 10MB, though all popular servers allow this to be increased or decreased via a setting file or panel.
*Some exceptions exist with older cell phone or other small device browsers - in those cases it is more a function of heap space reserved for this purpose on the device then anything else.
Meteor is a framework built ontop of node.js. It uses node.js to deploy but has several differences.
The key being it uses its own packaging system instead of node's module based system. It makes it easy to make web applications using Node. Node can be used for a variety of things and on its own is terrible at serving up dynamic web content. Meteor's libraries make all of this easy.
You're going to need DATEPART here. You can concatenate the results of the DATEPART calls together.
To get the month abbreviations, you might be able to use DATENAME; if that doesn't work for you, you can use a CASE statement on the DATEPART.
DATEPART also works for the time field.
I can think of a couple of ways of getting the AM/PM indicator, including comparing new dates built via DATEPART or calculating the total seconds elapsed in the day and comparing that to known AM/PM thresholds.
Check out Apache Commons FileUtils (listFiles, iterateFiles, etc.). Nice convenience methods for doing what you want and also applying filters.
http://commons.apache.org/io/api-1.4/org/apache/commons/io/FileUtils.html
I would do this slightly different by applying both the UNPIVOT
and the PIVOT
functions to get the final result. The unpivot takes the values from both the totalcount
and totalamount
columns and places them into one column with multiple rows. You can then pivot on those results.:
select chardate,
Australia_totalcount as [Australia # of Transactions],
Australia_totalamount as [Australia Total $ Amount],
Austria_totalcount as [Austria # of Transactions],
Austria_totalamount as [Austria Total $ Amount]
from
(
select
numericmonth,
chardate,
country +'_'+col col,
value
from
(
select numericmonth,
country,
chardate,
cast(totalcount as numeric(10, 2)) totalcount,
cast(totalamount as numeric(10, 2)) totalamount
from mytransactions
) src
unpivot
(
value
for col in (totalcount, totalamount)
) unpiv
) s
pivot
(
sum(value)
for col in (Australia_totalcount, Australia_totalamount,
Austria_totalcount, Austria_totalamount)
) piv
order by numericmonth
See SQL Fiddle with Demo.
If you have an unknown number of country
names, then you can use dynamic SQL:
DECLARE @cols AS NVARCHAR(MAX),
@colsName AS NVARCHAR(MAX),
@query AS NVARCHAR(MAX)
select @cols = STUFF((SELECT distinct ',' + QUOTENAME(country +'_'+c.col)
from mytransactions
cross apply
(
select 'TotalCount' col
union all
select 'TotalAmount'
) c
FOR XML PATH(''), TYPE
).value('.', 'NVARCHAR(MAX)')
,1,1,'')
select @colsName
= STUFF((SELECT distinct ', ' + QUOTENAME(country +'_'+c.col)
+' as ['
+ country + case when c.col = 'TotalCount' then ' # of Transactions]' else 'Total $ Amount]' end
from mytransactions
cross apply
(
select 'TotalCount' col
union all
select 'TotalAmount'
) c
FOR XML PATH(''), TYPE
).value('.', 'NVARCHAR(MAX)')
,1,1,'')
set @query
= 'SELECT chardate, ' + @colsName + '
from
(
select
numericmonth,
chardate,
country +''_''+col col,
value
from
(
select numericmonth,
country,
chardate,
cast(totalcount as numeric(10, 2)) totalcount,
cast(totalamount as numeric(10, 2)) totalamount
from mytransactions
) src
unpivot
(
value
for col in (totalcount, totalamount)
) unpiv
) s
pivot
(
sum(value)
for col in (' + @cols + ')
) p
order by numericmonth'
execute(@query)
Both give the result:
| CHARDATE | AUSTRALIA # OF TRANSACTIONS | AUSTRALIA TOTAL $ AMOUNT | AUSTRIA # OF TRANSACTIONS | AUSTRIA TOTAL $ AMOUNT |
--------------------------------------------------------------------------------------------------------------------------------------
| Jul-12 | 36 | 699.96 | 11 | 257.82 |
| Aug-12 | 44 | 1368.71 | 5 | 126.55 |
| Sep-12 | 52 | 1161.33 | 7 | 92.11 |
| Oct-12 | 50 | 1099.84 | 12 | 103.56 |
| Nov-12 | 38 | 1078.94 | 21 | 377.68 |
| Dec-12 | 63 | 1668.23 | 3 | 14.35 |
Extending @Def_Os's answer with an actual demo...
As @Def_Os has already said - using Pandas Datareader makes this task a real fun
In [12]: from pandas_datareader import data
pulling all available historical data for AAPL
starting from 1980-01-01
#In [13]: aapl = data.DataReader('AAPL', 'yahoo', '1980-01-01')
# yahoo api is inconsistent for getting historical data, please use google instead.
In [13]: aapl = data.DataReader('AAPL', 'google', '1980-01-01')
first 5 rows
In [14]: aapl.head()
Out[14]:
Open High Low Close Volume Adj Close
Date
1980-12-12 28.750000 28.875000 28.750 28.750 117258400 0.431358
1980-12-15 27.375001 27.375001 27.250 27.250 43971200 0.408852
1980-12-16 25.375000 25.375000 25.250 25.250 26432000 0.378845
1980-12-17 25.875000 25.999999 25.875 25.875 21610400 0.388222
1980-12-18 26.625000 26.750000 26.625 26.625 18362400 0.399475
last 5 rows
In [15]: aapl.tail()
Out[15]:
Open High Low Close Volume Adj Close
Date
2016-06-07 99.250000 99.870003 98.959999 99.029999 22366400 99.029999
2016-06-08 99.019997 99.559998 98.680000 98.940002 20812700 98.940002
2016-06-09 98.500000 99.989998 98.459999 99.650002 26419600 99.650002
2016-06-10 98.529999 99.349998 98.480003 98.830002 31462100 98.830002
2016-06-13 98.690002 99.120003 97.099998 97.339996 37612900 97.339996
save all data as CSV file
In [16]: aapl.to_csv('d:/temp/aapl_data.csv')
d:/temp/aapl_data.csv - 5 first rows
Date,Open,High,Low,Close,Volume,Adj Close
1980-12-12,28.75,28.875,28.75,28.75,117258400,0.431358
1980-12-15,27.375001,27.375001,27.25,27.25,43971200,0.408852
1980-12-16,25.375,25.375,25.25,25.25,26432000,0.378845
1980-12-17,25.875,25.999999,25.875,25.875,21610400,0.38822199999999996
1980-12-18,26.625,26.75,26.625,26.625,18362400,0.399475
...
string HexFromID(int ID)
{
return ID.ToString("X");
}
int IDFromHex(string HexID)
{
return int.Parse(HexID, System.Globalization.NumberStyles.HexNumber);
}
I really question the value of this, though. You're stated goal is to make the value shorter, which it will, but that isn't a goal in itself. You really mean either make it easier to remember or easier to type.
If you mean easier to remember, then you're taking a step backwards. We know it's still the same size, just encoded differently. But your users won't know that the letters are restricted to 'A-F', and so the ID will occupy the same conceptual space for them as if the letter 'A-Z' were allowed. So instead of being like memorizing a telephone number, it's more like memorizing a GUID (of equivalent length).
If you mean typing, instead of being able to use the keypad the user now must use the main part of the keyboard. It's likely to be more difficult to type, because it won't be a word their fingers recognize.
A much better option is to actually let them pick a real username.
Try this,
this.props.router.push('/foo')
warning works for versions prior to v4
and
this.props.history.push('/foo')
for v4 and above
A daemon is just a process in the background. If you want to start your program when the OS boots, on linux, you add your start command to /etc/rc.d/rc.local (run after all other scripts) or /etc/startup.sh
On windows, you make a service, register the service, and then set it to start automatically at boot in administration -> services panel.
This is an old thread, but I have just encountered this situation and discovered a neat way around it. I was trying to run a setup.exe, but the focus was returning to the next line of the script without waiting for the setup.exe to finish. I tried the above solutions with no luck.
In the end, piping the command through more did the trick.
setup.exe {arguments} | more
I recommend that you use REQUERY
the specific combo box whose data you have changed AND that you do it after the Cmd.Close
statement. that way, if you were inputing data, that data is also requeried.
DoCmd.Close
Forms![Form_Name]![Combo_Box_Name].Requery
you might also want to point to the recently changed value
Dim id As Integer
id = Me.[Index_Field]
DoCmd.Close
Forms![Form_Name]![Combo_Box_Name].Requery
Forms![Form_Name]![Combo_Box_Name] = id
this example supposes that you opened a form to input data into a secondary table.
let us say you save School_Index and School_Name in a School table and refer to it in a Student table (which contains only the School_Index field). while you are editing a student, you need to associate him with a school that is not in your School table, etc etc
Make sure nodejs in the PATH is in front of anything that uses node.
.close-image {
cursor: pointer;
display: block;
float: right;
position: relative;
top: 22px;
z-index: 1;
}
I think this might be what you are looking for.
Like the following. It will make the user database owner.
EXEC sp_addrolemember N'db_owner', N'USerNAme'
I am happy that browsers care to save us from intrusive scripts and the like. I am not happy with IE putting something into the browser that makes a simple style-fix look like a hack-attack!
I've used a < span > to represent the file-input so that I could apply appropriate styling to the < div > instead of the < input > (once again, because of IE). Now due to this IE want's to show the User a path with a value that's just guaranteed to put them on guard and in the very least apprehensive (if not totally scare them off?!)... MORE IE-CRAP!
Anyhow, thanks to to those who posted the explanation here: IE Browser Security: Appending "fakepath" to file path in input[type="file"], I've put together a minor fixer-upper...
The code below does two things - it fixes a lte IE8 bug where the onChange event doesn't fire until the upload field's onBlur and it updates an element with a cleaned filepath that won't scare the User.
// self-calling lambda to for jQuery shorthand "$" namespace
(function($){
// document onReady wrapper
$().ready(function(){
// check for the nefarious IE
if($.browser.msie) {
// capture the file input fields
var fileInput = $('input[type="file"]');
// add presentational <span> tags "underneath" all file input fields for styling
fileInput.after(
$(document.createElement('span')).addClass('file-underlay')
);
// bind onClick to get the file-path and update the style <div>
fileInput.click(function(){
// need to capture $(this) because setTimeout() is on the
// Window keyword 'this' changes context in it
var fileContext = $(this);
// capture the timer as well as set setTimeout()
// we use setTimeout() because IE pauses timers when a file dialog opens
// in this manner we give ourselves a "pseudo-onChange" handler
var ieBugTimeout = setTimeout(function(){
// set vars
var filePath = fileContext.val(),
fileUnderlay = fileContext.siblings('.file-underlay');
// check for IE's lovely security speil
if(filePath.match(/fakepath/)) {
// update the file-path text using case-insensitive regex
filePath = filePath.replace(/C:\\fakepath\\/i, '');
}
// update the text in the file-underlay <span>
fileUnderlay.text(filePath);
// clear the timer var
clearTimeout(ieBugTimeout);
}, 10);
});
}
});
})(jQuery);
Do a row div.
Like this:
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.3/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-Zug+QiDoJOrZ5t4lssLdxGhVrurbmBWopoEl+M6BdEfwnCJZtKxi1KgxUyJq13dy" crossorigin="anonymous">_x000D_
<div class="grid">_x000D_
<div class="row">_x000D_
<div class="col-lg-3 col-md-3 col-sm-3 col-xs-12 bg-success">Under me should be a DIV</div>_x000D_
<div class="col-lg-6 col-md-6 col-sm-5 col-xs-12 bg-danger">Under me should be a DIV</div>_x000D_
</div>_x000D_
<div class="row">_x000D_
<div class="col-lg-3 col-md-3 col-sm-4 col-xs-12 bg-warning">I am the last DIV</div>_x000D_
</div>_x000D_
</div>
_x000D_
recyclerView.setLayoutManager(new LinearLayoutManager(this,LinearLayoutManager.HORIZONTAL,false));
recyclerView.setAdapter(adapter);
Are you looking for something like this?
COLUMN_NAMES=['A','B','C','D','E','F','G']
df = pd.DataFrame(columns=COLUMN_NAMES)
df.columns
Index(['A', 'B', 'C', 'D', 'E', 'F', 'G'], dtype='object')
this
is the current Object instance. Whenever you have a non-static method, it can only be called on an instance of your object.
To add UNIQUE constraint using phpmyadmin, go to the structure of that table and find below and click that,
To remove the UNIQUE constraint, same way, go to the structure and scroll down till Indexes Tab and find below and click drop,
Hope this works.
Enjoy ;)
@people = qw( bob john linda );
$n = @people; # the number 3
Print " le number in the list is $n \n";
Expressions in Perl always return the appropriate value for their context. For example, how about the “name” * of an array. In a list context, it gives the list of elements. But in a scalar context, it returns the number of elements in the array:
For my keyboard layout it's Ctrl + § for:
//
//
//
And Shift + Alt + A for:
/*
...
*/
Two answers:
Firstly, to delay in a batch file, simply without all the obtuse methods people have been proposing:
timeout /t <TimeoutInSeconds> [/nobreak]
http://technet.microsoft.com/en-us/library/cc754891.aspx
Secondly, worth mentioning that while it may not do exactly what you want, using the inbuilt Windows snipping tool, you can trigger a snip on it without using the mouse. Run the snipping tool, escape out of the current snip but leave the tool running, and hit Control + Print Screen when you want the snip to occur. This shouldn't interfere with whatever it is you're trying to snip.
public static Dictionary<string, DateTime> ListBucketsByCreationDate(string AccessKey, string SecretKey)
{
return AWSClientFactory.CreateAmazonS3Client(AccessKey,
SecretKey).ListBuckets().Buckets.ToDictionary(s3Bucket => s3Bucket.BucketName,
s3Bucket => DateTime.Parse(s3Bucket.CreationDate));
}
I would recommend,
load './tokenizer.rb'
Given, that you know the file is in the same working directory.
If you're trying to require it relative to the file, you can use
require_relative 'tokenizer'
I hope this helps.
I used numpy to generate the array, but list of lists array should work similarly.
import numpy as np
def printArray(args):
print "\t".join(args)
n = 10
Array = np.zeros(shape=(n,n)).astype('int')
for row in Array:
printArray([str(x) for x in row])
If you want to only print certain indices:
import numpy as np
def printArray(args):
print "\t".join(args)
n = 10
Array = np.zeros(shape=(n,n)).astype('int')
i_indices = [1,2,3]
j_indices = [2,3,4]
for i in i_indices:printArray([str(Array[i][j]) for j in j_indices])
If you add text-align: center
to the declarations for .columns-container
then they align centrally:
.columns-container {
display: table-cell;
height: 100%;
width:600px;
text-align: center;
}
/*************************_x000D_
* Sticky footer hack_x000D_
* Source: http://pixelsvsbytes.com/blog/2011/09/sticky-css-footers-the-flexible-way/_x000D_
************************/_x000D_
_x000D_
/* Stretching all container's parents to full height */_x000D_
_x000D_
html,_x000D_
body {_x000D_
height: 100%;_x000D_
margin: 0;_x000D_
padding: 0;_x000D_
}_x000D_
/* Setting the container to be a table with maximum width and height */_x000D_
_x000D_
#container {_x000D_
display: table;_x000D_
height: 100%;_x000D_
width: 100%;_x000D_
}_x000D_
/* All sections (container's children) should be table rows with minimal height */_x000D_
_x000D_
.section {_x000D_
display: table-row;_x000D_
height: 1px;_x000D_
}_x000D_
/* The last-but-one section should be stretched to automatic height */_x000D_
_x000D_
.section.expand {_x000D_
height: auto;_x000D_
}_x000D_
/*************************_x000D_
* Full height columns_x000D_
************************/_x000D_
_x000D_
/* We need one extra container, setting it to full width */_x000D_
_x000D_
.columns-container {_x000D_
display: table-cell;_x000D_
height: 100%;_x000D_
width:600px;_x000D_
text-align: center;_x000D_
}_x000D_
/* Creating columns */_x000D_
_x000D_
.column {_x000D_
/* The float:left won't work for Chrome for some reason, so inline-block */_x000D_
display: inline-block;_x000D_
/* for this to work, the .column elements should have NO SPACE BETWEEN THEM */_x000D_
vertical-align: top;_x000D_
height: 100%;_x000D_
width: 100px;_x000D_
}_x000D_
/****************************************************************_x000D_
* Just some coloring so that we're able to see height of columns_x000D_
****************************************************************/_x000D_
_x000D_
header {_x000D_
background-color: yellow;_x000D_
}_x000D_
#a {_x000D_
background-color: pink;_x000D_
}_x000D_
#b {_x000D_
background-color: lightgreen;_x000D_
}_x000D_
#c {_x000D_
background-color: lightblue;_x000D_
}_x000D_
footer {_x000D_
background-color: purple;_x000D_
}
_x000D_
<div id="container">_x000D_
<header class="section">_x000D_
foo_x000D_
</header>_x000D_
_x000D_
<div class="section expand">_x000D_
<div class="columns-container">_x000D_
<div class="column" id="a">_x000D_
<p>Contents A</p>_x000D_
</div>_x000D_
<div class="column" id="b">_x000D_
<p>Contents B</p>_x000D_
</div>_x000D_
<div class="column" id="c">_x000D_
<p>Contents C</p>_x000D_
</div>_x000D_
</div>_x000D_
</div>_x000D_
_x000D_
<footer class="section">_x000D_
bar_x000D_
</footer>_x000D_
</div>
_x000D_
This does, though, require that you reset the .column
elements to text-align: left
(assuming you want them left-aligned, obviously (JS Fiddle demo).
In HTML5, using an a
element without an href
attribute is valid. It is considered to be a "placeholder hyperlink."
Example:
<a>previous</a>
Look for "placeholder hyperlink" on the w3c anchor tag reference page: https://www.w3.org/TR/2016/REC-html51-20161101/textlevel-semantics.html#the-a-element.
And it is also mentioned on the wiki here: https://www.w3.org/wiki/Elements/a
A placeholder link is for cases where you want to use an anchor element, but not have it navigate anywhere. This comes in handy for marking up the current page in a navigation menu or breadcrumb trail. (The old approach would have been to either use a span tag or an anchor tag with a class named "active" or "current" to style it and JavaScript to cancel navigation.)
A placeholder link is also useful in cases where you want to dynamically set the destination of the link via JavaScript at runtime. You simply set the value of the href attribute, and the anchor tag becomes clickable.
See also:
Here is a guide that resolved a lot of these issues for me.
http://www.steveworkman.com/node-js/2012/installing-jsdom-on-windows/
I remember in particular the python version as important. Make sure you install 2.7.3 instead of 3's.
in normal time, checkboxes return an on/off value.
you can verify it with this code:
<form action method="POST">
<input type="checkbox" name="hello"/>
</form>
<?php
if(isset($_POST['hello'])) echo('<p>'.$_POST['hello'].'</p>');
?>
this will return
<p>off</p>
or
<p>on</p>
SELECT UPPER(firstname) FROM Person
SELECT LOWER(firstname) FROM Person
"C:\Program Files\PuTTY\pscp.exe" -scp file.py server.com:
file.py
will be uploaded into your HOME
dir on remote server.
or when the remote server has a different user, use "C:\Program Files\PuTTY\pscp.exe" -l username -scp file.py server.com:
After connecting to the server pscp will ask for a password.
User-defined Exception can be Checked Exception or Unchecked Exception, It depends on the class it is extending to.
User-defined Exception can be Custom Checked Exception, if it is extending to Exception class
User-defined Exception can be Custom Unchecked Exception , if it is extending to Run time Exception class.
Define a class and make it a child to Exception or Run time Exception
Each row has an ID. All you have to do is to send this ID to the function setSelected()
, store it (in $scope.idSelectedVote
for instance), and then check for each row if the selected ID is the same as the current one. Here is a solution (see the documentation for ngClass
, if needed):
$scope.idSelectedVote = null;
$scope.setSelected = function (idSelectedVote) {
$scope.idSelectedVote = idSelectedVote;
};
<ul ng-repeat="vote in votes" ng-click="setSelected(vote.id)" ng-class="{selected: vote.id === idSelectedVote}">
...
</ul>
Place the link location in the action=""
of a wrapping form
tag.
Your first link would be:
<form action="1.html">
<input type="submit" class="button_active" value="1">
</form>
ORA-12154: TNS:could not resolve the connect identifier specified?
In case the TNS is not defined you can also try this one:
If you are using C#.net 2010
or other version of VS and oracle 10g express edition or lower version, and you make a connection string like this:
static string constr = @"Data Source=(DESCRIPTION=
(ADDRESS_LIST=(ADDRESS=(PROTOCOL=TCP)(HOST=yourhostname )(PORT=1521)))
(CONNECT_DATA=(SERVER=DEDICATED)(SERVICE_NAME=XE)));
User Id=system ;Password=yourpasswrd";
After that you get error message ORA-12154: TNS:could not resolve the connect identifier specified
then first you have to do restart your system and run your project.
And if Your windows is 64 bit then you need to install oracle 11g 32 bit and if you installed 11g 64 bit then you need to Install Oracle 11g Oracle Data Access Components (ODAC) with Oracle Developer Tools for Visual Studio version 11.2.0.1.2 or later from OTN and check it in Oracle Universal Installer Please be sure that the following are checked:
Oracle Data Provider for .NET 2.0
Oracle Providers for ASP.NET
Oracle Developer Tools for Visual Studio
Oracle Instant Client
And then restart your Visual Studio and then run your project .... NOTE:- SYSTEM RESTART IS necessary TO SOLVE THIS TYPES OF ERROR.......
If you have several files or directories and want to compare non continuous commits, you could do this:
Make a temporary branch ("revision" in this example)
git checkout -b revision
Rewind to the first commit target
git reset --hard <commit_target>
Cherry picking on those commit interested
git cherry-pick <commit_interested> ...
Apply diff
git diff <commit-target>^
When you done
git branch -D revision
I think a good first approximation is "never".
I think a good second approximation is "never".
If you are desperate for perf, consider them, but then always measure.
On Fedora 22, you need to do this instead:
sudo dnf install python-devel
sudo dnf install openldap-devel
They seem to round up the values to the closest integer; but Iam seeing inconsistency in chrome,safari and firefox.
For e.g if 33.3% converts to 420.945px
chrome and firexfox show it as 421px. while safari shows its as 420px.
This seems like chrome and firefox follow the floor and ceil logic while safari doesn't. This page seems to discuss the same problem
Sorry for awakening an old question like this. But I think what the original author wanted as an answer was:
You need to force your program to make the graphic update after you make the change to the textbox1. You can do that by invoking Update();
textBox1.Text += "\r\nThread Sleeps!";
textBox1.Update();
System.Threading.Thread.Sleep(4000);
textBox1.Text += "\r\nThread awakens!";
textBox1.Update();
Normally this will be done automatically when the thread is done.
Ex, you press a button, changes are made to the text, thread dies, and then .Update()
is fired and you see the changes.
(I'm not an expert so I cant really tell you when its fired, but its something similar to this any way.)
In this case, you make a change, pause the thread, and then change the text again, and when the thread finally dies the .Update()
is fired. This resulting in you only seeing the last change made to the text.
You would experience the same issue if you had a long execution between the text changes.
this is just a modification of Karsten's code
function include_all_php($folder){
foreach (glob("{$folder}/*.php") as $filename)
{
include $filename;
}
}
include_all_php("my_classes");
Just wanted to add a little more detail to the answers given. You can also use
sheet.Visible = False
to hide and
sheet.Visible = True
to unhide.
I had no idea what file was having the lock so what I did to get out of this issue was:
This worked for me.
I use a one-liner when processing data from GSON:
int i = object != null ? Double.valueOf(object.toString()).intValue() : 0;
This format is used to get current timestamp and stored in mysql
$date = date("Y-m-d H:i:s");
$update_query = "UPDATE db.tablename SET insert_time=".$date." WHERE username='" .$somename . "'";
After getting the help from @Blender, @ekhumoro and @Dan, I understand the Linux and Python more than before. Thank you. I got the an idea by @ekhumoro, it is I didn't install PyQt5 correctly. So I delete PyQt5 folder and download again. And redo everything from very start.
After redoing, I got the error as my last update at my question. So, when I search at stack, I got the following solution from here
sudo ln -s /usr/include/python2.7 /usr/local/include/python2.7
And then, I did "sudo make" and "sudo make install" step by step. After "sudo make install", I got the following error. But I ignored it and I created a simple design with qt designer. And I converted it into python file by pyuic5. Everything are going well.
install -m 755 -p /home/thura/PyQt/pyuic5 /usr/bin/
strip /usr/bin/pyuic5
strip:/usr/bin/pyuic5: File format not recognized
make: [install_pyuic5] Error 1 (ignored)
Java binaries may be under "Program Files" or "Program Files (x86)": those white spaces will likely affect the behaviour.
In order to set up env variables correctly, I suggest gathering some info before starting:
Cygwin configuration:
go under C:\cygwin\home\, then open .bash_profile and add the following two lines (conveniently customized in order to match you actual JDK path)
export JAVA_HOME="/cygdrive/c/PROGRA~1/Java/jdk1.8.0_65"
export PATH="$JAVA_HOME/bin:$PATH"
Now from Cygwin launch
javac -version
to check if the configuration is successful.
Use SSIS to extract and process the information. That way you will have the processing of the XML files separated from SQL Server. You can also do the SSIS transformations on a separate server if needed. Store the phone numbers in a standard format using VARCHAR. NVARCHAR would be unnecessary since we are talking about numbers and maybe a couple of other chars, like '+', ' ', '(', ')' and '-'.
It depends on what your local OS is.
If your local OS is Unix-like, then try:
scp username@remoteHost:/remote/dir/file.txt /local/dir/
If your local OS is Windows ,then you should use pscp.exe
utility.
For example, below command will download file.txt from remote to D:
disk of local machine.
pscp.exe username@remoteHost:/remote/dir/file.txt d:\
It seems your Local OS is Unix, so try the former one.
For those who don't know what pscp.exe
is and don't know where it is, you can always go to putty
official website to download it. And then open a CMD prompt, go to the pscp.exe directory where you put it. Then execute the command as provided above
In fact, your query is right except for the typo: your filter is excluding all records: you should change the <=
for >=
and vice versa:
qry = DBSession.query(User).filter(
and_(User.birthday <= '1988-01-17', User.birthday >= '1985-01-17'))
# or same:
qry = DBSession.query(User).filter(User.birthday <= '1988-01-17').\
filter(User.birthday >= '1985-01-17')
Also you can use between
:
qry = DBSession.query(User).filter(User.birthday.between('1985-01-17', '1988-01-17'))
Select
cast(replace(convert(decimal(15,2),acs_daily_debit), '.', ',') as varchar(20))
from acs_balance_details
It is important to highlight that the Property (MaximumErrorCount) that needs to be changed must be set as more than 0 (which is the default) in the Package level and not in the specific control that is showing the error (I tried this and it does not work!)
Be sure that in the Properties Window, the Pull down menu is set to "Package", then look for the property MaximumErrorCount to change it.
I see you've already found out a solution, however I just wanted to add some information which may help someone trying to achieve the same thing with big POST requests.
I had the same issue a couple of weeks ago, indeed it isn't possible to achieve a "clean" download through AJAX, the Filament Group created a jQuery plugin which works exactly how you've already found out, it is called jQuery File Download however there is a downside to this technique.
If you're sending big requests through AJAX (say files +1MB) it will negatively impact responsiveness. In slow Internet connections you'll have to wait a lot until the request is sent and also wait for the file to download. It isn't like an instant "click" => "popup" => "download start". It's more like "click" => "wait until data is sent" => "wait for response" => "download start" which makes it appear the file double its size because you'll have to wait for the request to be sent through AJAX and get it back as a downloadable file.
If you're working with small file sizes <1MB you won't notice this. But as I discovered in my own app, for bigger file sizes it is almost unbearable.
My app allow users to export images dynamically generated, these images are sent through POST requests in base64 format to the server (it is the only possible way), then processed and sent back to users in form of .png, .jpg files, base64 strings for images +1MB are huge, this force users to wait more than necessary for the file to start downloading. In slow Internet connections it can be really annoying.
My solution for this was to temporary write the file to the server, once it is ready, dynamically generate a link to the file in form of a button which changes between "Please wait..." and "Download" states and at the same time, print the base64 image in a preview popup window so users can "right-click" and save it. This makes all the waiting time more bearable for users, and also speed things up.
Update Sep 30, 2014:
Months have passed since I posted this, finally I've found a better approach to speed things up when working with big base64 strings. I now store base64 strings into the database (using longtext or longblog fields), then I pass its record ID through the jQuery File Download, finally on the download script file I query the database using this ID to pull the base64 string and pass it through the download function.
Download Script Example:
<?php
// Record ID
$downloadID = (int)$_POST['id'];
// Query Data (this example uses CodeIgniter)
$data = $CI->MyQueries->GetDownload( $downloadID );
// base64 tags are replaced by [removed], so we strip them out
$base64 = base64_decode( preg_replace('#\[removed\]#', '', $data[0]->image) );
// This example is for base64 images
$imgsize = getimagesize( $base64 );
// Set content headers
header('Content-Disposition: attachment; filename="my-file.png"');
header('Content-type: '.$imgsize['mime']);
// Force download
echo $base64;
?>
I know this is way beyond what the OP asked, however I felt it would be good to update my answer with my findings. When I was searching for solutions to my problem, I read lots of "Download from AJAX POST data" threads which didn't give me the answer I was looking for, I hope this information helps someone looking to achieve something like this.
<TextBlock Text="Stuff on line1
Stuff on line 2"/>
You can use any hexadecimally encoded value to represent a literal. In this case, I used the line feed (char 10). If you want to do "classic" vbCrLf
, then you can use 

By the way, note the syntax: It's the ampersand, a pound, the letter x, then the hex value of the character you want, and then finally a semi-colon.
ALSO: For completeness, you can bind to a text that already has the line feeds embedded in it like a constant in your code behind, or a variable constructed at runtime.
All "normal" triggers in SQL Server are "AFTER ..." triggers. There are no "BEFORE ..." triggers.
To do something before an update, check out INSTEAD OF UPDATE Triggers.
You can do lots of stupid thing with javascript. I will leave this quote here from YDKJS book.
Mentioned page of the book ->
Why not get the html first then pass it to the web view?
private String getHtml(String url){
HttpGet pageGet = new HttpGet(url);
ResponseHandler<String> handler = new ResponseHandler<String>() {
public String handleResponse(HttpResponse response) throws ClientProtocolException, IOException {
HttpEntity entity = response.getEntity();
String html;
if (entity != null) {
html = EntityUtils.toString(entity);
return html;
} else {
return null;
}
}
};
pageHTML = null;
try {
while (pageHTML==null){
pageHTML = client.execute(pageGet, handler);
}
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return pageHTML;
}
@Override
public void customizeWebView(final ServiceCommunicableActivity activity, final WebView webview, final SearchResult mRom) {
mRom.setFileSize(getFileSize(mRom.getURLSuffix()));
webview.getSettings().setJavaScriptEnabled(true);
WebViewClient anchorWebViewClient = new WebViewClient()
{
@Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
super.onPageStarted(view, url, favicon);
//Do what you want to with the html
String html = getHTML(url);
if( html!=null && !url.equals(lastLoadedURL)){
lastLoadedURL = url;
webview.loadDataWithBaseURL(url, html, null, "utf-8", url);
}
}
This should roughly do what you want to do. It is adapted from Is it possible to get the HTML code from WebView and shout out to https://stackoverflow.com/users/325081/aymon-fournier for his answer.
For me the problem was due to using rbenv
and forgetting to set the proper version globally.
So I had to set it with rbenv global xxx
In my case I installed 2.0.0-p247
so I had to issue the command:
rbenv global 2.0.0-p247
rbenv rehash
Then all was working fine.
Use upper-case HH
for 24h format:
String s = curr.ToString("HH:mm");
$_ is an alias for automatic variable $PSItem (introduced in PowerShell V3.0; Usage information found here) which represents the current item from the pipe.
PowerShell (v6.0) online documentation for automatic variables is here.
The problem with carousel automatically sliding after prev/next button press is solved.
$('.carousel').carousel({
pause: true,
interval: false
});
Use pygame
import pygame
mouse_pos = pygame.mouse.get_pos()
This returns the x and y position of the mouse.
See this website: https://www.pygame.org/docs/ref/mouse.html#pygame.mouse.set_pos
In this case, it appears that you've already included the file somewhere. But for class files, you should really "include" them using require_once
to avoid that sort of thing; it won't include the file if it already has been. (And you should usually use require[_once]
, not include[_once]
, the difference being that require
will cause a fatal error if the file doesn't exist, instead of just issuing a warning.)
Use queue.rear+1
to get the length of the queue
Adding to Gaby's post, my jdbc getTables() for Oracle 10g requires all caps to work:
"employee" -> "EMPLOYEE"
Otherwise I would get an exception:
java.sql.SqlExcepcion exhausted resultset
(even though "employee" is in the schema)
This might be another option. The trick is in the wrapper
function that returns another function which is passed in to pool.map
. The code below reads an input array and for each (unique) element in it, returns how many times (ie counts) that element appears in the array, For example if the input is
np.eye(3) = [ [1. 0. 0.]
[0. 1. 0.]
[0. 0. 1.]]
then zero appears 6 times and one 3 times
import numpy as np
from multiprocessing.dummy import Pool as ThreadPool
from multiprocessing import cpu_count
def extract_counts(label_array):
labels = np.unique(label_array)
out = extract_counts_helper([label_array], labels)
return out
def extract_counts_helper(args, labels):
n = max(1, cpu_count() - 1)
pool = ThreadPool(n)
results = {}
pool.map(wrapper(args, results), labels)
pool.close()
pool.join()
return results
def wrapper(argsin, results):
def inner_fun(label):
label_array = argsin[0]
counts = get_label_counts(label_array, label)
results[label] = counts
return inner_fun
def get_label_counts(label_array, label):
return sum(label_array.flatten() == label)
if __name__ == "__main__":
img = np.ones([2,2])
out = extract_counts(img)
print('input array: \n', img)
print('label counts: ', out)
print("========")
img = np.eye(3)
out = extract_counts(img)
print('input array: \n', img)
print('label counts: ', out)
print("========")
img = np.random.randint(5, size=(3, 3))
out = extract_counts(img)
print('input array: \n', img)
print('label counts: ', out)
print("========")
You should get:
input array:
[[1. 1.]
[1. 1.]]
label counts: {1.0: 4}
========
input array:
[[1. 0. 0.]
[0. 1. 0.]
[0. 0. 1.]]
label counts: {0.0: 6, 1.0: 3}
========
input array:
[[4 4 0]
[2 4 3]
[2 3 1]]
label counts: {0: 1, 1: 1, 2: 2, 3: 2, 4: 3}
========
I searched for firing click, mousedown and mouseup event on mouseover using JavaScript. I found an answer provided by Juan Mendes. For the answer click here.
Click here is the live demo and below is the code:
function fireEvent(node, eventName) {
// Make sure we use the ownerDocument from the provided node to avoid cross-window problems
var doc;
if (node.ownerDocument) {
doc = node.ownerDocument;
} else if (node.nodeType == 9) {
// the node may be the document itself, nodeType 9 = DOCUMENT_NODE
doc = node;
} else {
throw new Error("Invalid node passed to fireEvent: " + node.id);
}
if (node.dispatchEvent) {
// Gecko-style approach (now the standard) takes more work
var eventClass = "";
// Different events have different event classes.
// If this switch statement can't map an eventName to an eventClass,
// the event firing is going to fail.
switch (eventName) {
case "click": // Dispatching of 'click' appears to not work correctly in Safari. Use 'mousedown' or 'mouseup' instead.
case "mousedown":
case "mouseup":
eventClass = "MouseEvents";
break;
case "focus":
case "change":
case "blur":
case "select":
eventClass = "HTMLEvents";
break;
default:
throw "fireEvent: Couldn't find an event class for event '" + eventName + "'.";
break;
}
var event = doc.createEvent(eventClass);
var bubbles = eventName == "change" ? false : true;
event.initEvent(eventName, bubbles, true); // All events created as bubbling and cancelable.
event.synthetic = true; // allow detection of synthetic events
// The second parameter says go ahead with the default action
node.dispatchEvent(event, true);
} else if (node.fireEvent) {
// IE-old school style
var event = doc.createEventObject();
event.synthetic = true; // allow detection of synthetic events
node.fireEvent("on" + eventName, event);
}
};
You can use ^ or 0 (Zero) in normal mode to move to the beginning of a line.
^ moves the cursor to the first non-blank character of a line
0 always moves the cursor to the "first column"
You can also use Shifti to move and switch to Insert mode.
You can set CustomFormat property to "dd-MM-yyyy" in design mode and use dateTimePicker1.Text property to fetch string in "dd/MM/yyyy" format irrespective of display format.
First, hstore
is a contrib module, which only allows you to store key => value pairs, where keys and values can only be text
s (however values can be sql NULL
s too).
Both json
& jsonb
allows you to store a valid JSON value (defined in its spec).
F.ex. these are valid JSON representations: null
, true
, [1,false,"string",{"foo":"bar"}]
, {"foo":"bar","baz":[null]}
- hstore
is just a little subset compared to what JSON is capable (but if you only need this subset, it's fine).
The only difference between json
& jsonb
is their storage:
json
is stored in its plain text format, whilejsonb
is stored in some binary representationThere are 3 major consequences of this:
jsonb
usually takes more disk space to store than json
(sometimes not)jsonb
takes more time to build from its input representation than json
json
operations take significantly more time than jsonb
(& parsing also needs to be done each time you do some operation at a json
typed value)When jsonb
will be available with a stable release, there will be two major use cases, when you can easily select between them:
json
.jsonb
.Change:
using (RegistryKey key = Registry.LocalMachine.OpenSubKey("Software\\Wow6432Node\\MySQL AB\\MySQL Connector\\Net"))
To:
using (RegistryKey key = Registry.LocalMachine.OpenSubKey("Software\Wow6432Node\MySQL AB\MySQL Connector\Net"))
SELECT id,
Group_concat(column
)
FROM (SELECT id,
Concat(name
, ':', Group_concat(value
)) AS column
FROM mytbl
GROUP BY id,
name) tbl
GROUP BY id;
The way to reinstall Homebrew is completely remove it and start over. The Homebrew FAQ has a link to a shell script to uninstall homebrew.
If the only thing you've installed in /usr/local
is homebrew itself, you can just rm -rf /usr/local/* /usr/local/.git
to clear it out. But /usr/local/
is the standard Unix directory for all extra binaries, not just Homebrew, so you may have other things installed there. In that case uninstall_homebrew.sh
is a better bet. It is careful to only remove homebrew's files and leave the rest alone.
I searched for many pages of the web through of the Google and here on the Stack Overflow, but nothing suggested resolved my problem.
After many attempts, I've changed my way of to test that controller. Then I have discovered that the problem occurs always which I reopened the page through of the Ctrl + Shift + T
shortcut in Chrome. So the page ran, but without a parent window reference, and because this can't be closed.
I got the answer to my own question, ant this is:
select reverse(stuff(reverse('a,b,c,d,'), 1, N, ''))
Where N is the number of characters to remove. This avoids to write the complex column/string twice
One trick is to add a random number to the end of the URL. That way you don't have to rename the file every time. E.g.:
echo "<img src='temp.jpg?r=3892384947438'>"
The browser will not cache it as long as the random number is different, but the web server will ignore it.
Despite having all the appropriate using
statements, calling Close
, having some exponential back off logic and recreating the TcpClient
I've still been seeing issues where the application cannot recover the TCP connection without an application restart. It keeps failing with a
System.IO.IOException: Unable to read data from the transport connection: An existing connection was forcibly closed by the remote host
.
But there is an option LingerState
on the TcpClient
that appears it may have solved the issue (might not know for a few months as my own hardware setup only fails about that often!). See MSDN.
// This discards any pending data and Winsock resets the connection.
LingerOption lingerOption = new LingerOption(true, 0);
using (var tcpClient = new TcpClient
{SendTimeout = 2000, ReceiveTimeout = 2000, LingerState = lingerOption })
...
Just another alternative solution for those who want to pass variables to a script which is sourced using flask, I only managed to get this working by defining the variables outside and then calling the script as follows:
<script>
var myfileuri = "/static/my_csv.csv"
var mytableid = 'mytable';
</script>
<script type="text/javascript" src="/static/test123.js"></script>
If I input jinja variables in test123.js
it doesn't work and you will get an error.
You need to set
document["pic1"].src = searchPic.src;
The searchPic itself is your Image(), you need to read the src that you set.
ADO Recordset has .State
property, you can check if its value is adStateClosed
or adStateOpen
If Not (rs Is Nothing) Then
If (rs.State And adStateOpen) = adStateOpen Then rs.Close
Set rs = Nothing
End If
Edit;
The reason not to check .State
against 1 or 0 is because even if it works 99.99% of the time, it is still possible to have other flags set which will cause the If statement fail the adStateOpen
check.
Edit2:
For Late binding without the ActiveX Data Objects referenced, you have few options. Use the value of adStateOpen constant from ObjectStateEnum
If Not (rs Is Nothing) Then
If (rs.State And 1) = 1 Then rs.Close
Set rs = Nothing
End If
Or you can define the constant yourself to make your code more readable (defining them all for a good example.)
Const adStateClosed As Long = 0 'Indicates that the object is closed.
Const adStateOpen As Long = 1 'Indicates that the object is open.
Const adStateConnecting As Long = 2 'Indicates that the object is connecting.
Const adStateExecuting As Long = 4 'Indicates that the object is executing a command.
Const adStateFetching As Long = 8 'Indicates that the rows of the object are being retrieved.
[...]
If Not (rs Is Nothing) Then
' ex. If (0001 And 0001) = 0001 (only open flag) -> true
' ex. If (1001 And 0001) = 0001 (open and retrieve) -> true
' This second example means it is open, but its value is not 1
' and If rs.State = 1 -> false, even though it is open
If (rs.State And adStateOpen) = adStateOpen Then
rs.Close
End If
Set rs = Nothing
End If
select * from information_schema.columns
could get you started.
You do not have to reference std::cout
or std::endl
explicitly.
They are both included in the namespace std
. using namespace std
instead of using scope resolution operator ::
every time makes is easier and cleaner.
#include<iostream>
#include<string>
using namespace std;
It's unfortunately not so easy to do that. If you're trying to make some sort of text user interface, you may want to look into curses
. If you want to display things like you normally would in a terminal, but want input like that, then you'll have to work with termios
, which unfortunately appears to be poorly documented in Python. Neither of these options are that simple, though, unfortunately. Additionally, they do not work under Windows; if you need them to work under Windows, you'll have to use PDCurses as a replacement for curses
or pywin32 rather than termios
.
I was able to get this working decently. It prints out the hexadecimal representation of keys you type. As I said in the comments of your question, arrows are tricky; I think you'll agree.
#!/usr/bin/env python
import sys
import termios
import contextlib
@contextlib.contextmanager
def raw_mode(file):
old_attrs = termios.tcgetattr(file.fileno())
new_attrs = old_attrs[:]
new_attrs[3] = new_attrs[3] & ~(termios.ECHO | termios.ICANON)
try:
termios.tcsetattr(file.fileno(), termios.TCSADRAIN, new_attrs)
yield
finally:
termios.tcsetattr(file.fileno(), termios.TCSADRAIN, old_attrs)
def main():
print 'exit with ^C or ^D'
with raw_mode(sys.stdin):
try:
while True:
ch = sys.stdin.read(1)
if not ch or ch == chr(4):
break
print '%02x' % ord(ch),
except (KeyboardInterrupt, EOFError):
pass
if __name__ == '__main__':
main()
Also remember that all info()
, error()
, and debug()
logging calls provide internal documentation within any application.
This problem can also happen in Windows. Cmake looks into the registry and sometimes python values are not set. For those with similar problem:
http://ericsilva.org/2012/10/11/restoring-your-python-registry-in-windows/
Just create a .reg file to set the necessary keys and edit accordingly to match your setup.
Windows Registry Editor Version 5.00
[HKEY_CURRENT_USER\Software\Python]
[HKEY_CURRENT_USER\Software\Python\Pythoncore]
[HKEY_CURRENT_USER\Software\Python\Pythoncore\2.6]
[HKEY_CURRENT_USER\Software\Python\Pythoncore\2.6\InstallPath]
@="C:\\python26"
[HKEY_CURRENT_USER\Software\Python\Pythoncore\2.6\PythonPath]
@="C:\\python26;C:\\python26\\Lib\\;C:\\python26\\DLLs\\"
[HKEY_CURRENT_USER\Software\Python\Pythoncore\2.7]
[HKEY_CURRENT_USER\Software\Python\Pythoncore\2.7\InstallPath]
@="C:\\python27"
[HKEY_CURRENT_USER\Software\Python\Pythoncore\2.7\PythonPath]
@="C:\\python27;C:\\python27\\Lib\\;C:\\python27\\DLLs\\"
Try these
String appDirectoryName = getResources().getString(R.string.app_name);
File directory = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/" + getResources().getString(R.string.app_name));
directory.mkdirs();
File[] fList = directory.listFiles();
int a = 1;
for (int x = 0; x < fList.length; x++) {
//txt.setText("You Have Capture " + String.valueOf(a) + " Photos");
a++;
}
//get all the files from a directory
for (File file : fList) {
if (file.isFile()) {
list.add(new ModelClass(file.getName(), file.getAbsolutePath()));
}
}
Just hit the same problem... For some reason, the freezepanes command just caused crosshairs to appear in the centre of the screen. It turns oout I had switched ScreenUpdating off! Solved with the following code:
Application.ScreenUpdating = True
Cells(2, 1).Select
ActiveWindow.FreezePanes = True
Now it works fine.
This is a good example to demonstrate that BFS is better than DFS in certain case. https://leetcode.com/problems/01-matrix/
When correctly implemented, both solutions should visit cells that have farther distance than the current cell +1. But DFS is inefficient and repeatedly visited the same cell resulting O(n*n) complexity.
For example,
1,1,1,1,1,1,1,1,
1,1,1,1,1,1,1,1,
1,1,1,1,1,1,1,1,
0,0,0,0,0,0,0,0,
Pandas allows you to plot tables using matplotlib (details here). Usually this plots the table directly onto a plot (with axes and everything) which is not what you want. However, these can be removed first:
import matplotlib.pyplot as plt
import pandas as pd
from pandas.table.plotting import table # EDIT: see deprecation warnings below
ax = plt.subplot(111, frame_on=False) # no visible frame
ax.xaxis.set_visible(False) # hide the x axis
ax.yaxis.set_visible(False) # hide the y axis
table(ax, df) # where df is your data frame
plt.savefig('mytable.png')
The output might not be the prettiest but you can find additional arguments for the table() function here. Also thanks to this post for info on how to remove axes in matplotlib.
Here is a (admittedly quite hacky) way of simulating multi-indexes when plotting using the method above. If you have a multi-index data frame called df that looks like:
first second
bar one 1.991802
two 0.403415
baz one -1.024986
two -0.522366
foo one 0.350297
two -0.444106
qux one -0.472536
two 0.999393
dtype: float64
First reset the indexes so they become normal columns
df = df.reset_index()
df
first second 0
0 bar one 1.991802
1 bar two 0.403415
2 baz one -1.024986
3 baz two -0.522366
4 foo one 0.350297
5 foo two -0.444106
6 qux one -0.472536
7 qux two 0.999393
Remove all duplicates from the higher order multi-index columns by setting them to an empty string (in my example I only have duplicate indexes in "first"):
df.ix[df.duplicated('first') , 'first'] = '' # see deprecation warnings below
df
first second 0
0 bar one 1.991802
1 two 0.403415
2 baz one -1.024986
3 two -0.522366
4 foo one 0.350297
5 two -0.444106
6 qux one -0.472536
7 two 0.999393
Change the column names over your "indexes" to the empty string
new_cols = df.columns.values
new_cols[:2] = '','' # since my index columns are the two left-most on the table
df.columns = new_cols
Now call the table function but set all the row labels in the table to the empty string (this makes sure the actual indexes of your plot are not displayed):
table(ax, df, rowLabels=['']*df.shape[0], loc='center')
et voila:
Your not-so-pretty but totally functional multi-indexed table.
As pointed out in the comments, the import statement for table
:
from pandas.tools.plotting import table
is now deprecated in newer versions of pandas in favour of:
from pandas.plotting import table
The ix
indexer has now been fully deprecated so we should use the loc
indexer instead. Replace:
df.ix[df.duplicated('first') , 'first'] = ''
with
df.loc[df.duplicated('first') , 'first'] = ''
With HttpClient 4.5 you can do this:
CloseableHttpClient httpClient = HttpClients.custom().setConnectionManager(new PoolingHttpClientConnectionManager()).build();
Note that this one implements Closeable (for shutting down of the connection manager).
This comment is for readers who have found this entry but are using mysql instead of oracle! on mysql you can do the following: Today
SELECT *
FROM
WHERE date(tran_date) = CURRENT_DATE()
Yesterday
SELECT *
FROM yourtable
WHERE date(tran_date) = DATE_SUB(CURRENT_DATE(), INTERVAL 1 DAY)
In addition to @senderle's here, some might also be wondering how to use the functionality of multiprocessing.Pool
.
The nice thing is that there is a .Pool()
method to the manager
instance that mimics all the familiar API of the top-level multiprocessing
.
from itertools import repeat
import multiprocessing as mp
import os
import pprint
def f(d: dict) -> None:
pid = os.getpid()
d[pid] = "Hi, I was written by process %d" % pid
if __name__ == '__main__':
with mp.Manager() as manager:
d = manager.dict()
with manager.Pool() as pool:
pool.map(f, repeat(d, 10))
# `d` is a DictProxy object that can be converted to dict
pprint.pprint(dict(d))
Output:
$ python3 mul.py
{22562: 'Hi, I was written by process 22562',
22563: 'Hi, I was written by process 22563',
22564: 'Hi, I was written by process 22564',
22565: 'Hi, I was written by process 22565',
22566: 'Hi, I was written by process 22566',
22567: 'Hi, I was written by process 22567',
22568: 'Hi, I was written by process 22568',
22569: 'Hi, I was written by process 22569',
22570: 'Hi, I was written by process 22570',
22571: 'Hi, I was written by process 22571'}
This is a slightly different example where each process just logs its process ID to the global DictProxy
object d
.
I ran across this while on a hunt for answers myself after attempting to follow a guide using pm2. The goal is to automatically start a node.js application on a server. Some guides call out using pm2 startup systemd
, which is the path that leads to the question of using systemctl on Ubuntu 14.04. Instead, use pm2 startup ubuntu
.
If you need this to leave the dot for float numbers, use this
var s = "-12345.50 €".replace(/[^\d.-]/g, ''); // gives "-12345.50"
GridLayout is often not the best choice for buttons, although it might be for your application. A good reference is the tutorial on using Layout Managers. If you look at the GridLayout example, you'll see the buttons look a little silly -- way too big.
A better idea might be to use a FlowLayout for your buttons, or if you know exactly what you want, perhaps a GroupLayout. (Sun/Oracle recommend that GroupLayout or GridBag layout are better than GridLayout when hand-coding.)
You can put the condition after the WHEN
clause, like so:
SELECT
CASE
WHEN PAT_ENT.SCR_DT is not null and PAT_ENTRY.ELIGIBILITY is null THEN 'Favor'
WHEN PAT_ENT.SCR_DT is not null and PAT_ENTRY.EL = 'No' THEN 'Error'
WHEN PAT_ENTRY.EL = 'Yes' and ISNULL(DS.DES, 'OFF') = 'OFF' THEN 'Active'
WHEN DS.DES = 'N' THEN 'Early Term'
WHEN DS.DES = 'Y' THEN 'Complete'
END
FROM
....
Of course, the argument could be made that complex rules like this belong in your business logic layer, not in a stored procedure in the database...
I know this is an old question, a few of these methods didn't work for me so for anyone looking in the future or having my troubles this worked for me
I overrode onPause
and called finish()
inside that method.
require(name)
It will return bolean true/false
The name which is passed as parameter to the require, ruby will try to find the source file with that name in your load path. The require method will return ‘false’ if you try to load the same library after the first time. The require method only needs to be used if library you are loading is defined in a separate file. So it keeps track of whether that library was already loaded or not.
include module_name
Suppose if you have some methods that you need to have in two different classes. Then you don't have to write them in both the classes. Instead what you can do is, define it in module. And then include this module in other classes. It is provided by Ruby just to ensure DRY principle. It’s used to DRY up your code to avoid duplication
First, create the data for the chart
H <- c(1.964138757, 1.729143013, 1.713273714, 1.706771799, 1.67977205)
M <- c("SP105", "SP30", "SP244", "SP31", "SP147")
Second, give the name for a chart file
png(file = "Bargraph.jpeg", width = 500, height = 300)
Third, Plot the bar chart
barplot(H,names.arg=M,ylab="Degree ", col= rainbow(5), las=2, border = 0, cex.lab=1, cex.axis=1, font=1,col.axis="black")
title(xlab="Service Providers", line=4, cex.lab=1)
Finally, save the file
dev.off()
Output:
You must make your foreign key nullable:
public class User
{
public int Id { get; set; }
public int? CountryId { get; set; }
public virtual Country Country { get; set; }
}
If a TestRestTemplate is a valid option in your unit test, this documentation might be relevant
Short answer: if using
@SpringBootTest(webEnvironment=WebEnvironment.RANDOM_PORT)
then @Autowired
will work. If using
@SpringBootTest(webEnvironment=WebEnvironment.MOCK)
then create a TestRestTemplate like this
private TestRestTemplate template = new TestRestTemplate();
Attention, this is only advised if your
runOnceOnStartup
method depends on a fully initialized spring context. For example: you wan to call a dao with transaction demarcation
You can also use a scheduled method with fixedDelay set very high
@Scheduled(fixedDelay = Long.MAX_VALUE)
public void runOnceOnStartup() {
dosomething();
}
This has the advantage that the whole application is wired up (Transactions, Dao, ...)
seen in Scheduling tasks to run once, using the Spring task namespace
np.where
returns a tuple of length equal to the dimension of the numpy ndarray on which it is called (in other words ndim
) and each item of tuple is a numpy ndarray of indices of all those values in the initial ndarray for which the condition is True. (Please don't confuse dimension with shape)
For example:
x=np.arange(9).reshape(3,3)
print(x)
array([[0, 1, 2],
[3, 4, 5],
[6, 7, 8]])
y = np.where(x>4)
print(y)
array([1, 2, 2, 2], dtype=int64), array([2, 0, 1, 2], dtype=int64))
y is a tuple of length 2 because x.ndim
is 2. The 1st item in tuple contains row numbers of all elements greater than 4 and the 2nd item contains column numbers of all items greater than 4. As you can see, [1,2,2,2] corresponds to row numbers of 5,6,7,8 and [2,0,1,2] corresponds to column numbers of 5,6,7,8
Note that the ndarray is traversed along first dimension(row-wise).
Similarly,
x=np.arange(27).reshape(3,3,3)
np.where(x>4)
will return a tuple of length 3 because x has 3 dimensions.
But wait, there's more to np.where!
when two additional arguments are added to np.where
; it will do a replace operation for all those pairwise row-column combinations which are obtained by the above tuple.
x=np.arange(9).reshape(3,3)
y = np.where(x>4, 1, 0)
print(y)
array([[0, 0, 0],
[0, 0, 1],
[1, 1, 1]])
Use either COUNT(field)
or COUNT(*)
, and stick with it consistently, and if your database allows COUNT(tableHere)
or COUNT(tableHere.*)
, use that.
In short, don't use COUNT(1)
for anything. It's a one-trick pony, which rarely does what you want, and in those rare cases is equivalent to count(*)
count(*)
for countingUse *
for all your queries that need to count everything, even for joins, use *
SELECT boss.boss_id, COUNT(subordinate.*)
FROM boss
LEFT JOIN subordinate on subordinate.boss_id = boss.boss_id
GROUP BY boss.id
But don't use COUNT(*)
for LEFT joins, as that will return 1 even if the subordinate table doesn't match anything from parent table
SELECT boss.boss_id, COUNT(*)
FROM boss
LEFT JOIN subordinate on subordinate.boss_id = boss.boss_id
GROUP BY boss.id
Don't be fooled by those advising that when using *
in COUNT, it fetches entire row from your table, saying that *
is slow. The *
on SELECT COUNT(*)
and SELECT *
has no bearing to each other, they are entirely different thing, they just share a common token, i.e. *
.
In fact, if it is not permitted to name a field as same as its table name, RDBMS language designer could give COUNT(tableNameHere)
the same semantics as COUNT(*)
. Example:
For counting rows we could have this:
SELECT COUNT(emp) FROM emp
And they could make it simpler:
SELECT COUNT() FROM emp
And for LEFT JOINs, we could have this:
SELECT boss.boss_id, COUNT(subordinate)
FROM boss
LEFT JOIN subordinate on subordinate.boss_id = boss.boss_id
GROUP BY boss.id
But they cannot do that (COUNT(tableNameHere)
) since SQL standard permits naming a field with the same name as its table name:
CREATE TABLE fruit -- ORM-friendly name
(
fruit_id int NOT NULL,
fruit varchar(50), /* same name as table name,
and let's say, someone forgot to put NOT NULL */
shape varchar(50) NOT NULL,
color varchar(50) NOT NULL
)
And also, it is not a good practice to make a field nullable if its name matches the table name. Say you have values 'Banana', 'Apple', NULL, 'Pears' on fruit
field. This will not count all rows, it will only yield 3, not 4
SELECT count(fruit) FROM fruit
Though some RDBMS do that sort of principle (for counting the table's rows, it accepts table name as COUNT's parameter), this will work in Postgresql (if there is no subordinate
field in any of the two tables below, i.e. as long as there is no name conflict between field name and table name):
SELECT boss.boss_id, COUNT(subordinate)
FROM boss
LEFT JOIN subordinate on subordinate.boss_id = boss.boss_id
GROUP BY boss.id
But that could cause confusion later if we will add a subordinate
field in the table, as it will count the field(which could be nullable), not the table rows.
So to be on the safe side, use:
SELECT boss.boss_id, COUNT(subordinate.*)
FROM boss
LEFT JOIN subordinate on subordinate.boss_id = boss.boss_id
GROUP BY boss.id
count(1)
: The one-trick ponyIn particular to COUNT(1)
, it is a one-trick pony, it works well only on one table query:
SELECT COUNT(1) FROM tbl
But when you use joins, that trick won't work on multi-table queries without its semantics being confused, and in particular you cannot write:
-- count the subordinates that belongs to boss
SELECT boss.boss_id, COUNT(subordinate.1)
FROM boss
LEFT JOIN subordinate on subordinate.boss_id = boss.boss_id
GROUP BY boss.id
So what's the meaning of COUNT(1) here?
SELECT boss.boss_id, COUNT(1)
FROM boss
LEFT JOIN subordinate on subordinate.boss_id = boss.boss_id
GROUP BY boss.id
Is it this...?
-- counting all the subordinates only
SELECT boss.boss_id, COUNT(subordinate.boss_id)
FROM boss
LEFT JOIN subordinate on subordinate.boss_id = boss.boss_id
GROUP BY boss.id
Or this...?
-- or is that COUNT(1) will also count 1 for boss regardless if boss has a subordinate
SELECT boss.boss_id, COUNT(*)
FROM boss
LEFT JOIN subordinate on subordinate.boss_id = boss.boss_id
GROUP BY boss.id
By careful thought, you can infer that COUNT(1)
is the same as COUNT(*)
, regardless of type of join. But for LEFT JOINs result, we cannot mold COUNT(1)
to work as: COUNT(subordinate.boss_id)
, COUNT(subordinate.*)
So just use either of the following:
-- count the subordinates that belongs to boss
SELECT boss.boss_id, COUNT(subordinate.boss_id)
FROM boss
LEFT JOIN subordinate on subordinate.boss_id = boss.boss_id
GROUP BY boss.id
Works on Postgresql, it's clear that you want to count the cardinality of the set
-- count the subordinates that belongs to boss
SELECT boss.boss_id, COUNT(subordinate.*)
FROM boss
LEFT JOIN subordinate on subordinate.boss_id = boss.boss_id
GROUP BY boss.id
Another way to count the cardinality of the set, very English-like (just don't make a column with a name same as its table name) : http://www.sqlfiddle.com/#!1/98515/7
select boss.boss_name, count(subordinate)
from boss
left join subordinate on subordinate.boss_code = boss.boss_code
group by boss.boss_name
You cannot do this: http://www.sqlfiddle.com/#!1/98515/8
select boss.boss_name, count(subordinate.1)
from boss
left join subordinate on subordinate.boss_code = boss.boss_code
group by boss.boss_name
You can do this, but this produces wrong result: http://www.sqlfiddle.com/#!1/98515/9
select boss.boss_name, count(1)
from boss
left join subordinate on subordinate.boss_code = boss.boss_code
group by boss.boss_name
Shameless self plug: you could always use https://github.com/amoerie/jstreams
Works on Java 6 and up, a perfect fit for Android development.
It looks a lot like Scala operators, lodash, C# LINQ, etc.
phpMyAdmin provides a GUI for this within the structure view of a table. Check to select the column you want to move and click the change action at the bottom of the column list. You can then change all of the column properties and you'll find the 'move column' function at the far right of the screen.
Of course this is all just building the queries in the perfectly good top answer but GUI fans might appreciate the alternative.
my phpMyAdmin version is 4.1.7
I see in the documentation page an example like this:
<source src="foo.ogg" type="video/ogg; codecs="dirac, speex"">
Maybe you should enclose the codec
information with "
entities instead of actual quotes and the type
attribute with quotes instead of apostrophes.
You can also try removing the codec info altogether.
I had hard times figuring it out myself and this post helped me to find the right answer for my case. When working with financial messaging as ISO-8583 the 3DES requirements are quite specific, so for my especial case the "DESede/CBC/PKCS5Padding" combinations wasn't solving the problem. After some comparative testing of my results against some 3DES calculators designed for the financial world I found the the value "DESede/ECB/Nopadding" is more suited for the the specific task.
Here is a demo implementation of my TripleDes class (using the Bouncy Castle provider)
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;
import java.security.Security;
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
/**
*
* @author Jose Luis Montes de Oca
*/
public class TripleDesCipher {
private static String TRIPLE_DES_TRANSFORMATION = "DESede/ECB/Nopadding";
private static String ALGORITHM = "DESede";
private static String BOUNCY_CASTLE_PROVIDER = "BC";
private Cipher encrypter;
private Cipher decrypter;
public TripleDesCipher(byte[] key) throws NoSuchAlgorithmException, NoSuchProviderException, NoSuchPaddingException,
InvalidKeyException {
Security.addProvider(new BouncyCastleProvider());
SecretKey keySpec = new SecretKeySpec(key, ALGORITHM);
encrypter = Cipher.getInstance(TRIPLE_DES_TRANSFORMATION, BOUNCY_CASTLE_PROVIDER);
encrypter.init(Cipher.ENCRYPT_MODE, keySpec);
decrypter = Cipher.getInstance(TRIPLE_DES_TRANSFORMATION, BOUNCY_CASTLE_PROVIDER);
decrypter.init(Cipher.DECRYPT_MODE, keySpec);
}
public byte[] encode(byte[] input) throws IllegalBlockSizeException, BadPaddingException {
return encrypter.doFinal(input);
}
public byte[] decode(byte[] input) throws IllegalBlockSizeException, BadPaddingException {
return decrypter.doFinal(input);
}
}
For anyone looking for a scalable solution: I wrote a small helper utility in SASS to generate responsive proportional rectangles for different breakpoints. Take a look at SASS Proportions
Hope it helps anybody!
Environment.getExternalStorageDirectory().getAbsolutePath()
Gives you the full path the SDCard. You can then do normal File I/O operations using standard Java.
Here's a simple example for writing a file:
String baseDir = Environment.getExternalStorageDirectory().getAbsolutePath();
String fileName = "myFile.txt";
// Not sure if the / is on the path or not
File f = new File(baseDir + File.separator + fileName);
f.write(...);
f.flush();
f.close();
Edit:
Oops - you wanted an example for reading ...
String baseDir = Environment.getExternalStorageDirectory().getAbsolutePath();
String fileName = "myFile.txt";
// Not sure if the / is on the path or not
File f = new File(baseDir + File.Separator + fileName);
FileInputStream fiStream = new FileInputStream(f);
byte[] bytes;
// You might not get the whole file, lookup File I/O examples for Java
fiStream.read(bytes);
fiStream.close();
You could write an extension method:
public static class Extension
{
public static bool IsNumeric(this string s)
{
float output;
return float.TryParse(s, out output);
}
}
You can use any bash looping constructs like FOR
, with is compatible to Linux and Mac.
https://tiswww.case.edu/php/chet/bash/bashref.html#Looping-Constructs
In your specific case you can define N
iterations, with N
is a number defining how many curl
executions you want.
for n in {1..N}; do curl <arguments>; done
ex:
for n in {1..20}; do curl -d @notification.json -H 'Content-Type: application/json' localhost:3000/dispatcher/notify; done
User JQuery is EmptyObject to check whether array is contains elements or not.
var testArray=[1,2,3,4,5];
var testArray1=[];
console.log(jQuery.isEmptyObject(testArray)); //false
console.log(jQuery.isEmptyObject(testArray1)); //true
Use \overleftarrow
to create a long arrow to the left.
\overleftarrow{blahblahblah}
You can use js and add a class in html to maintain the standard of conditional comments:
var ua = navigator.userAgent,
doc = document.documentElement;
if ((ua.match(/MSIE 10.0/i))) {
doc.className = doc.className + " ie10";
} else if((ua.match(/rv:11.0/i))){
doc.className = doc.className + " ie11";
}
Or use a lib like bowser:
Or modernizr for feature detection: