You can't make window.open
modal and I strongly recommend you not to go that way.
Instead you can use something like jQuery UI's dialog widget.
UPDATE:
You can use load()
method:
$("#dialog").load("resource.php").dialog({options});
This way it would be faster but the markup will merge into your main document so any submit will be applied on the main window.
And you can use an IFRAME:
$("#dialog").append($("<iframe></iframe>").attr("src", "resource.php")).dialog({options});
This is slower, but will submit independently.
Edit your style.xml
with:
<style name="AppTheme" parent="Base.V21.Theme.AppCompat.Light.Dialog">
Base.V21.Theme.AppCompat.Light.Dialog
provides a android poup-up theme
if (isset($_POST['Register']))
{
$ErrorArrays = array (); //Empty array for input errors
$Input_Username = $_POST['Username'];
$Input_Password = $_POST['Password'];
$Input_Confirm = $_POST['ConfirmPass'];
$Input_Email = $_POST['Email'];
if (empty($Input_Username))
{
$ErrorArrays[] = "Username Is Empty";
}
if (empty($Input_Password))
{
$ErrorArrays[] = "Password Is Empty";
}
if ($Input_Password !== $Input_Confirm)
{
$ErrorArrays[] = "Passwords Do Not Match!";
}
if (!filter_var($Input_Email, FILTER_VALIDATE_EMAIL))
{
$ErrorArrays[] = "Incorrect Email Formatting";
}
if (count($ErrorArrays) == 0)
{
// No Errors
}
else
{
foreach ($ErrorArrays AS $Errors)
{
echo "<font color='red'><b>".$Errors."</font></b><br>";
}
}
}
?>
<form method="POST">
Username: <input type='text' name='Username'> <br>
Password: <input type='password' name='Password'><br>
Confirm Password: <input type='password' name='ConfirmPass'><br>
Email: <input type='text' name='Email'> <br><br>
<input type='submit' name='Register' value='Register'>
</form>
This is a very basic PHP Form validation. This could be put in a try
block, but for basic reference, I see this fit following our conversation in the comment box.
What this script will do, is process each of the post elements, and act accordingly, for example:
if (!filter_var($Input_Email, FILTER_VALIDATE_EMAIL))
{
$ErrorArrays[] = "Incorrect Email Formatting";
}
This will check:
if $Input_Email is not a valid email. If this is not a valid E-mail, then a message will get added to a empty array.
Further down the script, you will see:
if (count($ErrorArrays) == 0)
{
// No Errors
}
else
{
foreach ($ErrorArrays AS $Errors)
{
echo "<font color='red'><b>".$Errors."</font></b><br>";
}
}
Basically. if the array count is not 0, errors have been found. Then the script will print out the errors.
Remember, this is a reference based on our conversation in the comment box, and should be used as such.
You can handle popup window or alert box:
Alert alert = driver.switchTo().alert();
alert.accept();
You can also decline the alert box:
Alert alert = driver.switchTo().alert();
alert().dismiss();
For me, something like Abdelhak Mouaamou's answer works, tested on API level 16 and 27.
Instead of using popupWindow.getContentView().getParent()
and casting the result to View
(which crashes on API level 16 cause there it returns a ViewRootImpl
object which isn't an instance of View
) I just use .getRootView()
which returns a view already, so no casting required there.
Hope it helps someone :)
complete working example scrambled together from other stackoverflow posts, just copy-paste it, e.g., in the onClick listener of a button:
// inflate the layout of the popup window
LayoutInflater inflater = (LayoutInflater)getSystemService(LAYOUT_INFLATER_SERVICE);
if(inflater == null) {
return;
}
//View popupView = inflater.inflate(R.layout.my_popup_layout, null); // this version gives a warning cause it doesn't like null as argument for the viewRoot, c.f. https://stackoverflow.com/questions/24832497 and https://stackoverflow.com/questions/26404951
View popupView = View.inflate(MyParentActivity.this, R.layout.my_popup_layout, null);
// create the popup window
final PopupWindow popupWindow = new PopupWindow(popupView,
LinearLayout.LayoutParams.WRAP_CONTENT,
LinearLayout.LayoutParams.WRAP_CONTENT,
true // lets taps outside the popup also dismiss it
);
// do something with the stuff in your popup layout, e.g.:
//((TextView)popupView.findViewById(R.id.textview_popup_helloworld))
// .setText("hello stackoverflow");
// dismiss the popup window when touched
popupView.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
popupWindow.dismiss();
return true;
}
});
// show the popup window
// which view you pass in doesn't matter, it is only used for the window token
popupWindow.showAtLocation(view, Gravity.CENTER, 0, 0);
//popupWindow.setOutsideTouchable(false); // doesn't seem to change anything for me
View container = popupWindow.getContentView().getRootView();
if(container != null) {
WindowManager wm = (WindowManager)getSystemService(Context.WINDOW_SERVICE);
WindowManager.LayoutParams p = (WindowManager.LayoutParams)container.getLayoutParams();
p.flags = WindowManager.LayoutParams.FLAG_DIM_BEHIND;
p.dimAmount = 0.3f;
if(wm != null) {
wm.updateViewLayout(container, p);
}
}
You need to use ScriptManager.RegisterStartupScript for Ajax.
protected void ButtonPP_Click(object sender, EventArgs e) { if (radioBtnACO.SelectedIndex < 0) { string csname1 = "PopupScript"; var cstext1 = new StringBuilder(); cstext1.Append("alert('Please Select Criteria!')"); ScriptManager.RegisterStartupScript(this, GetType(), csname1, cstext1.ToString(), true); } }
Swift version of @Nicolas Bonnet 's answer:
var popupWindow: UIWindow?
func showViewController(controller: UIViewController) {
self.popupWindow = UIWindow(frame: UIScreen.mainScreen().bounds)
controller.view.frame = self.popupWindow!.bounds
self.popupWindow!.rootViewController = controller
self.popupWindow!.makeKeyAndVisible()
}
func viewControllerDidRemove() {
self.popupWindow?.removeFromSuperview()
self.popupWindow = nil
}
Don't forget that the window must be a strong property, because the original answer leads to an immediate deallocation of the window
Try this,
$('.popup').click(function(event) {
event.preventDefault();
window.open($(this).attr("href"), "popupWindow", "width=600,height=600,scrollbars=yes");
});
You have to include jQuery reference to work this, here is the working sampe http://jsfiddle.net/a7qJt/
public abstract class SingleFragmentActivity extends Activity {
public static final String FRAGMENT_TAG = "single";
private Fragment fragment;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (savedInstanceState == null) {
fragment = onCreateFragment();
getFragmentManager().beginTransaction()
.add(android.R.id.content, fragment, FRAGMENT_TAG)
.commit();
} else {
fragment = getFragmentManager().findFragmentByTag(FRAGMENT_TAG);
}
}
public abstract Fragment onCreateFragment();
public Fragment getFragment() {
return fragment;
}
}
use
public class ViewCatalogItemActivity extends SingleFragmentActivity {
@Override
public Fragment onCreateFragment() {
return new FragmentWorkShops();
}
}
Set display: table
for parent div and display: table-cell
for children divs
HTML :
<div class="container-fluid">
<div class="row justify-content-center display-as-table">
<div class="col-4 hidden-md-down" id="yellow">
XXXX<br />
XXXX<br />
XXXX<br />
XXXX<br />
XXXX<br />
XXXX<br />vv
XXXX<br />
</div>
<div class="col-10 col-sm-10 col-md-10 col-lg-8 col-xl-8" id="red">
Form Goes Here
</div>
</div>
</div>
CSS:
#yellow {
height: 100%;
background: yellow;
width: 50%;
}
#red {background: red}
.container-fluid {bacgkround: #ccc}
/* this is the part make equal height */
.display-as-table {display: table; width: 100%;}
.display-as-table > div {display: table-cell; float: none;}
The onClick attribute of html tags only takes Javascript but not PHP code. However, you can easily call a PHP function from within the Javascript code by using the JS document.write() function - effectively calling the PHP function by "writing" its call to the browser window: Eg.
onclick="document.write('<?php //call a PHP function here ?>');"
Your example:
<?php
function hello(){
echo "Hello";
}
?>
<input type="button" name="Release" onclick="document.write('<?php hello() ?>');" value="Click to Release">
cast(str_column as int)
I think it would be best for SecureString
dependent functions to encapsulate their dependent logic in an anonymous function for better control over the decrypted string in memory (once pinned).
The implementation for decrypting SecureStrings in this snippet will:
finally
block.This obviously makes it a lot easier to "standardize" and maintain callers vs. relying on less desirable alternatives:
string DecryptSecureString(...)
helper function.Notice here, you have two options:
static T DecryptSecureString<T>
which allows you to access the result of the Func
delegate from the caller (as shown in the DecryptSecureStringWithFunc
test method).static void DecryptSecureString
is simply a "void" version which employ an Action
delegate in cases where you actually don't want/need to return anything (as demonstrated in the DecryptSecureStringWithAction
test method).Example usage for both can be found in the StringsTest
class included.
Strings.cs
using System;
using System.Runtime.InteropServices;
using System.Security;
namespace SecurityUtils
{
public partial class Strings
{
/// <summary>
/// Passes decrypted password String pinned in memory to Func delegate scrubbed on return.
/// </summary>
/// <typeparam name="T">Generic type returned by Func delegate</typeparam>
/// <param name="action">Func delegate which will receive the decrypted password pinned in memory as a String object</param>
/// <returns>Result of Func delegate</returns>
public static T DecryptSecureString<T>(SecureString secureString, Func<string, T> action)
{
var insecureStringPointer = IntPtr.Zero;
var insecureString = String.Empty;
var gcHandler = GCHandle.Alloc(insecureString, GCHandleType.Pinned);
try
{
insecureStringPointer = Marshal.SecureStringToGlobalAllocUnicode(secureString);
insecureString = Marshal.PtrToStringUni(insecureStringPointer);
return action(insecureString);
}
finally
{
//clear memory immediately - don't wait for garbage collector
fixed(char* ptr = insecureString )
{
for(int i = 0; i < insecureString.Length; i++)
{
ptr[i] = '\0';
}
}
insecureString = null;
gcHandler.Free();
Marshal.ZeroFreeGlobalAllocUnicode(insecureStringPointer);
}
}
/// <summary>
/// Runs DecryptSecureString with support for Action to leverage void return type
/// </summary>
/// <param name="secureString"></param>
/// <param name="action"></param>
public static void DecryptSecureString(SecureString secureString, Action<string> action)
{
DecryptSecureString<int>(secureString, (s) =>
{
action(s);
return 0;
});
}
}
}
StringsTest.cs
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System.Security;
namespace SecurityUtils.Test
{
[TestClass]
public class StringsTest
{
[TestMethod]
public void DecryptSecureStringWithFunc()
{
// Arrange
var secureString = new SecureString();
foreach (var c in "UserPassword123".ToCharArray())
secureString.AppendChar(c);
secureString.MakeReadOnly();
// Act
var result = Strings.DecryptSecureString<bool>(secureString, (password) =>
{
return password.Equals("UserPassword123");
});
// Assert
Assert.IsTrue(result);
}
[TestMethod]
public void DecryptSecureStringWithAction()
{
// Arrange
var secureString = new SecureString();
foreach (var c in "UserPassword123".ToCharArray())
secureString.AppendChar(c);
secureString.MakeReadOnly();
// Act
var result = false;
Strings.DecryptSecureString(secureString, (password) =>
{
result = password.Equals("UserPassword123");
});
// Assert
Assert.IsTrue(result);
}
}
}
Obviously, this doesn't prevent abuse of this function in the following manner, so just be careful not to do this:
[TestMethod]
public void DecryptSecureStringWithAction()
{
// Arrange
var secureString = new SecureString();
foreach (var c in "UserPassword123".ToCharArray())
secureString.AppendChar(c);
secureString.MakeReadOnly();
// Act
string copyPassword = null;
Strings.DecryptSecureString(secureString, (password) =>
{
copyPassword = password; // Please don't do this!
});
// Assert
Assert.IsNull(copyPassword); // Fails
}
Happy coding!
I agree with all the above solutions, but to point out whats the root cause of this issue is, that major role player in all above code is this line of code:
dataType:'json'
when you miss this line (which is optional), the data returned from server is treated as full length string (which is default return type). Adding this line of code informs jQuery to convert the possible json string into json object.
Any jQuery ajax calls should specify this line, if expecting json data object.
Actually what made this so confusing is that the Beanstalk people stand behind their very non-standard use of Staging (it comes before development in their diagram, and it's not a mistake!
In my case, I received the HTTP 415 Unsupported Media Type response, since I specified the content type to be TEXT and NOT JSON, so simply changing the type solved the issue. Please check the solution in more detail in the following blog post: https://www.howtodevelop.net/article/20/unsupported-media-type-415-in-aspnet-core-web-api
Another approach that we can do is to :
There's, however, slight difference among all these options which
I found out that
If you do
string URL = Server.MapPath("~");
or
string URL = Server.MapPath("/");
or
string URL = HttpRuntime.AppDomainAppPath;
your URL will display resources in your link like this:
"file:///d:/InetPUB/HOME/Index/bin/Resources/HandlerDoc.htm"
But if you want your URL to show only virtual path not the resources location, you should do
string URL = HttpRuntime.AppDomainAppVirtualPath;
then, your URL is displaying a virtual path to your resources as below
"http://HOME/Index/bin/Resources/HandlerDoc.htm"
Always use either String.valueOf(number)
or Integer.toString(number)
.
Using "" + number is an overhead and does the following:
StringBuilder sb = new StringBuilder();
sb.append("");
sb.append(number);
return sb.toString();
As @user3483203 pointed out, numpy.select is the best approach
Store your conditional statements and the corresponding actions in two lists
conds = [(df['eri_hispanic'] == 1),(df[['eri_afr_amer', 'eri_asian', 'eri_hawaiian', 'eri_nat_amer', 'eri_white']].sum(1).gt(1)),(df['eri_nat_amer'] == 1),(df['eri_asian'] == 1),(df['eri_afr_amer'] == 1),(df['eri_hawaiian'] == 1),(df['eri_white'] == 1,])
actions = ['Hispanic', 'Two Or More', 'A/I AK Native', 'Asian', 'Black/AA', 'Haw/Pac Isl.', 'White']
You can now use np.select using these lists as its arguments
df['label_race'] = np.select(conds,actions,default='Other')
Reference: https://numpy.org/doc/stable/reference/generated/numpy.select.html
With ObsoleteAttribute
you can to show the deprecated method.
Obsolete attribute has three constructor:
[Obsolete]:
is a no parameter constructor and is a default using this attribute.[Obsolete(string message)]:
in this format you can getmessage
of why this method is deprecated.[Obsolete(string message, bool error)]:
in this format message is very explicit buterror
means, in compilation time, compiler must be showing error and cause to fail compiling or not.
if you want to add a global property, you can use:
var styleEl = document.createElement('style'), styleSheet;
document.head.appendChild(styleEl);
styleSheet = styleEl.sheet;
styleSheet.insertRule(".modal { position:absolute; bottom:auto; }", 0);
Try
string Camnr , Klantnr , Ordernr , Bonnr , Volgnr , Omschrijving , Startdatum , Bonprioriteit , Matsoort , Dikte , Draaibaarheid , Draaiomschrijving , Orderleverdatum , Regeltaakkode , Gebruiksvoorkeur , Regelcamprog , Regeltijd , Orderrelease ;
and then
Camnr = Klantnr = Ordernr = Bonnr = Volgnr = Omschrijving = Startdatum = Bonprioriteit = Matsoort = Dikte = Draaibaarheid = Draaiomschrijving = Orderleverdatum = Regeltaakkode = Gebruiksvoorkeur = Regelcamprog = Regeltijd = Orderrelease = "";
I'am posting this answer because many visitors enter here from google for this problem.
string result = this.GetType().GetMethod("Print").Invoke(this, new object[]{"firstParam", 157, "third_Parammmm" } );
when external .dll -instead of this.GetType()
, you might use typeof(YourClass)
.
Also you can use f-string formatting to write integer to file
For appending use following code, for writing once replace 'a' with 'w'.
for i in s_list:
with open('path_to_file','a') as file:
file.write(f'{i}\n')
file.close()
<mvc:annotation-driven />
means that you can define spring beans dependencies without actually having to specify a bunch of elements in XML or implement an interface or extend a base class. For example @Repository
to tell spring that a class is a Dao without having to extend JpaDaoSupport
or some other subclass of DaoSupport. Similarly @Controller
tells spring that the class specified contains methods that will handle Http requests without you having to implement the Controller interface or extend a subclass that implements the controller.
When spring starts up it reads its XML configuration file and looks for <bean
elements within it if it sees something like <bean class="com.example.Foo" />
and Foo was marked up with @Controller
it knows that the class is a controller and treats it as such. By default, Spring assumes that all the classes it should manage are explicitly defined in the beans.XML file.
Component scanning with <context:component-scan base-package="com.mycompany.maventestwebapp" />
is telling spring that it should search the classpath for all the classes under com.mycompany.maventestweapp and look at each class to see if it has a @Controller
, or @Repository
, or @Service
, or @Component
and if it does then Spring will register the class with the bean factory as if you had typed <bean class="..." />
in the XML configuration files.
In a typical spring MVC app you will find that there are two spring configuration files, a file that configures the application context usually started with the Spring context listener.
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
And a Spring MVC configuration file usually started with the Spring dispatcher servlet. For example.
<servlet>
<servlet-name>main</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>main</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
Spring has support for hierarchical bean factories, so in the case of the Spring MVC, the dispatcher servlet context is a child of the main application context. If the servlet context was asked for a bean called "abc" it will look in the servlet context first, if it does not find it there it will look in the parent context, which is the application context.
Common beans such as data sources, JPA configuration, business services are defined in the application context while MVC specific configuration goes not the configuration file associated with the servlet.
Hope this helps.
The basic way is:
printf ("Here are the first 8 chars: %.8s\n", "A string that is more than 8 chars");
The other, often more useful, way is:
printf ("Here are the first %d chars: %.*s\n", 8, 8, "A string that is more than 8 chars");
Here, you specify the length as an int argument to printf(), which treats the '*' in the format as a request to get the length from an argument.
You can also use the notation:
printf ("Here are the first 8 chars: %*.*s\n",
8, 8, "A string that is more than 8 chars");
This is also analogous to the "%8.8s" notation, but again allows you to specify the minimum and maximum lengths at runtime - more realistically in a scenario like:
printf("Data: %*.*s Other info: %d\n", minlen, maxlen, string, info);
The POSIX specification for printf()
defines these mechanisms.
For Swift 3 and XCode 8, this worked. Follow below steps to achieve this:-
{
let layout: UICollectionViewFlowLayout = UICollectionViewFlowLayout()
let width = UIScreen.main.bounds.width
layout.sectionInset = UIEdgeInsets(top: 0, left: 5, bottom: 0, right: 5)
layout.itemSize = CGSize(width: width / 2, height: width / 2)
layout.minimumInteritemSpacing = 0
layout.minimumLineSpacing = 0
collectionView!.collectionViewLayout = layout
}
Place this code into viewDidLoad() function.
As others already suggested, you can enable the "less secure" applications or you can simply switch from ssl
to tls
:
$mailer->Host = 'tls://smtp.gmail.com';
$mailer->SMTPAuth = true;
$mailer->Username = "[email protected]";
$mailer->Password = "***";
$mailer->SMTPSecure = 'tls';
$mailer->Port = 587;
When using tls
there's no need to grant access for less secure applications, just make sure, IMAP is enabled.
Here is what I do using Intl api:
let currentTimeZone = new Intl.DateTimeFormat().resolvedOptions().timeZone; // For example: Australia/Sydney
this will return a time zone name. Pass this parameter to the following function to get the time
let dateTime = new Date(date).toLocaleDateString('en-US',{ timeZone: currentTimeZone, hour12: true});
let time = new Date(date).toLocaleTimeString('en-US',{ timeZone: currentTimeZone, hour12: true});
you can also format the time with moment like this:
moment(new Date(`${dateTime} ${time}`)).format('YYYY-MM-DD[T]HH:mm:ss');
You want
String[] strarray = strlist.toArray(new String[0]);
See here for the documentation and note that you can also call this method in such a way that it populates the passed array, rather than just using it to work out what type to return. Also note that maybe when you print your array you'd prefer
System.out.println(Arrays.toString(strarray));
since that will print the actual elements.
Landed here looking to extract from a tab separated file. Thought I would add.
cat textfile.tsv | cut -f2 -s
Where -f2
extracts the 2, non-zero indexed column, or the second column.
So I found this page while trying to optimize a thing for taking the only key in a dictionary of known length 1 and returning only the key. The below process was the fastest for all dictionaries I tried up to size 700.
I tried 7 different approaches, and found that this one was the best, on my 2014 Macbook with Python 3.6:
def first_5():
for key in biased_dict:
return key
The results of profiling them were:
2226460 / s with first_1
1905620 / s with first_2
1994654 / s with first_3
1777946 / s with first_4
3681252 / s with first_5
2829067 / s with first_6
2600622 / s with first_7
All the approaches I tried are here:
def first_1():
return next(iter(biased_dict))
def first_2():
return list(biased_dict)[0]
def first_3():
return next(iter(biased_dict.keys()))
def first_4():
return list(biased_dict.keys())[0]
def first_5():
for key in biased_dict:
return key
def first_6():
for key in biased_dict.keys():
return key
def first_7():
for key, v in biased_dict.items():
return key
As of CMake 3.1+ the developers strongly discourage users from using file(GLOB
or file(GLOB_RECURSE
to collect lists of source files.
Note: We do not recommend using GLOB to collect a list of source files from your source tree. If no CMakeLists.txt file changes when a source is added or removed then the generated build system cannot know when to ask CMake to regenerate. The CONFIGURE_DEPENDS flag may not work reliably on all generators, or if a new generator is added in the future that cannot support it, projects using it will be stuck. Even if CONFIGURE_DEPENDS works reliably, there is still a cost to perform the check on every rebuild.
See the documentation here.
There are two goods answers ([1], [2]) here on SO detailing the reasons to manually list source files.
It is possible. E.g. with file(GLOB
:
cmake_minimum_required(VERSION 2.8)
file(GLOB helloworld_SRC
"*.h"
"*.cpp"
)
add_executable(helloworld ${helloworld_SRC})
Note that this requires manual re-running of cmake
if a source file is added or removed, since the generated build system does not know when to ask CMake to regenerate, and doing it at every build would increase the build time.
As of CMake 3.12, you can pass the CONFIGURE_DEPENDS
flag to file(GLOB
to automatically check and reset the file lists any time the build is invoked. You would write:
cmake_minimum_required(VERSION 3.12)
file(GLOB helloworld_SRC CONFIGURE_DEPENDS "*.h" "*.cpp")
This at least lets you avoid manually re-running CMake every time a file is added.
If your images are in landscape mode, you can do like this.
from fpdf import FPDF
import os, sys, glob
from tqdm import tqdm
pdf = FPDF('L', 'mm', 'A4')
im_width = 1920
im_height = 1080
aspect_ratio = im_height/im_width
page_width = 297
# page_height = aspect_ratio * page_width
page_height = 200
left_margin = 0
right_margin = 0
# imagelist is the list with all image filenames
for image in tqdm(sorted(glob.glob('test_images/*.png'))):
pdf.add_page()
pdf.image(image, left_margin, right_margin, page_width, page_height)
pdf.output("mypdf.pdf", "F")
print('Conversion completed!')
Here page_width and page_height is the size of 'A4' paper where in landscape its width will 297mm and height will be 210mm; but here I have adjusted the height as per my image. OR you can use either maintaining the aspect ratio as I have commented above for proper scaling of both width and height of the image.
To delete an object by it's id in given array;
const hero = [{'id' : 1, 'name' : 'hero1'}, {'id': 2, 'name' : 'hero2'}];
//remove hero1
const updatedHero = hero.filter(item => item.id !== 1);
As Darin says, you can read from the input stream - but I'd avoid relying on all the data being available in a single go. If you're using .NET 4 this is simple:
MemoryStream target = new MemoryStream();
model.File.InputStream.CopyTo(target);
byte[] data = target.ToArray();
It's easy enough to write the equivalent of CopyTo
in .NET 3.5 if you want. The important part is that you read from HttpPostedFileBase.InputStream
.
For efficient purposes you could check whether the stream returned is already a MemoryStream
:
byte[] data;
using (Stream inputStream = model.File.InputStream)
{
MemoryStream memoryStream = inputStream as MemoryStream;
if (memoryStream == null)
{
memoryStream = new MemoryStream();
inputStream.CopyTo(memoryStream);
}
data = memoryStream.ToArray();
}
This will remove the annoying confirm submission on refresh, the code is self-explanatory:
if (!isset($_SESSION)) {
session_start();
}
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
$_SESSION['postdata'] = $_POST;
unset($_POST);
header("Location: ".$_SERVER[REQUEST_URI]);
exit;
}
if (@$_SESSION['postdata']){
$_POST=$_SESSION['postdata'];
unset($_SESSION['postdata']);
}
What helped me was a look at the source code of the two functions.
Map - wraps the result in an Optional.
public<U> Optional<U> map(Function<? super T, ? extends U> mapper) {
Objects.requireNonNull(mapper);
if (!isPresent())
return empty();
else {
return Optional.ofNullable(mapper.apply(value)); //<--- wraps in an optional
}
}
flatMap - returns the 'raw' object
public<U> Optional<U> flatMap(Function<? super T, Optional<U>> mapper) {
Objects.requireNonNull(mapper);
if (!isPresent())
return empty();
else {
return Objects.requireNonNull(mapper.apply(value)); //<--- returns 'raw' object
}
}
Option 1 is to use display:table-cell
. You need to unfloat the Bootstrap col-* using float:none
..
.center {
display:table-cell;
vertical-align:middle;
float:none;
}
Option 2 is display:flex
to vertical align the row with flexbox:
.row.center {
display: flex;
align-items: center;
}
http://www.bootply.com/7rAuLpMCwr
Vertical centering is very different in Bootstrap 4. See this answer for Bootstrap 4 https://stackoverflow.com/a/41464397/171456
This can also happen in safari if you try a selector with a missing ], for example
$('select[name="something"')
but interestingly, this same jquery selector with a missing bracket will work in chrome.
Use a native SQL query by specifying a @NamedNativeQuery
annotation on the entity class, or by using the EntityManager.createNativeQuery
method. You will need to specify the type of the ResultSet using an appropriate class, or use a ResultSet mapping.
Given worked for me.
document.querySelectorAll(".widget.hover").forEach(obj=>obj.classList.remove("hover"));
$(document).ready(function() {
$('#div2').hide(0);
$('#preview').on('click', function() {
$('#div1').hide(300, function() { // first hide div1
// then show div2
$('#div2').show(300);
});
});
});
You missed #
before div2
I had the same problem & in my case this is what I did
@Html.Partial("~/Views/Cabinets/_List.cshtml", (List<Shop>)ViewBag.cabinets)
and in Partial view
@foreach (Shop cabinet in Model)
{
//...
}
Unless I am misunderstanding the question, I would almost always use $this->get_species because the subclass (in this case dog) could overwrite that method since it does extend it. If the class dog doesn't redefine the method then both ways are functionally equivalent but if at some point in the future you decide you want the get_species method in dog should print "dog" then you would have to go back through all the code and change it.
When you use $this it is actually part of the object which you created and so will always be the most up-to-date as well (if the property being used has changed somehow in the lifetime of the object) whereas using the parent class is calling the static class method.
wget -nd -r -l 2 -A jpg,jpeg,png,gif http://t.co
-nd
: no directories (save all files to the current directory; -P directory
changes the target directory)-r -l 2
: recursive level 2-A
: accepted extensionswget -nd -H -p -A jpg,jpeg,png,gif -e robots=off example.tumblr.com/page/{1..2}
-H
: span hosts (wget doesn't download files from different domains or subdomains by default)-p
: page requisites (includes resources like images on each page)-e robots=off
: execute command robotos=off
as if it was part of .wgetrc
file. This turns off the robot exclusion which means you ignore robots.txt and the robot meta tags (you should know the implications this comes with, take care).Example: Get all .jpg
files from an exemplary directory listing:
$ wget -nd -r -l 1 -A jpg http://example.com/listing/
My advise is: try not to rely on dependencies when you can easily do it with few lines of codes
Here's what you're trying to achieve in 14 lines of code:
fs.isDir = function(dpath) {
try {
return fs.lstatSync(dpath).isDirectory();
} catch(e) {
return false;
}
};
fs.mkdirp = function(dirname) {
dirname = path.normalize(dirname).split(path.sep);
dirname.forEach((sdir,index)=>{
var pathInQuestion = dirname.slice(0,index+1).join(path.sep);
if((!fs.isDir(pathInQuestion)) && pathInQuestion) fs.mkdirSync(pathInQuestion);
});
};
I know this question asked quite long time ago but for the new users of this question. Please read this article where contains complete description on upcasting, downcasting and use of instanceof operator
There's no need to upcast manually, it happens on its own:
Mammal m = (Mammal)new Cat();
equals to Mammal m = new Cat();
But downcasting must always be done manually:
Cat c1 = new Cat();
Animal a = c1; //automatic upcasting to Animal
Cat c2 = (Cat) a; //manual downcasting back to a Cat
Why is that so, that upcasting is automatical, but downcasting must be manual? Well, you see, upcasting can never fail. But if you have a group of different Animals and want to downcast them all to a Cat, then there's a chance, that some of these Animals are actually Dogs, and process fails, by throwing ClassCastException. This is where is should introduce an useful feature called "instanceof", which tests if an object is instance of some Class.
Cat c1 = new Cat();
Animal a = c1; //upcasting to Animal
if(a instanceof Cat){ // testing if the Animal is a Cat
System.out.println("It's a Cat! Now i can safely downcast it to a Cat, without a fear of failure.");
Cat c2 = (Cat)a;
}
For more information please read this article
Once I found an xsd link on the top of the wsdl. Like this wsdl example from the web, you can see a link xsd1. The server has to be running to see it.
<?xml version="1.0"?>
<definitions name="StockQuote"
targetNamespace="http://example.com/stockquote.wsdl"
xmlns:tns="http://example.com/stockquote.wsdl"
xmlns:xsd1="http://example.com/stockquote.xsd"
xmlns:soap="http://schemas.xmlsoap.org/wsdl/soap/"
xmlns="http://schemas.xmlsoap.org/wsdl/">
local_settings.py, for django projects.
*~ for all projects.
JUnit 4 does not have any out-of-the-box mechanism for a test case to get it’s own name (including during setup and teardown).
The above solutions work fine for most cases. However, if you also need to remove all traces of that file (ie sensitive data such as passwords), you will also want to remove it from your entire commit history, as the file could still be retrieved from there.
Here is a solution that removes all traces of the file from your entire commit history, as though it never existed, yet keeps the file in place on your system.
https://help.github.com/articles/remove-sensitive-data/
You can actually skip to step 3 if you are in your local git repository, and don't need to perform a dry run. In my case, I only needed steps 3 and 6, as I had already created my .gitignore file, and was in the repository I wanted to work on.
To see your changes, you may need to go to the GitHub root of your repository and refresh the page. Then navigate through the links to get to an old commit that once had the file, to see that it has now been removed. For me, simply refreshing the old commit page did not show the change.
It looked intimidating at first, but really, was easy and worked like a charm ! :-)
This should work:
quote_df.loc[:,'TVol'] = quote_df['TVol']/TVOL_SCALE
Had similar problems using VS2012 and VS2013.
Adding the following line to <appSettings> in the main web.config worked:
<add key="webpages:Version" value="3.0.0.0" />
If the line was already there but said 2.0.0.0, changing it to 3.0.0.0 worked.
I found the docs for the get api
to be helpful - especially the two sections, Source filtering and Fields: https://www.elastic.co/guide/en/elasticsearch/reference/7.3/docs-get.html#get-source-filtering
They state about source filtering:
If you only need one or two fields from the complete _source, you can use the _source_include & _source_exclude parameters to include or filter out that parts you need. This can be especially helpful with large documents where partial retrieval can save on network overhead
Which fitted my use case perfectly. I ended up simply filtering the source like so (using the shorthand):
{
"_source": ["field_x", ..., "field_y"],
"query": {
...
}
}
FYI, they state in the docs about the fields parameter:
The get operation allows specifying a set of stored fields that will be returned by passing the fields parameter.
It seems to cater for fields that have been specifically stored, where it places each field in an array. If the specified fields haven't been stored it will fetch each one from the _source, which could result in 'slower' retrievals. I also had trouble trying to get it to return fields of type object.
So in summary, you have two options, either though source filtering or [stored] fields.
It's netstat -ano|findstr port no
Result would show process id in last column
The source code provides some basic guidance:
The order in terms of verbosity, from least to most is ERROR, WARN, INFO, DEBUG, VERBOSE. Verbose should never be compiled into an application except during development. Debug logs are compiled in but stripped at runtime. Error, warning and info logs are always kept.
For more detail, Kurtis' answer is dead on. I would just add: Don't log any personally identifiable or private information at INFO
or above (WARN
/ERROR
). Otherwise, bug reports or anything else that includes logging may be polluted.
[project structure]: http://i.stack.imgur.com/RAGX3.jpg
-------------------------------
package beans;
import java.util.Properties;
import java.util.Set;
public class PropertiesBeans {
private Properties properties;
public void setProperties(Properties properties) {
this.properties = properties;
}
public void getProperty(){
Set keys = properties.keySet();
for (Object key : keys) {
System.out.println(key+" : "+properties.getProperty(key.toString()));
}
}
}
----------------------------
package beans;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class Test {
public static void main(String[] args) {
// TODO Auto-generated method stub
ApplicationContext ap = new ClassPathXmlApplicationContext("resource/spring.xml");
PropertiesBeans p = (PropertiesBeans)ap.getBean("p");
p.getProperty();
}
}
----------------------------
- driver.properties
Driver = com.mysql.jdbc.Driver
url = jdbc:mysql://localhost:3306/test
username = root
password = root
----------------------------
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:util="http://www.springframework.org/schema/util"
xsi:schemaLocation="
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-3.0.xsd">
<bean id="p" class="beans.PropertiesBeans">
<property name="properties">
<util:properties location="classpath:resource/driver.properties"/>
</property>
</bean>
</beans>
Best way to create a function like this for wait in milli seconds, this function will wait for milliseconds provided in the argument:
function waitSeconds(iMilliSeconds) {_x000D_
var counter= 0_x000D_
, start = new Date().getTime()_x000D_
, end = 0;_x000D_
while (counter < iMilliSeconds) {_x000D_
end = new Date().getTime();_x000D_
counter = end - start;_x000D_
}_x000D_
}
_x000D_
In bootstrap 4, you can add a .text-truncate
class to truncate the text with an ellipsis.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" rel="stylesheet" />_x000D_
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js"></script>_x000D_
_x000D_
<!-- Inline level -->_x000D_
<span class="d-inline-block text-truncate" style="max-width: 250px;">_x000D_
The quick brown fox jumps over the lazy dog._x000D_
</span>
_x000D_
Try the command line tool expand
.
expand -i -t 4 input | sponge output
where
-i
is used to expand only leading tabs on each line;-t 4
means that each tab will be converted to 4 whitespace chars (8 by default).sponge
is from the moreutils
package, and avoids clearing the input file.Finally, you can use gexpand
on OSX, after installing coreutils
with Homebrew (brew install coreutils
).
Might this be the download you are looking for?
First thing to do is run this:
SHOW GRANTS;
You will quickly see you were assigned the anonymous user to authenticate into mysql.
Instead of logging into mysql with
mysql
login like this:
mysql -uroot
By default, root@localhost has all rights and no password.
If you cannot login as root without a password, do the following:
Step 01) Add the two options in the mysqld section of my.ini:
[mysqld]
skip-grant-tables
skip-networking
Step 02) Restart mysql
net stop mysql
<wait 10 seconds>
net start mysql
Step 03) Connect to mysql
mysql
Step 04) Create a password from root@localhost
UPDATE mysql.user SET password=password('whateverpasswordyoulike')
WHERE user='root' AND host='localhost';
exit
Step 05) Restart mysql
net stop mysql
<wait 10 seconds>
net start mysql
Step 06) Login as root with password
mysql -u root -p
You should be good from there.
I just went through the character map to get these. They are all in Calibri.
Number Name HTML Code Appearance ------ -------------------- --------- ---------- U+2000 En Quad   " " U+2001 Em Quad   " " U+2002 En Space   " " U+2003 Em Space   " " U+2004 Three-Per-Em Space   " " U+2005 Four-Per-Em Space   " " U+2006 Six-Per-Em Space   " " U+2007 Figure Space   " " U+2008 Punctuation Space   " " U+2009 Thin Space   " " U+200A Hair Space   " " U+200B Zero-Width Space ​ "" U+200C Zero Width Non-Joiner ‌ "" U+200D Zero Width Joiner ‍ "" U+200E Left-To-Right Mark ‎ "" U+200F Right-To-Left Mark ‏ "" U+202F Narrow No-Break Space   " "
From You don't know the difference between HTTP and REST
So REST architecture and HTTP 1.1 protocol are independent from each other, but the HTTP 1.1 protocol was built to be the ideal protocol to follow the principles and constraints of REST. One way to look at the relationship between HTTP and REST is, that REST is the design, and HTTP 1.1 is an implementation of that design.
On SQL Server specifically:
SELECT DATALENGTH(Remarks) AS FIELDSIZE FROM mytable
Change this:
<div class=fetch_results>
To this:
<div id="fetch_results">
Then the following should work:
$("#fetch_results input").each(function() {
this.value = "";
})?
Use HH instead of hh in formatter string
Consider this question asked at StackOverflow today:
A good test and a practical example is what happens in the above scenario...
The developer used the name of the JavaScript function in one of his variables.
What's the problem with the code?
The code only works the first time the user clicks the button.
What's the solution?
Add the var
keyword before the variable name.
If using XML configuration you can use
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:security="http://www.springframework.org/schema/security">
<security:http>
<security:headers>
<security:frame-options disabled="true"></security:frame-options>
</security:headers>
</security:http>
</beans>
I don't know why but for me the solution proposed by Marius Stanescu is breaking the specificity of col (a col-md-3 followed by a col-md-4 will take all of the twelve row)
I found another working solution :
.bottom-column
{
display: inline-block;
vertical-align: middle;
float: none;
}
Perhaps "the most pythonic way" should include handling the case where list1 and list2 are not the same size. Applying some of these methods will quietly give you an answer. The numpy approach will let you know, most likely with a ValueError.
Example:
import numpy as np
>>> list1 = [ 1, 2 ]
>>> list2 = [ 1, 2, 3]
>>> list3 = [ 1 ]
>>> [a + b for a, b in zip(list1, list2)]
[2, 4]
>>> [a + b for a, b in zip(list1, list3)]
[2]
>>> a = np.array (list1)
>>> b = np.array (list2)
>>> a+b
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: operands could not be broadcast together with shapes (2) (3)
Which result might you want if this were in a function in your problem?
If you want to access redis
from the host (127.0.0.1), you have to use the ports
command.
redis:
build:
context: .
dockerfile: Dockerfile-redis
ports:
- "6379:6379"
Nothing worked for me except, I loggined using pgAdmin4 and on the Dashboard I disconnected all connections except pgAdmin4 and then was able to rename by right lick on the database and properties and typed new name.
You can change it in iOS without opening Xcode by editing file *project/ios/Runner/info.plist. Set <key>CFBundleDisplayName</key>
to the string that you want as your name.
For Android, change the app name from the Android folder, in the AndroidManifest.xml file, android/app/src/main. Let the android label refer to the name you prefer, for example,
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
<application
android:label="test"
// The rest of the code
</application>
</manifest>
I found that the formal way to do this is as follows:
Just install two (or more, using their installers) versions of Python on Windows 7 (for me work with 3.3 and 2.7).
Follow the instuctions below, changing the parameters for your needs.
Create the following environment variable (to default on double click):
Name: PY_PYTHON
Value: 3
To launch a script in a particular interpreter, add the following shebang (beginning of script):
#! python2
To execute a script using a specific interpreter, use the following prompt command:
> py -2 MyScript.py
To launch a specific interpreter:
> py -2
To launch the default interpreter (defined by the PY_PYTHON variable):
> py
Resources
Documentation: Using Python on Windows
PEP 397 - Python launcher for Windows
You can create folder using the following Java code:
File dir = new File("nameoffolder");
dir.mkdir();
By executing above you will have folder 'nameoffolder' in current folder.
The same as an int:
float f = 6;
Also here's how to programmatically convert from an int to a float, and a single in C# is the same as a float:
int i = 8;
float f = Convert.ToSingle(i);
Or you can just cast an int to a float:
float f = (float)i;
Use properties file. Here is a good start: http://www.mkyong.com/java/java-properties-file-examples/
Try this:
hex_str = "0xAD4"
hex_int = int(hex_str, 16)
new_int = hex_int + 0x200
print hex(new_int)
If you don't like the 0x
in the beginning, replace the last line with
print hex(new_int)[2:]
It depends how many rows are returned in $results
, and how many columns there are in $row
?
I've done this before. You can just create a new exception and grab the stack trace on it without throwing it, then examine the stack trace. As the other answer says though, it's extremely costly--don't do it in a tight loop.
I've done it before for a logging utility on an app where performance didn't matter much (Performance rarely matters much at all, actually--as long as you display the result to an action such as a button click quickly).
It was before you could get the stack trace, exceptions just had .printStackTrace() so I had to redirect System.out to a stream of my own creation, then (new Exception()).printStackTrace(); Redirect System.out back and parse the stream. Fun stuff.
The struct's name is ReducedForm
; you need to make an object (instance of the struct
or class
) and use that. Do this:
ReducedForm MyReducedForm;
MyReducedForm.iSimplifiedNumerator = iNumerator/iGreatCommDivisor;
MyReducedForm.iSimplifiedDenominator = iDenominator/iGreatCommDivisor;
You may have as many levels of Object hierarchy as you want, as long you declare an Object as being a property of another parent Object. Pay attention to the commas on each level, that's the tricky part. Don't use commas after the last element on each level:
{el1, el2, {el31, el32, el33}, {el41, el42}}
var MainObj = {_x000D_
_x000D_
prop1: "prop1MainObj",_x000D_
_x000D_
Obj1: {_x000D_
prop1: "prop1Obj1",_x000D_
prop2: "prop2Obj1", _x000D_
Obj2: {_x000D_
prop1: "hey you",_x000D_
prop2: "prop2Obj2"_x000D_
}_x000D_
},_x000D_
_x000D_
Obj3: {_x000D_
prop1: "prop1Obj3",_x000D_
prop2: "prop2Obj3"_x000D_
},_x000D_
_x000D_
Obj4: {_x000D_
prop1: true,_x000D_
prop2: 3_x000D_
} _x000D_
};_x000D_
_x000D_
console.log(MainObj.Obj1.Obj2.prop1);
_x000D_
global static variables are initialized at compile-time unlike automatic
You're "setting" the value of that variable/attribute. Not overriding or overloading it. Your code is very, very common and normal.
All of these terms ("set", "override", "overload") have specific meanings. Override and Overload are about polymorphism (subclassing).
From http://en.wikipedia.org/wiki/Object-oriented_programming :
Polymorphism allows the programmer to treat derived class members just like their parent class' members. More precisely, Polymorphism in object-oriented programming is the ability of objects belonging to different data types to respond to method calls of methods of the same name, each one according to an appropriate type-specific behavior. One method, or an operator such as +, -, or *, can be abstractly applied in many different situations. If a Dog is commanded to speak(), this may elicit a bark(). However, if a Pig is commanded to speak(), this may elicit an oink(). They both inherit speak() from Animal, but their derived class methods override the methods of the parent class; this is Overriding Polymorphism. Overloading Polymorphism is the use of one method signature, or one operator such as "+", to perform several different functions depending on the implementation. The "+" operator, for example, may be used to perform integer addition, float addition, list concatenation, or string concatenation. Any two subclasses of Number, such as Integer and Double, are expected to add together properly in an OOP language. The language must therefore overload the addition operator, "+", to work this way. This helps improve code readability. How this is implemented varies from language to language, but most OOP languages support at least some level of overloading polymorphism.
$data = json_decode($json, true);
echo $data[0]["c_name"]; // "John"
$data = json_decode($json);
echo $data[0]->c_name; // "John"
Why don't you introduce a service layer. then your controller will be lean and more readable, then your all controller functions will be pure actions. you can decompose business logic as you much as you need within service layer . code reusability is hight . no impact on models and repositories.
int main();
This is a simple declaration. It cannot take any command line arguments.
int main(int argc, char* argv[]);
This declaration is used when your program must take command-line arguments. When run like such:
myprogram arg1 arg2 arg3
argc
, or Argument Count, will be set to 4 (four arguments), and argv
, or Argument Vectors, will be populated with string pointers to "myprogram", "arg1", "arg2", and "arg3". The program invocation (myprogram
) is included in the arguments!
Alternatively, you could use:
int main(int argc, char** argv);
This is also valid.
There is another parameter you can add:
int main (int argc, char *argv[], char *envp[])
The envp
parameter also contains environment variables. Each entry follows this format:
VARIABLENAME=VariableValue
like this:
SHELL=/bin/bash
The environment variables list is null-terminated.
IMPORTANT: DO NOT use any argv
or envp
values directly in calls to system()
! This is a huge security hole as malicious users could set environment variables to command-line commands and (potentially) cause massive damage. In general, just don't use system()
. There is almost always a better solution implemented through C libraries.
This works for 3 bytes. Live code is here
def twos_compliment(byte_arr):
a = byte_arr[0]; b = byte_arr[1]; c = byte_arr[2]
out = ((a<<16)&0xff0000) | ((b<<8)&0xff00) | (c&0xff)
neg = (a & (1<<7) != 0) # first bit of a is the "signed bit." if it's a 1, then the value is negative
if neg: out -= (1 << 24)
print(hex(a), hex(b), hex(c), neg, out)
return out
twos_compliment([0x00, 0x00, 0x01])
>>> 1
twos_compliment([0xff,0xff,0xff])
>>> -1
twos_compliment([0b00010010, 0b11010110, 0b10000111])
>>> 1234567
twos_compliment([0b11101101, 0b00101001, 0b01111001])
>>> -1234567
twos_compliment([0b01110100, 0b11001011, 0b10110001])
>>> 7654321
twos_compliment([0b10001011, 0b00110100, 0b01001111])
>>> -7654321
I'll try and explain it as simple as possible. So there is no guarantee of the accuracy of the actual terms.
Session is where to initiate the connectivity to AWS services. E.g. following is default session that uses the default credential profile(e.g. ~/.aws/credentials, or assume your EC2 using IAM instance profile )
sqs = boto3.client('sqs')
s3 = boto3.resource('s3')
Because default session is limit to the profile or instance profile used, sometimes you need to use the custom session to override the default session configuration (e.g. region_name, endpoint_url, etc. ) e.g.
# custom resource session must use boto3.Session to do the override
my_west_session = boto3.Session(region_name = 'us-west-2')
my_east_session = boto3.Session(region_name = 'us-east-1')
backup_s3 = my_west_session.resource('s3')
video_s3 = my_east_session.resource('s3')
# you have two choices of create custom client session.
backup_s3c = my_west_session.client('s3')
video_s3c = boto3.client("s3", region_name = 'us-east-1')
Resource : This is the high-level service class recommended to be used. This allows you to tied particular AWS resources and passes it along, so you just use this abstraction than worry which target services are pointed to. As you notice from the session part, if you have a custom session, you just pass this abstract object than worrying about all custom regions,etc to pass along. Following is a complicated example E.g.
import boto3
my_west_session = boto3.Session(region_name = 'us-west-2')
my_east_session = boto3.Session(region_name = 'us-east-1')
backup_s3 = my_west_session.resource("s3")
video_s3 = my_east_session.resource("s3")
backup_bucket = backup_s3.Bucket('backupbucket')
video_bucket = video_s3.Bucket('videobucket')
# just pass the instantiated bucket object
def list_bucket_contents(bucket):
for object in bucket.objects.all():
print(object.key)
list_bucket_contents(backup_bucket)
list_bucket_contents(video_bucket)
Client is a low level class object. For each client call, you need to explicitly specify the targeting resources, the designated service target name must be pass long. You will lose the abstraction ability.
For example, if you only deal with the default session, this looks similar to boto3.resource.
import boto3
s3 = boto3.client('s3')
def list_bucket_contents(bucket_name):
for object in s3.list_objects_v2(Bucket=bucket_name) :
print(object.key)
list_bucket_contents('Mybucket')
However, if you want to list objects from a bucket in different regions, you need to specify the explicit bucket parameter required for the client.
import boto3
backup_s3 = my_west_session.client('s3',region_name = 'us-west-2')
video_s3 = my_east_session.client('s3',region_name = 'us-east-1')
# you must pass boto3.Session.client and the bucket name
def list_bucket_contents(s3session, bucket_name):
response = s3session.list_objects_v2(Bucket=bucket_name)
if 'Contents' in response:
for obj in response['Contents']:
print(obj['key'])
list_bucket_contents(backup_s3, 'backupbucket')
list_bucket_contents(video_s3 , 'videobucket')
XmlReaderSettings _configsettings = new XmlReaderSettings();
_configsettings.IgnoreComments = true;
XmlReader _configreader = XmlReader.Create(ConfigFilePath, _configsettings);
XmlDocument doc_config = new XmlDocument();
doc_config.Load(_configreader);
_configreader.Close();
foreach (XmlNode RootName in doc_config.DocumentElement.ChildNodes)
{
if (RootName.LocalName == "appSettings")
{
if (RootName.HasChildNodes)
{
foreach (XmlNode _child in RootName.ChildNodes)
{
if (_child.Attributes["key"].Value == "HostName")
{
if (_child.Attributes["value"].Value == "false")
_child.Attributes["value"].Value = "true";
}
}
}
}
}
doc_config.Save(ConfigFilePath);
An <input>
's width is generated from its size
attribute. The default size
is what's driving the auto width.
You could try width:100%
as illustrated in my example below.
Doesn't fill width:
<form action='' method='post' style='width:200px;background:khaki'>
<input style='width:auto' />
</form>
Fills width:
<form action='' method='post' style='width:200px;background:khaki'>
<input style='width:100%' />
</form>
Smaller size, smaller width:
<form action='' method='post' style='width:200px;background:khaki'>
<input size='5' />
</form>
UPDATE
Here's the best I could do after a few minutes. It's 1px off in FF, Chrome, and Safari, and perfect in IE. (The problem is #^&* IE applies borders differently than everyone else so it's not consistent.)
<div style='padding:30px;width:200px;background:red'>
<form action='' method='post' style='width:200px;background:blue;padding:3px'>
<input size='' style='width:100%;margin:-3px;border:2px inset #eee' />
<br /><br />
<input size='' style='width:100%' />
</form>
</div>
InputMethodManager imm = (InputMethodManager)GetSystemService(Context.InputMethodService);
imm.ShowSoftInput(_enterPin.FindFocus(), 0);
*This is for Android.xamarin and FindFocus()-it searches for the view in hierarchy rooted at this view that currently has focus,as i have _enterPin.RequestFocus() before the above code thus it shows keyboard for _enterPin EditText *
You had thead
in your selector, but there is no thead
in your table. Also you had your selectors backwards. As you mentioned above, you wanted to be adding the tr
class to the th
, not vice-versa (although your comment seems to contradict what you wrote up above).
$('tr th').each(function(index){ if($('tr td').eq(index).attr('class') != ''){ // get the class of the td var tdClass = $('tr td').eq(index).attr('class'); // add it to this th $(this).addClass(tdClass ); } });
Here is code for secure, easy, but a little bit more expensive session identifiers.
import java.security.SecureRandom;
import java.math.BigInteger;
public final class SessionIdentifierGenerator
{
private SecureRandom random = new SecureRandom();
public String nextSessionId()
{
return new BigInteger(130, random).toString(32);
}
}
gcc will typically use logical shifts on unsigned variables and for left-shifts on signed variables. The arithmetic right shift is the truly important one because it will sign extend the variable.
gcc will will use this when applicable, as other compilers are likely to do.
I suppose you want form based authentication using deployment descriptors and j_security_check
.
You can also do this in JSF by just using the same predefinied field names j_username
and j_password
as demonstrated in the tutorial.
E.g.
<form action="j_security_check" method="post">
<h:outputLabel for="j_username" value="Username" />
<h:inputText id="j_username" />
<br />
<h:outputLabel for="j_password" value="Password" />
<h:inputSecret id="j_password" />
<br />
<h:commandButton value="Login" />
</form>
You could do lazy loading in the User
getter to check if the User
is already logged in and if not, then check if the Principal
is present in the request and if so, then get the User
associated with j_username
.
package com.stackoverflow.q2206911;
import java.io.IOException;
import java.security.Principal;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.context.FacesContext;
@ManagedBean
@SessionScoped
public class Auth {
private User user; // The JPA entity.
@EJB
private UserService userService;
public User getUser() {
if (user == null) {
Principal principal = FacesContext.getCurrentInstance().getExternalContext().getUserPrincipal();
if (principal != null) {
user = userService.find(principal.getName()); // Find User by j_username.
}
}
return user;
}
}
The User
is obviously accessible in JSF EL by #{auth.user}
.
To logout do a HttpServletRequest#logout()
(and set User
to null!). You can get a handle of the HttpServletRequest
in JSF by ExternalContext#getRequest()
. You can also just invalidate the session altogether.
public String logout() {
FacesContext.getCurrentInstance().getExternalContext().invalidateSession();
return "login?faces-redirect=true";
}
For the remnant (defining users, roles and constraints in deployment descriptor and realm), just follow the Java EE 6 tutorial and the servletcontainer documentation the usual way.
Update: you can also use the new Servlet 3.0 HttpServletRequest#login()
to do a programmatic login instead of using j_security_check
which may not per-se be reachable by a dispatcher in some servletcontainers. In this case you can use a fullworthy JSF form and a bean with username
and password
properties and a login
method which look like this:
<h:form>
<h:outputLabel for="username" value="Username" />
<h:inputText id="username" value="#{auth.username}" required="true" />
<h:message for="username" />
<br />
<h:outputLabel for="password" value="Password" />
<h:inputSecret id="password" value="#{auth.password}" required="true" />
<h:message for="password" />
<br />
<h:commandButton value="Login" action="#{auth.login}" />
<h:messages globalOnly="true" />
</h:form>
And this view scoped managed bean which also remembers the initially requested page:
@ManagedBean
@ViewScoped
public class Auth {
private String username;
private String password;
private String originalURL;
@PostConstruct
public void init() {
ExternalContext externalContext = FacesContext.getCurrentInstance().getExternalContext();
originalURL = (String) externalContext.getRequestMap().get(RequestDispatcher.FORWARD_REQUEST_URI);
if (originalURL == null) {
originalURL = externalContext.getRequestContextPath() + "/home.xhtml";
} else {
String originalQuery = (String) externalContext.getRequestMap().get(RequestDispatcher.FORWARD_QUERY_STRING);
if (originalQuery != null) {
originalURL += "?" + originalQuery;
}
}
}
@EJB
private UserService userService;
public void login() throws IOException {
FacesContext context = FacesContext.getCurrentInstance();
ExternalContext externalContext = context.getExternalContext();
HttpServletRequest request = (HttpServletRequest) externalContext.getRequest();
try {
request.login(username, password);
User user = userService.find(username, password);
externalContext.getSessionMap().put("user", user);
externalContext.redirect(originalURL);
} catch (ServletException e) {
// Handle unknown username/password in request.login().
context.addMessage(null, new FacesMessage("Unknown login"));
}
}
public void logout() throws IOException {
ExternalContext externalContext = FacesContext.getCurrentInstance().getExternalContext();
externalContext.invalidateSession();
externalContext.redirect(externalContext.getRequestContextPath() + "/login.xhtml");
}
// Getters/setters for username and password.
}
This way the User
is accessible in JSF EL by #{user}
.
If you really need maximum copying performance (which you might not), use neither of them.
There's a lot that can be done to optimize memory copying - even more if you're willing to use multiple threads/cores for it. See, for example:
What's missing/sub-optimal in this memcpy implementation?
both the question and some of the answers have suggested implementations or links to implementations.
You must use the column names and then set the values to insert (both ? marks):
//insert 1st row
String inserting = "INSERT INTO employee(emp_name ,emp_address) values(?,?)";
System.out.println("insert " + inserting);//
PreparedStatement ps = con.prepareStatement(inserting);
ps.setString(1, "hans");
ps.setString(2, "germany");
ps.executeUpdate();
For SQL Server 2000:
SELECT su.name,so.name,so.crdate,*
FROM sysobjects so JOIN sysusers su
ON so.uid = su.uid
WHERE xtype='U'
ORDER BY so.name
I am very surprised that nobody here has mentioned the problem of connection and read timeout. It could happen (especially on Android and/or with some crappy network connectivity) that the request will hang and wait forever.
The following code (which also uses Apache IO Commons) takes this into account, and waits max. 5 seconds until it fails:
public static byte[] downloadFile(URL url)
{
try {
URLConnection conn = url.openConnection();
conn.setConnectTimeout(5000);
conn.setReadTimeout(5000);
conn.connect();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
IOUtils.copy(conn.getInputStream(), baos);
return baos.toByteArray();
}
catch (IOException e)
{
// Log error and return null, some default or throw a runtime exception
}
}
I think you missed a key point in the documentation for .add()
Mutates the original moment by adding time.
You appear to be treating it as a function that returns the immutable result. Easy mistake to make. :)
If you use the return value, it is the same actual object as the one you started with. It's just returned as a convenience for method chaining.
You can work around this behavior by cloning the moment, as described here.
Also, you cannot just use ==
to test. You could format each moment to the same output and compare those, or you could just use the .isSame()
method.
Your code is now:
var timestring1 = "2013-05-09T00:00:00Z";
var timestring2 = "2013-05-09T02:00:00Z";
var startdate = moment(timestring1);
var expected_enddate = moment(timestring2);
var returned_endate = moment(startdate).add(2, 'hours'); // see the cloning?
returned_endate.isSame(expected_enddate) // true
Passing arguments by bundle is restricted to some data types. But you can transfer any data to your fragment this way:
In your fragment create a public method like this
public void passData(Context context, List<LexItem> list, int pos) {
mContext = context;
mLexItemList = list;
mIndex = pos;
}
and in your activity call passData() with all your needed data types after instantiating the fragment
WebViewFragment myFragment = new WebViewFragment();
myFragment.passData(getApplicationContext(), mLexItemList, index);
FragmentManager fm = getSupportFragmentManager();
FragmentTransaction ft = fm.beginTransaction();
ft.add(R.id.my_fragment_container, myFragment);
ft.addToBackStack(null);
ft.commit();
Remark: My fragment extends "android.support.v4.app.Fragment", therefore I have to use "getSupportFragmentManager()". Of course, this principle will work also with a fragment class extending "Fragment", but then you have to use "getFragmentManager()".
It is debatable as to whether you should use String or use Char[] for this purpose because both have their advantages and disadvantages. It depends on what the user needs.
Since Strings in Java are immutable, whenever some tries to manipulate your string it creates a new Object and the existing String remains unaffected. This could be seen as an advantage for storing a password as a String, but the object remains in memory even after use. So if anyone somehow got the memory location of the object, that person can easily trace your password stored at that location.
Char[] is mutable, but it has the advantage that after its usage the programmer can explicitly clean the array or override values. So when it's done being used it is cleaned and no one could ever know about the information you had stored.
Based on the above circumstances, one can get an idea whether to go with String or to go with Char[] for their requirements.
One of the latest XAMPP releases (XAMPP for Windows v5.6.11 (PHP 5.6.11) for sure, probably some earlier versions too) does not have the Control Panel with the "Svc" checkbox that allows to install Apache and MySQL as a service.
Go to your XAMPP/Apache directory instead (typically C:/xampp/apache
) and run apache_installservice.bat as an administrator. There is also apache_uninstallservice.bat for uninstall.
To run MySQL as a service. Do it the same way - the location is xampp/mysql
and batch files are: mysql_installservice.bat for service installation and mysql_uninstallservice.bat for removing the MySQL service.
You can check if they were installed or not by going to services manager window (press Windows + R and type: services.msc) and check if you have Apache service (I had Apache2.4) running and set to startup automatically. The MySQL service name is just: mysql.
db.collection.findOne().sort({age:-1}) //get Max without need for limit(1)
I want to add an additional piece of information her about the difference in performance.
We already know that due to the fact that ArrayList
implementation is backed by an Object[]
it's supports random access and dynamic resizing and LinkedList
implementation uses references to head and tail to navigate it. It has no random access capabilities, but it supports dynamic resizing as well.
The first thing is that with an ArrayList, you can immediately access the index, whereas with a LinkedList, you have iterate down the object chain.
Secondly, inserting into ArrayList is generally slower because it has to grow once you hit its boundaries. It will have to create a new bigger array, and copy data from the original one.
But the interesting thing is that when you create an ArrayList that is already huge enough to fit all your inserts it will obviously not involve any array copying operations. Adding to it will be even faster than with LinkedList because LinkedList will have to deal with its pointers, while huge ArrayList just sets value at given index.
Check out for more ArrayList and LinkedList differences.
You can just as easily access each element in the list using e.g. path[[1]]
. You can't put a set of matrices into an atomic vector and access each element. A matrix is an atomic vector with dimension attributes. I would use the list structure returned by split
, it's what it was designed for. Each list element can hold data of different types and sizes so it's very versatile and you can use *apply
functions to further operate on each element in the list. Example below.
# For reproducibile data
set.seed(1)
# Make some data
userid <- rep(1:2,times=4)
data1 <- replicate(8 , paste( sample(letters , 3 ) , collapse = "" ) )
data2 <- sample(10,8)
df <- data.frame( userid , data1 , data2 )
# Split on userid
out <- split( df , f = df$userid )
#$`1`
# userid data1 data2
#1 1 gjn 3
#3 1 yqp 1
#5 1 rjs 6
#7 1 jtw 5
#$`2`
# userid data1 data2
#2 2 xfv 4
#4 2 bfe 10
#6 2 mrx 2
#8 2 fqd 9
Access each element using the [[
operator like this:
out[[1]]
# userid data1 data2
#1 1 gjn 3
#3 1 yqp 1
#5 1 rjs 6
#7 1 jtw 5
Or use an *apply
function to do further operations on each list element. For instance, to take the mean of the data2
column you could use sapply like this:
sapply( out , function(x) mean( x$data2 ) )
# 1 2
#3.75 6.25
You can make use of PieceLabel plugin for Chart.js.
{ pieceLabel: { mode: 'percentage', precision: 2 } }
The plugin appears to have a new location (and name): Demo Docs.
There are 3 solutions available for these.
1) Enable remote login using below command - sudo systemsetup -setremotelogin on
2) In Mac, go to System Preference -> Sharing -> enable Remote Login that's it. 100% working solution
3) Final and most important solution is - Check your private area network connection . Sometime remote login isn't allow inside the local area network.
Kindly try to connect your machine using personal network like mobile network, Hotspot etc.
I used a BoxLayout
and set its second parameter as BoxLayout.Y_AXIS
and it worked for me:
panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS));
Here's a quick code snippet that will find the first non-empty line in a string:
string line1;
while (
((line1 = sr.ReadLine()) != null) &&
((line1 = line1.Trim()).Length == 0)
)
{ /* Do nothing - just trying to find first non-empty line*/ }
if(line1 == null){ /* Error - no non-empty lines in string */ }
In our case it was simply a case of giving write rights in github. Initially the user had only read rights and it was giving this error.
In my case, when i upgrade vs project to angular 10, I had this errors.
Angular cli creates tsconfig.json
, tsconfig.base.json
and tsconfig.app.json
when i delete tsconfig.json and rename tsconfig.base.json to tsconfig.ts all things will Ok.
you must also change extends inside tsconfig.app.json to tsconfig.json
I had pip
referring by default to pip3, which made me download the libs for python3. On the contrary I launched the shell as python
(which opened python 2) and the library wasn't installed there obviously.
Once I matched the names pip3 -> python3, pip -> python (2) all worked.
Here is one of the most efficient way, it works smoothly:
https://github.com/MikeOrtiz/TouchImageView
Place TouchImageView.java in your project. It can then be used the same as
ImageView
.
Example:
TouchImageView img = (TouchImageView) findViewById(R.id.img);
If you are using TouchImageView
in xml, then you must provide the full package
name, because it is a custom view.
Example:
<com.example.touch.TouchImageView
android:id="@+id/img”
android:layout_width="match_parent"
android:layout_height="match_parent" />
Maybe something like this?
$('.ui-state-default:first').addClass('classForCancelButton');
For 32-bit systems:
fprintf(stdout, "%u\n", (unsigned)time(NULL));
For 64-bit systems:
fprintf(stdout, "%lu\n", (unsigned long)time(NULL));
Pass the id and hold into a variable and pass the variable where ever you want.
var temp = $('select[name=ID Name]').val();
From official documentation :
To enable Google to crawl your app content and allow users to enter your app from search results, you must add intent filters for the relevant activities in your app manifest. These intent filters allow deep linking to the content in any of your activities. For example, the user might click on a deep link to view a page within a shopping app that describes a product offering that the user is searching for.
Using this link Enabling Deep Links for App Content you'll see how to use it.
And using this Test Your App Indexing Implementation how to test it.
The following XML snippet shows how you might specify an intent filter in your manifest for deep linking.
<activity
android:name="com.example.android.GizmosActivity"
android:label="@string/title_gizmos" >
<intent-filter android:label="@string/filter_title_viewgizmos">
<action android:name="android.intent.action.VIEW" />
<category android:name="android.intent.category.DEFAULT" />
<category android:name="android.intent.category.BROWSABLE" />
<!-- Accepts URIs that begin with "http://www.example.com/gizmos” -->
<data android:scheme="http"
android:host="www.example.com"
android:pathPrefix="/gizmos" />
<!-- note that the leading "/" is required for pathPrefix-->
<!-- Accepts URIs that begin with "example://gizmos” -->
<data android:scheme="example"
android:host="gizmos" />
</intent-filter>
</activity>
To test via Android Debug Bridge
$ adb shell am start
-W -a android.intent.action.VIEW
-d <URI> <PACKAGE>
$ adb shell am start
-W -a android.intent.action.VIEW
-d "example://gizmos" com.example.android
Just becuase your class object has no variables does not mean that it is nothing. Declaring and object and creating an object are two different things. Look and see if you are setting/creating the object.
Take for instance the dictionary object - just because it contains no variables does not mean it has not been created.
Sub test()
Dim dict As Object
Set dict = CreateObject("scripting.dictionary")
If Not dict Is Nothing Then
MsgBox "Dict is something!" '<--- This shows
Else
MsgBox "Dict is nothing!"
End If
End Sub
However if you declare an object but never create it, it's nothing.
Sub test()
Dim temp As Object
If Not temp Is Nothing Then
MsgBox "Temp is something!"
Else
MsgBox "Temp is nothing!" '<---- This shows
End If
End Sub
You can try using Scanner if you are using JDK5 or higher.
Scanner scan = new Scanner(file);
scan.useDelimiter("\\Z");
String content = scan.next();
Or you can also use Guava
String data = Files.toString(new File("path.txt"), Charsets.UTF8);
I just want one result
implies that you expect only one row to be returned. So either adapt your query, e.g.
SELECT player_id
FROM players p
WHERE CONCAT(p.first_name, ' ', p.last_name) = ?
LIMIT 0, 1
(and then use getSingleResult()
as recommended by AdrienBrault) or fetch rows as an array and access the first item:
// ...
$players = $query->getArrayResult();
$myPlayer = $players[0];
An alternate solution rather than closing all apps that might be locking the directory as just about every other answer says to do, would be to use a utility that will unlock the files/directory without closing everything. (I hate needing to restart Visual Studio)
LockHunter is the one that I use: https://lockhunter.com/ There are likely others out there as well, but this one has worked great for me.
You can use display: flex to position an element to the bottom, but I do not think you want to use flex in this case, as it will affect all of your elements.
To position an element to the bottom using flex try this:
.container {
display: flex;
}
.button {
align-self: flex-end;
}
Your best bet is to set position: absolute to the button and set it to bottom: 0
, or you can place the button outside the container and use negative transform: translateY(-100%)
to bring it in the container like this:
.content {
height: 400px;
background: #000;
color: #fff;
}
.button {
transform: translateY(-100%);
display: inline-block;
}
Check this JSFiddle
Many people will suggest you use MERGE
, but I caution you against it. By default, it doesn't protect you from concurrency and race conditions any more than multiple statements, but it does introduce other dangers:
http://www.mssqltips.com/sqlservertip/3074/use-caution-with-sql-servers-merge-statement/
Even with this "simpler" syntax available, I still prefer this approach (error handling omitted for brevity):
SET TRANSACTION ISOLATION LEVEL SERIALIZABLE;
BEGIN TRANSACTION;
UPDATE dbo.table SET ... WHERE PK = @PK;
IF @@ROWCOUNT = 0
BEGIN
INSERT dbo.table(PK, ...) SELECT @PK, ...;
END
COMMIT TRANSACTION;
A lot of folks will suggest this way:
SET TRANSACTION ISOLATION LEVEL SERIALIZABLE;
BEGIN TRANSACTION;
IF EXISTS (SELECT 1 FROM dbo.table WHERE PK = @PK)
BEGIN
UPDATE ...
END
ELSE
BEGIN
INSERT ...
END
COMMIT TRANSACTION;
But all this accomplishes is ensuring you may need to read the table twice to locate the row(s) to be updated. In the first sample, you will only ever need to locate the row(s) once. (In both cases, if no rows are found from the initial read, an insert occurs.)
Others will suggest this way:
BEGIN TRY
INSERT ...
END TRY
BEGIN CATCH
IF ERROR_NUMBER() = 2627
UPDATE ...
END CATCH
However, this is problematic if for no other reason than letting SQL Server catch exceptions that you could have prevented in the first place is much more expensive, except in the rare scenario where almost every insert fails. I prove as much here:
Not sure what you think you gain by having a single statement; I don't think you gain anything. MERGE
is a single statement but it still has to really perform multiple operations anyway - even though it makes you think it doesn't.
EDIT: This answer is deprecated. Check the other answers.
No,
There is no way to get all resources within your account in one go. Each region is independent and for some services like IAM concept of a region does not exist at all.
Although there are API calls available to list down resources and services.
For example:
output, err := client.DescribeRegions(&ec2.DescribeRegionsInput{})
client.GetAccountAuthorizationDetails(&iam.GetAccountAuthorizationDetailsInput{})
You can find more detail about API calls and their use at: https://docs.aws.amazon.com/sdk-for-go/api/service/iam/
Above link is only for IAM. Similarly, you can find API for all other resources and services.
For bootstrap 4.0.0-alph.6
npm install [email protected] jquery tether --save
Then after this is done run:
npm install
Now. Open .angular-cli.json file and import bootstrap, jquery, and tether:
"styles": [
"styles.css",
"../node_modules/bootstrap/dist/css/bootstrap.css"
],
"scripts": [
"../node_modules/jquery/dist/jquery.js",
"../node_modules/tether/dist/js/tether.js",
"../node_modules/bootstrap/dist/js/bootstrap.js"
]
And now. You ready to go.
I came across this question as I was attempting to focus the ChromeVox screen reader to the top of the "screen" after navigating to a new screen in a React single page app. Basically trying to emulate what would happen if this page was loaded by following a link to a new server-rendered web page.
This solution doesn't require any listeners, it uses withRouter()
and the componentDidUpdate()
lifecycle method to trigger a click to focus ChromeVox on the desired element when navigating to a new url path.
I created a "Screen" component which is wrapped around the react-router switch tag which contains all the apps screens.
<Screen>
<Switch>
... add <Route> for each screen here...
</Switch>
</Screen>
Screen.tsx
ComponentNote: This component uses React + TypeScript
import React from 'react'
import { RouteComponentProps, withRouter } from 'react-router'
class Screen extends React.Component<RouteComponentProps> {
public screen = React.createRef<HTMLDivElement>()
public componentDidUpdate = (prevProps: RouteComponentProps) => {
if (this.props.location.pathname !== prevProps.location.pathname) {
// Hack: setTimeout delays click until end of current
// event loop to ensure new screen has mounted.
window.setTimeout(() => {
this.screen.current!.click()
}, 0)
}
}
public render() {
return <div ref={this.screen}>{this.props.children}</div>
}
}
export default withRouter(Screen)
I had tried using focus()
instead of click()
, but click causes ChromeVox to stop reading whatever it is currently reading and start again where I tell it to start.
Advanced note: In this solution, the navigation <nav>
which inside the Screen component and rendered after the <main>
content is visually positioned above the main
using css order: -1;
. So in pseudo code:
<Screen style={{ display: 'flex' }}>
<main>
<nav style={{ order: -1 }}>
<Screen>
If you have any thoughts, comments, or tips about this solution, please add a comment.
JavaScript stores strings as UTF-16
(double byte) so if you want to ignore the second byte just strip it out with a bitwise &
operator on 0000000011111111
(ie 255):
'a'.charCodeAt(0) & 255 === 97; // because 'a' = 97 0
'b'.charCodeAt(0) & 255 === 98; // because 'b' = 98 0
'?'.charCodeAt(0) & 255 === 19; // because '?' = 19 39
Range("A1").Function="=SUM(Range(Cells(2,1),Cells(3,2)))"
won't work because worksheet functions (when actually used on a worksheet) don't understand Range
or Cell
Try
Range("A1").Formula="=SUM(" & Range(Cells(2,1),Cells(3,2)).Address(False,False) & ")"
this is because str is pointing to a string literal means a constant string ...but you are trying to modify it by copying . Note : if it would have been an error due to memory allocation it would have been given segmentation fault at the run time .But this error is coming due to constant string modification or you can go through the below for more details abt bus error :
Bus errors are rare nowadays on x86 and occur when your processor cannot even attempt the memory access requested, typically:
Segmentation faults occur when accessing memory which does not belong to your process, they are very common and are typically the result of:
To be more precise this is not manipulating the pointer itself that will cause issues, it's accessing the memory it points to (dereferencing).
May use this-
#if defined CONDITION1 || defined CONDITION2
//your code here
#endif
This also does the same-
#if defined(CONDITION1) || defined(CONDITION2)
//your code here
#endif
Further-
#if defined CONDITION1 && defined CONDITION2
#if defined CONDITION1 ^ defined CONDITION2
#if defined CONDITION1 && !defined CONDITION2
If anyone is using lodash, there is a _.camelCase()
function.
_.camelCase('Foo Bar');
// ? 'fooBar'
_.camelCase('--foo-bar--');
// ? 'fooBar'
_.camelCase('__FOO_BAR__');
// ? 'fooBar'
My favorite visual merge tool is SourceGear DiffMerge
Perhaps you might try and use Tidy before handing the file to the converter. If one of the renderer chokes on some HTML problem (like unclosed tag), it might help it.
Recommendation. Do not use user-added REM statements to block batch steps. Use conditional GOTO instead. That way you can predefine and test the steps and options. The users also get much simpler changes and better confidence.
@Echo on
rem Using flags to control command execution
SET ExecuteSection1=0
SET ExecuteSection2=1
@echo off
IF %ExecuteSection1%==0 GOTO EndSection1
ECHO Section 1 Here
:EndSection1
IF %ExecuteSection2%==0 GOTO EndSection2
ECHO Section 2 Here
:EndSection2
If you don't want to modify the dataframe, you could use a custom formatter for that column.
import pandas as pd
pd.options.display.float_format = '${:,.2f}'.format
df = pd.DataFrame([123.4567, 234.5678, 345.6789, 456.7890],
index=['foo','bar','baz','quux'],
columns=['cost'])
print df.to_string(formatters={'cost':'${:,.2f}'.format})
yields
cost
foo $123.46
bar $234.57
baz $345.68
quux $456.79
You should set the timezone to the one of the timezones you want.
// set default timezone
date_default_timezone_set('America/Chicago'); // CDT
$info = getdate();
$date = $info['mday'];
$month = $info['mon'];
$year = $info['year'];
$hour = $info['hours'];
$min = $info['minutes'];
$sec = $info['seconds'];
$current_date = "$date/$month/$year == $hour:$min:$sec";
Or a much shorter version:
// set default timezone
date_default_timezone_set('America/Chicago'); // CDT
$current_date = date('d/m/Y == H:i:s');
It's been a while, but last time I had something similar:
ROLLBACK TRAN
or trying to
COMMIT
what had allready been done free'd everything up so I was able to clear things out and start again.
One of my experience:
I always change the default keyboard shortcut of Chrome through reverse engineering. After modification, I forgot to close Chrome and ran the following:
sudo cp chrome /opt/google/chrome/chrome
cp: cannot create regular file '/opt/google/chrome/chrome': Text file busy
Using strace, you can find the more details:
sudo strace cp ./chrome /opt/google/chrome/chrome 2>&1 |grep 'Text file busy'
open("/opt/google/chrome/chrome", O_WRONLY|O_TRUNC) = -1 ETXTBSY (Text file busy)
I use many times the ImageMagic convert
command to convert *.tif
files to *.pdf
files.
I don't know why but today I began to receive the following error:
convert: not authorized `a.pdf' @ error/constitute.c/WriteImage/1028.
After issuing the command:
convert a.tif a.pdf
After reading the above answers I edited the file /etc/ImageMagick-6/policy.xml
and changed the line:
policy domain="coder" rights="none" pattern="PDF"
to
policy domain="coder" rights="read|write" pattern="PDF"
and now everything works fine.
I have "ImageMagick 6.8.9-9 Q16 x86_64 2018-09-28" on "Ubuntu 16.04.5 LTS".
Try this regular expression:
\w*Id\b
\w*
allows word characters in front of Id
and the \b
ensures that Id
is at the end of the word (\b
is word boundary assertion).
Maybe this will help someone else, but I've seen this error when the RHS of the mapping contains a colon without enclosing quotes, such as:
someKey: another key: Change to make today: work out more
should be
someKey: another key: "Change to make today: work out more"
Check out this awesome converter. http://labs.rampinteractive.co.uk/android_dp_px_calculator/
With no additional plugin required, this bootstrap solution works great for me:
<div style="position:relative;">
<a class='btn btn-primary' href='javascript:;'>
Choose File...
<input type="file" style='position:absolute;z-index:2;top:0;left:0;filter: alpha(opacity=0);-ms-filter:"progid:DXImageTransform.Microsoft.Alpha(Opacity=0)";opacity:0;background-color:transparent;color:transparent;' name="file_source" size="40" onchange='$("#upload-file-info").html($(this).val());'>
</a>
<span class='label label-info' id="upload-file-info"></span>
</div>
demo:
http://jsfiddle.net/haisumbhatti/cAXFA/1/ (bootstrap 2)
http://jsfiddle.net/haisumbhatti/y3xyU/ (bootstrap 3)
For Visual Studio 2017
do the following:
Tools > Options > All Languages, then check or uncheck the checkbox based on your preference. As you can see in below image :
You can send the parameters in the URL of the POST request itself.
Example URL:
localhost:8080/abc/getDetails?paramter1=value1¶meter2=value2
Once you copy such type of URL in Firefox REST client make a POST call to the server you want
Why did it take a lot of valgrind investigation to find this out! Just prove it to yourself with some simple code e.g.
std::vector<std::string> vec;
{
std::string obj("hello world");
vec.push_pack(obj);
}
std::cout << vec[0] << std::endl;
If "hello world" is printed, the object must have been copied
app[func].apply(this, args);
You could execute an external tool for that task (like copy
in windows environments) but, to keep the code portable, the general approach is to:
File#renameTo
will work as long as source and target location are on the same volume. Personally I'd avoid using it to move files to different folders.
Sub test()
MsgBox Worksheets("sheet_name").Range("A65536").End(xlUp).Row
End Sub
This is looking for a value in column A
because of "A65536"
.
Chrome (technically, Blink) will not implement maxlength for <input type="number">
.
The HTML5 specification says that maxlength is only applicable to the types text, url, e-mail, search, tel, and password.
you have to try this
func clearAllScrollSubView ()
{
let theSubviews = itemsScrollView.subviews
for (var view) in theSubviews
{
if view is UIView
{
view.removeFromSuperview()
}
}
}
You can also use the following syntax for the strongly typed version:
<% using (Html.BeginForm<SomeController>(x=> x.SomeAction(),
FormMethod.Post,
new { enctype = "multipart/form-data" }))
{ %>
The HTTPS certificate verification security measure isn't something to be discarded light-heartedly. The Man-in-the-middle attack that it prevents safeguards you from a third party e.g. sipping a virus in or tampering with or stealing your data.
Even if you only intend to do that in a test environment, you can easily forget to undo it when moving elsewhere.
Instead, read the relevant section on the provided link and do as it says. The way specific for requests
(which bundles with its own copy of urllib3
), as per CA Certificates — Advanced Usage — Requests 2.8.1 documentation:
requests
ships with its own certificate bundle (but it can only be updated together with the module)requests
v2.4.0
) the certifi
package instead if it's installedcertifi
as per how do I update root certificates of certifi? . E.g. if you replace its bundle with just your test certificate, you will immediately see it if you forget to undo that when moving to production.Finally, with today's government-backed global hacking operations like Tailored Access Operations and the Great Firewall of China that target network infrastructure, falling under a MITM attack is more probable than you think.
one way is if you have a jdk installed , in bin folder there is a utility called jconsole(even visualvm can be used). Launch it and connect to the relevant java process and you can see what are the heap size settings set and many other details
When running headless or cli only, jConsole can be used over lan, if you specify a port to connect on when starting the service in question.
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;
The amazing ubiquity of Vim, and the even more amazing ubiquity of Vi-clones in general, on Unix systems alone is enough to make it worth learning.
Besides that, the whole Vi-style thinking is something that I really think has made me a bit more productive. For a person not used to modes such as the command mode and insert mode, it seems a bit excessive to have to enter a mode just to insert text. But, when one has been using Vim for a few months, and has learned quite a few tips and tricks, Vim seems to be an asset that seems to be worth it.
Of course, the Emacs crowd says the same thing regarding Emacs-style thinking, but I gave up on learning Emacs because Vim was simpler and did the job for me.
The problem is that (as of 2016), for the password field, Firefox and Internet Explorer use the character "Black Circle" (?), which uses the Unicode code point 25CF
, but Chrome uses the character "Bullet" (•), which uses the Unicode code point 2022
.
As you can see, even in the StackOverflow font the two characters have different sizes.
The font you're using, "Lucida Sans Unicode", has an even greater disparity between the sizes of these two characters, leading to you noticing the difference.
The simple solution is to use a font in which both characters have similar sizes.
The fix could thus be to use a default font of the browser, which should render the characters in the password field just fine:
input[type="password"] {
font-family: caption;
}
The easy way to do this is to put the Date function you want to use in a Cell, and link to that cell from the textbox with the LinkedCell property.
From VBA you might try using:
textbox.Value = Format(Date(),"mm/dd/yy")
See some of the answers to my similar question why-cant-i-push-from-a-shallow-clone and the link to the recent thread on the git list.
Ultimately, the 'depth' measurement isn't consistent between repos, because they measure from their individual HEADs, rather than (a) your Head, or (b) the commit(s) you cloned/fetched, or (c) something else you had in mind.
The hard bit is getting one's Use Case right (i.e. self-consistent), so that distributed, and therefore probably divergent repos will still work happily together.
It does look like the checkout --orphan
is the right 'set-up' stage, but still lacks clean (i.e. a simple understandable one line command) guidance on the "clone" step. Rather it looks like you have to init
a repo, set up a remote
tracking branch (you do want the one branch only?), and then fetch
that single branch, which feels long winded with more opportunity for mistakes.
Edit: For the 'clone' step see this answer
Please note that C# and C++'s % operator is actually NOT a modulo, it's remainder. The formula for modulo that you want, in your case, is:
float nfmod(float a,float b)
{
return a - b * floor(a / b);
}
You have to recode this in C# (or C++) but this is the way you get modulo and not a remainder.
public static void WriteLine(this List<int> theList)
{
foreach (int i in list)
{
Console.Write("{0}\t", t.ToString());
}
Console.WriteLine();
}
Then, later...
list.WriteLine();
Also check out the open financial exchange (ofx) http://www.ofx.net/
This is what apps like quicken, ms money etc use.
Adding executable permissions, recursively, to all files (not folders) within the current folder with sh
extension:
find . -name '*.sh' -type f | xargs chmod +x
* Notice the pipe (|
)
The only way you can get it fancier is with MetaWhere.
MetaWhere has a newer cousin which is called Squeel which allows code like this:
GroupUser.where{user_id != me}
It goes without saying, that if this is the only refactor you are going to make, it is not worth using a gem and I would just stick with what you got. Squeel is useful in situations where you have many complex queries interacting with Ruby code.
Since other solutions are old and either poorly-working or not working at all, I've modified NestedScrollView
, which is stable, modern and it has all you expect from a scroll view. Except for horizontal scrolling.
Here's the repo: https://github.com/ultimate-deej/TwoWayNestedScrollView
I've made no changes, no "improvements" to the original NestedScrollView
expect for what was absolutely necessary.
The code is based on androidx.core:core:1.3.0
, which is the latest stable version at the time of writing.
All of the following works:
NestedScrollView
)For anyone that is still stuck on this issue after trying the above. If you are right-clicking on the database and going to tasks->import, then here is the issue. Go to your start menu and under sql server, find the x64 bit import export wizard and try that. Worked like a charm for me, but it took me FAR too long to find it Microsoft!
if you can write a batch file that does not need to be interactive, try running that batch file as a service, to do what needs to be done.
If I set my backend to template
in ~/.matplotlib/matplotlibrc
,
then I can reproduce your symptoms:
~/.matplotlib/matplotlibrc:
# backend : GtkAgg
backend : template
Note that the file matplotlibrc
may not be in directory ~/.matplotlib/
. In this case, the following code shows where it is:
>>> import matplotlib
>>> matplotlib.matplotlib_fname()
In [1]: import matplotlib.pyplot as p
In [2]: p.plot(range(20),range(20))
Out[2]: [<matplotlib.lines.Line2D object at 0xa64932c>]
In [3]: p.show()
If you edit ~/.matplotlib/matplotlibrc
and change the backend to something like GtkAgg
, you should see a plot. You can list all the backends available on your machine with
import matplotlib.rcsetup as rcsetup
print(rcsetup.all_backends)
It should return a list like:
['GTK', 'GTKAgg', 'GTKCairo', 'FltkAgg', 'MacOSX', 'QtAgg', 'Qt4Agg',
'TkAgg', 'WX', 'WXAgg', 'CocoaAgg', 'agg', 'cairo', 'emf', 'gdk', 'pdf',
'ps', 'svg', 'template']
Reference:
You could use the checked
property of a radio button to uncheck it.
Something like this:
<script>
function uncheck()
{
document.getElementById('myRadio').checked = false;
}
function check()
{
document.getElementById('myRadio').checked = true;
}
</script>
<input id="myRadio" type="radio" checked="checked"/>
<button onclick="uncheck();">Uncheck</button>
<button onclick="check();">Check</button>
?See it in action here: http://jsfiddle.net/wgYNa/
Since Django 2.0 the ForeignKey field requires two positional arguments:
categorie = models.ForeignKey('Categorie', on_delete=models.PROTECT)
Here are some methods can used in on_delete
Cascade deletes. Django emulates the behavior of the SQL constraint ON DELETE CASCADE and also deletes the object containing the ForeignKey
Prevent deletion of the referenced object by raising ProtectedError, a subclass of django.db.IntegrityError.
Take no action. If your database backend enforces referential integrity, this will cause an IntegrityError unless you manually add an SQL ON DELETE constraint to the database field.
you can find more about on_delete by reading the documentation.
It really depends on how you write your bash scripts. If your /bin/sh
is symlinked to bash, when bash is invoked as sh
, some features are unavailable.
If you want bash-specific, non-POSIX features, use #!/bin/bash
You can use %%:
printf("100%%");
The result is:
100%
The <label>
tag allows you to click on the label, and it will be treated like clicking on the associated input element. There are two ways to create this association:
One way is to wrap the label element around the input element:
<label>Input here:
<input type='text' name='theinput' id='theinput'>
</label>
The other way is to use the for
attribute, giving it the ID of the associated input:
<label for="theinput">Input here:</label>
<input type='text' name='whatever' id='theinput'>
This is especially useful for use with checkboxes and buttons, since it means you can check the box by clicking on the associated text instead of having to hit the box itself.
Read more about this element in MDN.
Put it in double quotes:
echo "\t";
Single quotes do not expand escaped characters.
Use the documentation when in doubt.
I have never used jekyll, but it's main page says that it uses Liquid, and according to their docs, I think the following should work:
<ul> {% for page in site.pages %} {% if page.title != 'index' %} <li><div class="drvce"><a href="{{ page.url }}">{{ page.title }}</a></div></li> {% endif %} {% endfor %} </ul>
I like how this guy does it — https://amalgjose.com/2015/02/19/python-code-for-calculating-the-difference-between-two-time-stamps. Not sure if it has some cons.
But looks neat for me :)
from datetime import datetime
from dateutil.relativedelta import relativedelta
t_a = datetime.now()
t_b = datetime.now()
def diff(t_a, t_b):
t_diff = relativedelta(t_b, t_a) # later/end time comes first!
return '{h}h {m}m {s}s'.format(h=t_diff.hours, m=t_diff.minutes, s=t_diff.seconds)
Regarding to the question you still need to use datetime.strptime()
as others said earlier.
Rules are used to add additional functionality which applies to all tests within a test class, but in a more generic way.
For instance, ExternalResource executes code before and after a test method, without having to use @Before
and @After
. Using an ExternalResource
rather than @Before
and @After
gives opportunities for better code reuse; the same rule can be used from two different test classes.
The design was based upon: Interceptors in JUnit
For more information see JUnit wiki : Rules.
using command
npm install bootstrap --save
open .angular.json old (.angular-cli.json ) file find the "styles" add the bootstrap css file
"styles": [
"src/styles.scss",
"node_modules/bootstrap/dist/css/bootstrap.min.css"
],
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class Swingtest extends JFrame implements ActionListener
{
JTextField txtdata;
JButton calbtn = new JButton("Calculate");
public Swingtest()
{
JPanel myPanel = new JPanel();
add(myPanel);
myPanel.setLayout(new GridLayout(3, 2));
myPanel.add(calbtn);
calbtn.addActionListener(this);
txtdata = new JTextField();
myPanel.add(txtdata);
}
public void actionPerformed(ActionEvent e)
{
if (e.getSource() == calbtn) {
String data = txtdata.getText(); //perform your operation
System.out.println(data);
}
}
public static void main(String args[])
{
Swingtest g = new Swingtest();
g.setLocation(10, 10);
g.setSize(300, 300);
g.setVisible(true);
}
}
now its working
Well, in mathematics to convert a negative number to a positive number you just need to multiple the negative number by -1;
Then your solution could be like this:
a = a * -1;
or shorter:
a *= -1;
>>> a = set([6, 7, 8, 9, 10, 11, 12])
>>> sub_a = set([6, 9, 12])
>>> a - sub_a
set([8, 10, 11, 7])
Here is what I ended up doing to accomplish everything. The only thing you need to consider in addition to this is (a) the login process and (b) where you are storing your app data (in this case, I used a singleton).
As you can see, the root view controller is my Main Tab Controller. I did this because after the user has logged in, I want the app to launch directly to the first tab. (This avoids any "flicker" where the login view shows temporarily.)
AppDelegate.m
In this file, I check whether the user is already logged in. If not, I push the login view controller. I also handle the logout process, where I clear data and show the login view.
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
// Show login view if not logged in already
if(![AppData isLoggedIn]) {
[self showLoginScreen:NO];
}
return YES;
}
-(void) showLoginScreen:(BOOL)animated
{
// Get login screen from storyboard and present it
UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"MainStoryboard" bundle:nil];
LoginViewController *viewController = (LoginViewController *)[storyboard instantiateViewControllerWithIdentifier:@"loginScreen"];
[self.window makeKeyAndVisible];
[self.window.rootViewController presentViewController:viewController
animated:animated
completion:nil];
}
-(void) logout
{
// Remove data from singleton (where all my app data is stored)
[AppData clearData];
// Reset view controller (this will quickly clear all the views)
UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"MainStoryboard" bundle:nil];
MainTabControllerViewController *viewController = (MainTabControllerViewController *)[storyboard instantiateViewControllerWithIdentifier:@"mainView"];
[self.window setRootViewController:viewController];
// Show login screen
[self showLoginScreen:NO];
}
LoginViewController.m
Here, if the login is successful, I simply dismiss the view and send a notification.
-(void) loginWasSuccessful
{
// Send notification
[[NSNotificationCenter defaultCenter] postNotificationName:@"loginSuccessful" object:self];
// Dismiss login screen
[self dismissViewControllerAnimated:YES completion:nil];
}
In Oracle, there is the concept of schema name, so try using this
update schemname.tablename t
set t.columnname = replace(t.columnname, t.oldvalue, t.newvalue);
You can only match to constants in switch statements.
Example:
switch (variable1)
{
case 1: // A hard-coded value
// Code
break;
default:
// Code
break;
}
Successful!
switch (variable1)
{
case variable2:
// Code
break;
default:
// Code
break;
}
CS0150 A constant value is expected.
cq.select(cb.construct(entityClazz.class, root.get("ID"), root.get("VERSION"))); // HERE IS NO ERROR
Add this to your macro and it will recalculate all the cells and formulae.
Call Application.CalculateFullRebuild
Hope it has been already fixed.
PS The above code is for the people looking for a macro to solve the issue.
Beginning from version 1.2.0-alpha02 of androidx recyclerView library, it is now automatically managed. Just add it with:
implementation "androidx.recyclerview:recyclerview:1.2.0-alpha02"
And use:
adapter.stateRestorationPolicy = StateRestorationPolicy.PREVENT_WHEN_EMPTY
The StateRestorationPolicy enum has 3 options:
Note that at the time of this answer, recyclerView library is still in alpha03, but alpha phase is not suitable for production purposes.
I think in order import namespace in razor view, you just need to add below way:
@using XX.YY.ZZ
Just if someone is interested in another option:
content=( $(cat test.txt) )
a=0
while [ $a -le ${#content[@]} ]
do
echo ${content[$a]}
a=$[a+1]
done
file.lines
with JFile package
var JFile=require('jfile');
var myF=new JFile("./data.txt");
myF.lines // ["first line","second line"] ....
Don't forget before :
npm install jfile --save
try this C# code to drop your database
public static void DropDatabases(string dataBase) {
string sql = "ALTER DATABASE " + dataBase + "SET SINGLE_USER WITH ROLLBACK IMMEDIATE" ;
using (System.Data.SqlClient.SqlConnection connection = new System.Data.SqlClient.SqlConnection(ConfigurationManager.ConnectionStrings["DBRestore"].ConnectionString))
{
connection.Open();
using (System.Data.SqlClient.SqlCommand command = new System.Data.SqlClient.SqlCommand(sql, connection))
{
command.CommandType = CommandType.Text;
command.CommandTimeout = 7200;
command.ExecuteNonQuery();
}
sql = "DROP DATABASE " + dataBase;
using (System.Data.SqlClient.SqlCommand command = new System.Data.SqlClient.SqlCommand(sql, connection))
{
command.CommandType = CommandType.Text;
command.CommandTimeout = 7200;
command.ExecuteNonQuery();
}
}
}
also works if you do a "display: block;" on the td, destroying the td identity, but works!
The strcmp and strcmpi functions are the most direct way to do this. They search through arrays.
strs = {'HA' 'KU' 'LA' 'MA' 'TATA'}
ix = find(strcmp(strs, 'KU'))
UPDATE Employee SET Empid=emp3.empid
FROM EMP_Employee AS emp3
WHERE Employee.Empid=emp3.empid
It's worth adding that, in addition to the QR codes library posted by @abaumg, Google provides a QR Codes API QR Codes APImany thanks to @Toukakoukan for the link update.
To use this , basically:
https://chart.googleapis.com/chart?chs=300x300&cht=qr&chl=http%3A%2F%2Fwww.google.com%2F&choe=UTF-8
300x300
is the size of the QR image you want to generate,chl
is the url-encoded string you want to change into a QR code, andchoe
is the (optional) encoding.The link, above, gives more detail, but to use it just have the src
of an image point to the manipulated value, like so:
<img src="https://chart.googleapis.com/chart?chs=300x300&cht=qr&chl=http%3A%2F%2Fwww.google.com%2F&choe=UTF-8" title="Link to Google.com" />
Demo:
Notice that you're using Observable#map to convert the raw Response
object your base Observable emits to a parsed representation of the JSON response.
If I understood you correctly, you want to map
again. But this time, converting that raw JSON to instances of your Model
. So you would do something like:
http.get('api/people.json')
.map(res => res.json())
.map(peopleData => peopleData.map(personData => new Person(personData)))
So, you started with an Observable that emits a Response
object, turned that into an observable that emits an object of the parsed JSON of that response, and then turned that into yet another observable that turned that raw JSON into an array of your models.
To avoid using integer values to identify the VideoCapture
properties, one can use, e.g., cv2.cv.CV_CAP_PROP_FPS
in OpenCV 2.4 and cv2.CAP_PROP_FPS
in OpenCV 3.0. (See also Stefan's comment below.)
Here a utility function that works for both OpenCV 2.4 and 3.0:
# returns OpenCV VideoCapture property id given, e.g., "FPS"
def capPropId(prop):
return getattr(cv2 if OPCV3 else cv2.cv,
("" if OPCV3 else "CV_") + "CAP_PROP_" + prop)
OPCV3
is set earlier in my utilities code like this:
from pkg_resources import parse_version
OPCV3 = parse_version(cv2.__version__) >= parse_version('3')
Check this -
<a href="{{url('/abc/xyz')}}">Go</a>
This is working for me and I hope it will work for you.
great answer from @David, here is for Python 3 without the generic try-except:
def send_email(user, password, recipient, subject, body):
gmail_user = user
gmail_pwd = password
FROM = user
TO = recipient if type(recipient) is list else [recipient]
SUBJECT = subject
TEXT = body
# Prepare actual message
message = """From: %s\nTo: %s\nSubject: %s\n\n%s
""" % (FROM, ", ".join(TO), SUBJECT, TEXT)
server = smtplib.SMTP("smtp.gmail.com", 587)
server.ehlo()
server.starttls()
server.login(gmail_user, gmail_pwd)
server.sendmail(FROM, TO, message)
server.close()
If you want to insert all the columns then
insert into def select * from abc;
here the number of columns in def should be equal to abc.
if you want to insert the subsets of columns then
insert into def (col1,col2, col3 ) select scol1,scol2,scol3 from abc;
if you want to insert some hardcorded values then
insert into def (col1, col2,col3) select 'hardcoded value',scol2, scol3 from abc;