I had some issues with the MouseDown part of this, but here is some code that might get your started.
<Window x:Class="WpfApplication1.Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="Window1" Height="300" Width="300">
<Grid>
<Control VerticalAlignment="Top">
<Control.Template>
<ControlTemplate>
<StackPanel>
<TextBox x:Name="MyText"></TextBox>
<Popup x:Name="Popup" PopupAnimation="Fade" VerticalAlignment="Top">
<Border Background="Red">
<TextBlock>Test Popup Content</TextBlock>
</Border>
</Popup>
</StackPanel>
<ControlTemplate.Triggers>
<EventTrigger RoutedEvent="UIElement.MouseEnter" SourceName="MyText">
<BeginStoryboard>
<Storyboard>
<BooleanAnimationUsingKeyFrames Storyboard.TargetName="Popup" Storyboard.TargetProperty="(Popup.IsOpen)">
<DiscreteBooleanKeyFrame KeyTime="00:00:00" Value="True"/>
</BooleanAnimationUsingKeyFrames>
</Storyboard>
</BeginStoryboard>
</EventTrigger>
<EventTrigger RoutedEvent="UIElement.MouseLeave" SourceName="MyText">
<BeginStoryboard>
<Storyboard>
<BooleanAnimationUsingKeyFrames Storyboard.TargetName="Popup" Storyboard.TargetProperty="(Popup.IsOpen)">
<DiscreteBooleanKeyFrame KeyTime="00:00:00" Value="False"/>
</BooleanAnimationUsingKeyFrames>
</Storyboard>
</BeginStoryboard>
</EventTrigger>
</ControlTemplate.Triggers>
</ControlTemplate>
</Control.Template>
</Control>
</Grid>
</Window>
Below code is working on my live server as well as in my own Lapy.
Note:
Please Create data folder in WebContent and put in any single image or any file(jsp or html file).
Add jar files
commons-collections-3.1.jar
commons-fileupload-1.2.2.jar
commons-io-2.1.jar
commons-logging-1.0.4.jar
upload.jsp
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>File Upload</title>
</head>
<body>
<form method="post" action="UploadServlet" enctype="multipart/form-data">
Select file to upload:
<input type="file" name="dataFile" id="fileChooser"/><br/><br/>
<input type="submit" value="Upload" />
</form>
</body>
</html>
UploadServlet.java
package com.servlet;
import java.io.File;
import java.io.IOException;
import java.util.Iterator;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
/**
* Servlet implementation class UploadServlet
*/
public class UploadServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
private static final String DATA_DIRECTORY = "data";
private static final int MAX_MEMORY_SIZE = 1024 * 1024 * 2;
private static final int MAX_REQUEST_SIZE = 1024 * 1024;
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// Check that we have a file upload request
boolean isMultipart = ServletFileUpload.isMultipartContent(request);
if (!isMultipart) {
return;
}
// Create a factory for disk-based file items
DiskFileItemFactory factory = new DiskFileItemFactory();
// Sets the size threshold beyond which files are written directly to
// disk.
factory.setSizeThreshold(MAX_MEMORY_SIZE);
// Sets the directory used to temporarily store files that are larger
// than the configured size threshold. We use temporary directory for
// java
factory.setRepository(new File(System.getProperty("java.io.tmpdir")));
// constructs the folder where uploaded file will be stored
String uploadFolder = getServletContext().getRealPath("")
+ File.separator + DATA_DIRECTORY;
// Create a new file upload handler
ServletFileUpload upload = new ServletFileUpload(factory);
// Set overall request size constraint
upload.setSizeMax(MAX_REQUEST_SIZE);
try {
// Parse the request
List items = upload.parseRequest(request);
Iterator iter = items.iterator();
while (iter.hasNext()) {
FileItem item = (FileItem) iter.next();
if (!item.isFormField()) {
String fileName = new File(item.getName()).getName();
String filePath = uploadFolder + File.separator + fileName;
File uploadedFile = new File(filePath);
System.out.println(filePath);
// saves the file to upload directory
item.write(uploadedFile);
}
}
// displays done.jsp page after upload finished
getServletContext().getRequestDispatcher("/done.jsp").forward(
request, response);
} catch (FileUploadException ex) {
throw new ServletException(ex);
} catch (Exception ex) {
throw new ServletException(ex);
}
}
}
web.xml
<servlet>
<description></description>
<display-name>UploadServlet</display-name>
<servlet-name>UploadServlet</servlet-name>
<servlet-class>com.servlet.UploadServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>UploadServlet</servlet-name>
<url-pattern>/UploadServlet</url-pattern>
</servlet-mapping>
done.jsp
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Upload Done</title>
</head>
<body>
<h3>Your file has been uploaded!</h3>
</body>
</html>
In one line of code as below :
<p> cursor on text field shows text .if not password will be shown</p>_x000D_
<input type="password" name="txt_password" onmouseover="this.type='text'"_x000D_
onmouseout="this.type='password'" placeholder="password" />
_x000D_
As there is a problem with the third optonal parameter in IE and using closures prevents us from changing the variables (in a loop for example) and still achieving the desired result, I suggest the following solution.
We can try using recursion like this:
var i = 0;
var hellos = ["Hello World1!", "Hello World2!", "Hello World3!", "Hello World4!", "Hello World5!"];
if(hellos.length > 0) timeout();
function timeout() {
document.write('<p>' + hellos[i] + '<p>');
i++;
if (i < hellos.length)
setTimeout(timeout, 500);
}
We need to make sure that nothing else changes these variables and that we write a proper recursion condition to avoid infinite recursion.
Try the following and see if it works:
<video width="400" height="300" preload controls>
<source src="video.mp4" type="video/mp4" />
Your browser does not support the video tag.
</video>
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
}
//private void Form1_Load(object sender, EventArgs e)
//{
// // Instantiate a new instance of Form1.
// Form1 f1 = new Form1();
// f1.Text = "zzzzzzz";
//}
}
class MainApplication
{
public static void Main()
{
// Instantiate a new instance of Form1.
Form1 f1 = new Form1();
// Display a messagebox. This shows the application
// is running, yet there is nothing shown to the user.
// This is the point at which you customize your form.
System.Windows.Forms.MessageBox.Show("The application "
+ "is running now, but no forms have been shown.");
// Customize the form.
f1.Text = "Running Form";
// Show the instance of the form modally.
f1.ShowDialog();
}
}
}
Here is another approach using CSS transform: skew(45deg)
to produce the cut corner effect. The shape itself involves three elements (1 real and 2 pseudo-elements) as follows:
div
element has overflow: hidden
and produces the left border.:before
pseudo-element which is 20% the height of the parent container and has a skew transform applied to it. This element prodcues the border on the top and cut (slanted) border on the right side.:after
pseudo-element which is 80% the height of the parent (basically, remaining height) and produces the bottom border, the remaining portion of the right border.The output produced is responsive, produces a transparent cut at the top and supports transparent backgrounds.
div {_x000D_
position: relative;_x000D_
height: 100px;_x000D_
width: 200px;_x000D_
border-left: 2px solid beige;_x000D_
overflow: hidden;_x000D_
}_x000D_
div:after,_x000D_
div:before {_x000D_
position: absolute;_x000D_
content: '';_x000D_
width: calc(100% - 2px);_x000D_
left: 0px;_x000D_
z-index: -1;_x000D_
}_x000D_
div:before {_x000D_
height: 20%;_x000D_
top: 0px;_x000D_
border: 2px solid beige;_x000D_
border-width: 2px 3px 0px 0px;_x000D_
transform: skew(45deg);_x000D_
transform-origin: right bottom;_x000D_
}_x000D_
div:after {_x000D_
height: calc(80% - 4px);_x000D_
bottom: 0px;_x000D_
border: 2px solid beige;_x000D_
border-width: 0px 2px 2px 0px;_x000D_
}_x000D_
.filled:before, .filled:after {_x000D_
background-color: beige;_x000D_
}_x000D_
_x000D_
/* Just for demo */_x000D_
_x000D_
div {_x000D_
float: left;_x000D_
color: beige;_x000D_
padding: 10px;_x000D_
transition: all 1s;_x000D_
margin: 10px;_x000D_
}_x000D_
div:hover {_x000D_
height: 200px;_x000D_
width: 300px;_x000D_
}_x000D_
div.filled{_x000D_
color: black;_x000D_
}_x000D_
body{_x000D_
background-image: radial-gradient(circle, #3F9CBA 0%, #153346 100%);_x000D_
}
_x000D_
<div class="cut-corner">Some content</div>_x000D_
<div class="cut-corner filled">Some content</div>
_x000D_
The below is another method to produce the cut corner effect by using linear-gradient
background images. A combination of 3 gradient images (given below) is used:
The output produced is responsive, produces transparent cut and doesn't require any extra elements (real or pseudo). The drawback is that this approach would work only when the background (fill) is a solid color and it is very difficult to produce borders (but still possible as seen in the snippet).
.cut-corner {_x000D_
height: 100px;_x000D_
width: 200px;_x000D_
background-image: linear-gradient(to bottom left, transparent 50%, beige 50%), linear-gradient(beige, beige), linear-gradient(beige, beige);_x000D_
background-size: 25px 25px, 100% 100%, 100% 100%;_x000D_
background-position: 100% 0%, -25px 0%, 100% 25px;_x000D_
background-repeat: no-repeat;_x000D_
}_x000D_
.filled {_x000D_
background-image: linear-gradient(black, black), linear-gradient(black, black), linear-gradient(black, black), linear-gradient(black, black), linear-gradient(to bottom left, transparent calc(50% - 1px), black calc(50% - 1px), black calc(50% + 1px), beige calc(50% + 1px)), linear-gradient(beige, beige), linear-gradient(beige, beige);_x000D_
background-size: 2px 100%, 2px 100%, 100% 2px, 100% 2px, 25px 25px, 100% 100%, 100% 100%;_x000D_
background-position: 0% 0%, 100% 25px, -25px 0%, 0px 100%, 100% 0%, -25px 0%, 100% 25px;_x000D_
}_x000D_
_x000D_
/* Just for demo */_x000D_
_x000D_
*{_x000D_
box-sizing: border-box;_x000D_
}_x000D_
div {_x000D_
float: left;_x000D_
color: black;_x000D_
padding: 10px;_x000D_
transition: all 1s;_x000D_
margin: 10px;_x000D_
}_x000D_
div:hover {_x000D_
height: 200px;_x000D_
width: 300px;_x000D_
}_x000D_
body{_x000D_
background-image: radial-gradient(circle, #3F9CBA 0%, #153346 100%);_x000D_
}
_x000D_
<div class="cut-corner">Some content</div>_x000D_
<div class="cut-corner filled">Some content</div>
_x000D_
Another way to do this problem besides using ASCII conversions is the following:
String input = "abc".toLowerCase();
final static String alphabet = "abcdefghijklmnopqrstuvwxyz";
for(int i=0; i < input.length(); i++){
System.out.print(alphabet.indexOf(input.charAt(i))+1);
}
Petar Ivanov's answer to replace a character at a specific index in a string question
String are immutable in Java. You can't change them.
You need to create a new string with the character replaced.
String myName = "domanokz";
String newName = myName.substring(0,4)+'x'+myName.substring(5);
Or you can use a StringBuilder:
StringBuilder myName = new StringBuilder("domanokz");
myName.setCharAt(4, 'x');
System.out.println(myName);
Check out std::isdigit()
function.
You've already listed the most notable solutions for embedding Chromium (CEF, Chrome Frame, Awesomium). There aren't any more projects that matter.
There is still the Berkelium project (see Berkelium Sharp and Berkelium Managed), but it emebeds an old version of Chromium.
CEF is your best bet - it's fully open source and frequently updated. It's the only option that allows you to embed the latest version of Chromium. Now that Per Lundberg is actively working on porting CEF 3 to CefSharp, this is the best option for the future. There is also Xilium.CefGlue, but this one provides a low level API for CEF, it binds to the C API of CEF. CefSharp on the other hand binds to the C++ API of CEF.
Adobe is not the only major player using CEF, see other notable applications using CEF on the CEF wikipedia page.
Updating Chrome Frame is pointless since the project has been retired.
<input type="submit" value="Create" name="button"/>_x000D_
<input type="submit" value="Reset" name="button" />
_x000D_
write the following code in Controler.
[HttpPost]
public ActionResult Login(string button)
{
switch (button)
{
case "Create":
return RedirectToAction("Deshboard", "Home");
break;
case "Reset":
return RedirectToAction("Login", "Home");
break;
}
return View();
}
Are you sure that you are executing the script against the correct database? In SQL Server Management studio you can change the database you are running the query against in a drop-down box on one of the toolbars, or you can start your query with this:
USE SomeDatabase
You want:
this.value = ''; // straight JS, no jQuery
or
$(this).val(''); // jQuery
With $(this).value = ''
you're assigning an empty string as the value
property of the jQuery object that wraps this
-- not the value
of this
itself.
Your module and your class AthleteList
have the same name. The line
import AthleteList
imports the module and creates a name AthleteList
in your current scope that points to the module object. If you want to access the actual class, use
AthleteList.AthleteList
In particular, in the line
return(AthleteList(templ.pop(0), templ.pop(0), templ))
you are actually accessing the module object and not the class. Try
return(AthleteList.AthleteList(templ.pop(0), templ.pop(0), templ))
Use the below code to resolve the issue.
import json
from numpyencoder import NumpyEncoder
alerts = {'upper':[1425],'lower':[576],'level':[2],'datetime':['2012-08-08
15:30']}
afile = open('test.json','w')
afile.write(json.dumps(alerts,encoding='UTF-8',cls=NumpyEncoder))
afile.close()
For all users of the system via the /etc/wgetrc
or for the user only with the ~/.wgetrc
file:
use_proxy=yes
http_proxy=127.0.0.1:8080
https_proxy=127.0.0.1:8080
or via -e
options placed after the URL:
wget ... -e use_proxy=yes -e http_proxy=127.0.0.1:8080 ...
Datasets implement IDisposable thorough MarshalByValueComponent, which implements IDisposable. Since datasets are managed there is no real benefit to calling dispose.
These are different Form content types defined by W3C. If you want to send simple text/ ASCII data, then x-www-form-urlencoded will work. This is the default.
But if you have to send non-ASCII text or large binary data, the form-data is for that.
You can use Raw if you want to send plain text or JSON or any other kind of string. Like the name suggests, Postman sends your raw string data as it is without modifications. The type of data that you are sending can be set by using the content-type header from the drop down.
Binary can be used when you want to attach non-textual data to the request, e.g. a video/audio file, images, or any other binary data file.
Refer to this link for further reading: Forms in HTML documents
Try this ,
<img src= "@Url.Content(Model.ImagePath)" alt="Sample Image" style="height:50px;width:100px;"/>
(or)
<img src="~/Content/img/@Url.Content(model =>model.ImagePath)" style="height:50px;width:100px;"/>
Sure you can create an html template and I would recommend also a text template. In the template you can just put [BODY] in the place where the body would be placed and then you can just read in the template and replace the body with the new content. You can send the email using .Nets Mail Class. You just have to loop through the sending of the email to all recipients after you create the email initially. Worked like a charm for me.
using System.Net.Mail;
// Email content
string HTMLTemplatePath = @"path";
string TextTemplatePath = @"path";
string HTMLBody = "";
string TextBody = "";
HTMLBody = File.ReadAllText(HTMLTemplatePath);
TextBody = File.ReadAllText(TextTemplatePath);
HTMLBody = HTMLBody.Replace(["[BODY]", content);
TextBody = HTMLBody.Replace(["[BODY]", content);
// Create email code
MailMessage m = new MailMessage();
m.From = new MailAddress("[email protected]", "display name");
m.To.Add("[email protected]");
m.Subject = "subject";
AlternateView plain = AlternateView.CreateAlternateViewFromString(_EmailBody + text, new System.Net.Mime.ContentType("text/plain"));
AlternateView html = AlternateView.CreateAlternateViewFromString(_EmailBody + body, new System.Net.Mime.ContentType("text/html"));
mail.AlternateViews.Add(plain);
mail.AlternateViews.Add(html);
SmtpClient smtp = new SmtpClient("server");
smtp.Send(m);
To convert an ordinal into its enum represantation you might want to do this:
ReportTypeEnum value = ReportTypeEnum.values()[ordinal];
Please notice the array bounds.
Note that every call to values()
returns a newly cloned array which might impact performance in a negative way. You may want to cache the array if it's going to be called often.
Code example on how to cache values()
.
This answer was edited to include the feedback given inside the comments
Here is a work around for inner bordered rect
using symbol
and use
.
Example: https://jsbin.com/yopemiwame/edit?html,output
SVG:
<svg>
<symbol id="inner-border-rect">
<rect class="inner-border" width="100%" height="100%" style="fill:rgb(0,255,255);stroke-width:10;stroke:rgb(0,0,0)">
</symbol>
...
<use xlink:href="#inner-border-rect" x="?" y="?" width="?" height="?">
</svg>
Note: Make sure to replace the ?
in use
with real values.
Background: The reason why this works is because symbol establishes a new viewport by replacing symbol
with svg
and creating an element in the shadow DOM. This svg
of the shadow DOM is then linked into your current SVG
element. Note that svg
s can be nested and every svg
creates a new viewport, which clips everything that overlaps, including the overlapping border. For a much more detailed overview of whats going on read this fantastic article by Sara Soueidan.
Show file and track error
systemctl status nginx.service
For the Base64 code like:
"data:image/jpg;base64,iVBORw0KGgoAAAANSUhEUgAAAMgAAADIAQAAAACFI5MzAAAB9klEQVR42u2YQYorMQxEBbqWQFc36FoG/6pyOpNZ/J20mGGaTiftF2hbLpWU2PnfYX/k55Jl5vhUVTu8luUdaCeFcydejjdwDUyQ5XV2JOcSZnkHZgiejusK51QGycrl2yIR1BwjjKivSFz8YC7fY91GKIj6PL5pp4/wWL54t3MHt/AjFxoJwmkYwosbh6/UEHE817hvi/vGex8gEkTdVRo1/55BM7kjUIgpoMW1DxB6kD+GtCX4PUFws40OwcUm0/lRYjOB3pG9YcguBFQuO0ISJ9UIrUP5CKy/MriXHDkETYmLDax1+RkgWBglQgUyq6T/HCAHBq7iJHd9KWWAlIKoGpiLc6HNDhDkETNYwqeVhym72snKKxA6BJL4UPM5QPYtgGwZeNZ5O0UvgSb0VGdcmVfJCQwQrM+pRiGnYJ497SUlv2NOYfOCX3qU2Equ7W3JAslsN7oDBDWWojcZq+KbEwQRdRYl1wD3ML52rpGc6w24qCXaKh4DRHWJbUPemqtEGyBMKC4Q/QmWiDWzRxkgO1UtSLh3svMaILeDpEGwrwvZ4Bkg9LynK1Y1LJWQdqKGnm3K7VTCz7vS9hIuUyYRd/xKcYRIHGqAViisQ4S/Uozmqo41Pn6bNRI1xS/fk2fMEKpDZYkpjP6B1T0HyN9/Nb+M/AORXDdE4Lb/mQAAAABJRU5ErkJggg=="
Use Swift5.0 code like:
func imageFromBase64(_ base64: String) -> UIImage? {
if let url = URL(string: base64) {
if let data = try? Data(contentsOf: url) {
return UIImage(data: data)
}
}
return nil
}
I believe for windows you may use: os.execute("ping 1.1.1.1 /n 1 /w <time in milliseconds> >nul
as a simple timer.
(remove the "<>" when inserting the time in milliseconds) (there is a space between the rest of the code and >nul
)
What you're checking
if(isset($_POST['submit']))
but there's no variable name called "submit".
well i want you to understand why it doesn't works.
lets imagine if you give your submit button name delete
<input type="submit" value="Submit" name="delete" />
and check if(isset($_POST['delete']))
then it works in this code you didn't give any name to submit button and checking its exist or not with isset();
function so php didn't find any variable like "submit" so its not working now try this :
<input type="submit" name="submit" value="Submit" />
I believe what you are looking for is assign_attributes
.
It's basically the same as update_attributes but it doesn't save the record:
class User < ActiveRecord::Base
attr_accessible :name
attr_accessible :name, :is_admin, :as => :admin
end
user = User.new
user.assign_attributes({ :name => 'Josh', :is_admin => true }) # Raises an ActiveModel::MassAssignmentSecurity::Error
user.assign_attributes({ :name => 'Bob'})
user.name # => "Bob"
user.is_admin? # => false
user.new_record? # => true
If you want to solve this issue using async/await:
(async function(){
try {
const response1, response2, response3
response1 = await promise1()
if(response1){
response2 = await promise2()
}
if(response2){
response3 = await promise3()
}
return [response1, response2, response3]
} catch (error) {
return []
}
})()
So after research the following is discovered:
For a div#bar
setting display:block; width: auto;
causes the equivalent of outerWidth:100%;
For a table#bar
you need to wrap it in a div with the rules stated below. So your structure becomes:
<div id="foo">
<div id="barWrap" style="border....">
<table id="bar" style="width: 100%; border: 0; padding: 0; margin: 0;">
This way the table takes up the parent div 100%, and #barWrap
is used to add borders/margin/padding to the #bar
table. Note that you will need to set the background of the whole thing in #barWrap
and have #bar
's background be transparent or the same as #barWrap
.
For textarea#bar
and input#bar
you need to do the same thing as table#bar
, the down side is that by removing the borders you stop native widget rendering of the input/textarea and the #barWrap
's borders will look a bit different than everything else, so you will probably have to style all your inputs this way.
Short answer:
Neither
Longer answer:
using Argument*Exception (except in a library that is a product on its on, such as component library) is a smell. Exceptions are to handle exceptional situation, not bugs, and not user's (i.e. API consumer) shortfalls.
Longest answer:
Throwing exceptions for invalid arguments is rude, unless you write a library.
I prefer using assertions, for two (or more) reasons:
Here is what handling of null exception looks like (being sarcastic, obviously):
try {
library.Method(null);
}
catch (ArgumentNullException e) {
// retry with real argument this time
library.Method(realArgument);
}
Exceptions shall be used when situation is expected but exceptional (things happen that are outside of consumer's control, such as IO failure). Argument*Exception is an indication of a bug and shall be (my opinion) handled with tests and assisted with Debug.Assert
BTW: In this particular case, you could have used Month type, instead of int. C# falls short when it comes to type safety (Aspect# rulez!) but sometimes you can prevent (or catch at compile time) those bugs all together.
And yes, MicroSoft is wrong about that.
You can do:
var buf = Buffer.from(bufStr, 'utf8');
But this is a bit silly, so another suggestion would be to copy the minimal amount of code out of the called function to allow yourself access to the original buffer. This might be quite easy or fairly difficult depending on the details of that library.
You want DateTime.DaysInMonth
:
int days = DateTime.DaysInMonth(year, month);
Obviously it varies by year, as sometimes February has 28 days and sometimes 29. You could always pick a particular year (leap or not) if you want to "fix" it to one value or other.
I was facing the same problem and I've just added one line in my manifest.xml and it worked for me.
tools:replace="android:allowBackup,icon,theme,label,name">
add this line under
<application
android:name=".MyApplication"
android:allowBackup="true"
android:icon="@drawable/launcher"
android:label="@string/app_name"
android:largeHeap="true"
android:screenOrientation="portrait"
android:supportsRtl="true"
android:theme="@style/AppThemecustom"
tools:replace="android:allowBackup,icon,theme,label">
Hope it will help.
First, you should probably use SYSDATETIME()
if you're looking for more precision.
To format your data with milliseconds, try CONVERT(varchar, SYSDATETIME(), 121)
.
For other formats, check out the MSDN page on CAST
and CONVERT
.
SELECT ID from bugs WHERE user=Me ORDER BY CREATED_STAMP DESC; BY CREATED_STAMP DESC fetches those data at index first which last created.
I hope it will resolve your problem
The problem with your code is that when you do
list[] == "e"
you're asking if the array object (not the contents) is equal to the string "e", which is clearly not the case.
You'll want to iterate over the contents in order to do the check you want:
for(String element : list) {
if (element.equals("e")) {
// do something here
}
}
A solution without using imported modules or sets:
text = "ask not what your country can do for you ask what you can do for your country"
sentence = text.split(" ")
noduplicates = [(sentence[i]) for i in range (0,len(sentence)) if sentence[i] not in sentence[:i]]
print(noduplicates)
Gives output:
['ask', 'not', 'what', 'your', 'country', 'can', 'do', 'for', 'you']
$result = mysql_query($query) or die("Data not found.");
$rows=array();
while($r=mysql_fetch_assoc($result))
{
$rows[]=$r;
}
header("Content-type:application/json");
echo json_encode($rows);
Here's the function I use.
function trim(s){
return ( s || '' ).replace( /^\s+|\s+$/g, '' );
}
Set the contentHorizontalAlignment:
emailBtn.contentHorizontalAlignment = .left;
You might also want to adjust the content left inset otherwise the text will touch the left border:
emailBtn.contentEdgeInsets = UIEdgeInsetsMake(0, 10, 0, 0);
// Swift 3 and up:
emailBtn.contentEdgeInsets = UIEdgeInsets(top: 0, left: 10, bottom: 0, right: 0);
Just (array)
is missing in your code before the simplexml object:
...
$xml = simplexml_load_string($string, 'SimpleXMLElement', LIBXML_NOCDATA);
$array = json_decode(json_encode((array)$xml), TRUE);
^^^^^^^
...
I had that problem too.
Try using Server.Transfer
instead of Response.Redirect
Worked for me.
declare @tab table(FirstName varchar(100))
insert into @tab values('John'),('Sarah'),('George')
SELECT *
FROM @tab
WHERE 'John' in (FirstName)
The above answers are good and you can do it in a simple way also.
You can use the recursive method calls.
func vibrateTheDeviceContinuously() throws {
// Added concurrent queue for next & Vibrate device
DispatchQueue.global(qos: .utility).async {
//Vibrate the device
AudioServicesPlaySystemSound(kSystemSoundID_Vibrate)
self.incrementalCount += 1
usleep(800000) // if you don't want, remove this line.
do {
if let isKeepBuzzing = self.iShouldKeepBuzzing , isKeepBuzzing == true {
try self.vibrateTheDeviceContinuously()
}
else {
return
}
} catch {
//Exception handle
print("exception")
}
}
}
To stop the device vibration use the following line.
self.iShouldKeepBuzzing = false
Do you even need them to be input elements in the first place? You can use Javascript to dynamically create divs or paragraphs or list items or whatever that contain the information you want to present.
But if the interactive element is important and it's a pain in the butt to place those elements outside the <form>
block, it ought to be possible to remove those elements from the form when the page gets submitted.
You want to use postgresql's replace function:
replace(string text, from text, to text)
for instance :
UPDATE <table> SET <field> = replace(<field>, 'cat', 'dog')
Be aware, though, that this will be a string-to-string replacement, so 'category' will become 'dogegory'. the regexp_replace function may help you define a stricter match pattern for what you want to replace.
Use substr()
with a negative number for the 2nd argument.
$newstring = substr($dynamicstring, -7);
From the php docs:
string substr ( string $string , int $start [, int $length ] )
If start is negative, the returned string will start at the start'th character from the end of string.
Great answers, but if you look for a singe line do all, you can concatenate, alias and enjoy the convenience:
git add * && git commit -am "<commit message>"
It is a single line but two commands, and as mentioned you can alias these commands:
alias git-aac="git add * && git commit -am "
(the space at the end is important) because you are going to parameterize the new short hand command.
From this moment on, you will be using this alias:
git-acc "<commit message>"
You basically say:
git, add for me all untracked files and commit them with this given commit message.
Hope you use Linux, hope this helps.
Either make your friends download the runtime DLL (@Kay's answer), or compile the app with static linking.
In visual studio, go to Project tab -> properties - > configuration properties -> C/C++ -> Code Generation
on runtime library choose /MTd
for debug mode and /MT
for release mode.
This will cause the compiler to embed the runtime into the app. The executable will be significantly bigger, but it will run without any need of runtime dlls.
The HTML specification never specifies any content formats. That's not its job. There's plenty of standards organizations that are more qualified than the W3C to specify video formats.
That's what content negotiation is for.
<img>
element.<style>
element.<script>
element.<object>
and embed
elements.<audio>
element.Why should it specify one for the <video>
element?
I would suggest looking at the javadoc for Thread class.
You have multiple mechanisms for thread manipulation.
Your main thread could join()
the three threads serially, and would then not proceed until all three are done.
Poll the thread state of the spawned threads at intervals.
Put all of the spawned threads into a separate ThreadGroup
and poll the activeCount()
on the ThreadGroup
and wait for it to get to 0.
Setup a custom callback or listener type of interface for inter-thread communication.
I'm sure there are plenty of other ways I'm still missing.
You should also know that in Python, iterating over integer indices is bad style, and also slower than the alternative. If you just want to look at each of the items in a list or dict, loop directly through the list or dict.
mylist = [1,2,3]
for item in mylist:
print item
mydict = {1:'one', 2:'two', 3:'three'}
for key in mydict:
print key, mydict[key]
This is actually faster than using the above code with range(), and removes the extraneous i
variable.
If you need to edit items of a list in-place, then you do need the index, but there's still a better way:
for i, item in enumerate(mylist):
mylist[i] = item**2
Again, this is both faster and considered more readable. This one of the main shifts in thinking you need to make when coming from C++ to Python.
From the man git-stash
page:
The modifications stashed away by this command can be listed with git stash list, inspected with git stash show
show [<stash>]
Show the changes recorded in the stash as a diff between the stashed state and
its original parent. When no <stash> is given, shows the latest one. By default,
the command shows the diffstat, but it will accept any format known to git diff
(e.g., git stash show -p stash@{1} to view the second most recent stash in patch
form).
To list the stashed modifications
git stash list
To show files changed in the last stash
git stash show
So, to view the content of the most recent stash, run
git stash show -p
To view the content of an arbitrary stash, run something like
git stash show -p stash@{1}
angle(vector.b,vector.a)=pi/2*((1+sgn(xa))*(1-sgn(ya^2))-(1+sgn(xb))*(1-sgn(yb^2)))
+pi/4*((2+sgn(xa))*sgn(ya)-(2+sgn(xb))*sgn(yb))
+sgn(xa*ya)*atan((abs(xa)-abs(ya))/(abs(xa)+abs(ya)))
-sgn(xb*yb)*atan((abs(xb)-abs(yb))/(abs(xb)+abs(yb)))
xb,yb and xa,ya are the coordinates of the two vectors
.htpasswd entries are HASHES. They are not encrypted passwords. Hashes are designed not to be decryptable. Hence there is no way (unless you bruteforce for a loooong time) to get the password from the .htpasswd file.
What you need to do is apply the same hash algorithm to the password provided to you and compare it to the hash in the .htpasswd file. If the user and hash are the same then you're a go.
This usually has to do with a selector not being used properly. Check and make sure that you are using the jQuery selectors like intended. For example I had this problem when creating a click method:
$("[editButton]").click(function () {
this.css("color", "red");
});
Because I was not using the correct selector method $(this) for jQuery it gave me the same error.
So simply enough, check your selectors!
Try creating a shell script like the one below:
#!/bin/bash
mysql --user=[username] --password=[password] --database=[db name] --execute="DELETE FROM tbl_message WHERE DATEDIFF( NOW( ) , timestamp ) >=7"
You can then add this to the cron
The only thing about using telnet to test postfix, or other SMTP, is that you have to know the commands and syntax. Instead, just use swaks :)
thufir@dur:~$
thufir@dur:~$ mail -f Maildir
"/home/thufir/Maildir": 4 messages
> 1 [email protected] 15/553 test Mon, 30 Dec 2013 10:15:12 -0800
2 [email protected] 15/581 test Mon, 30 Dec 2013 10:15:55 -0800
3 [email protected] 15/581 test Mon, 30 Dec 2013 10:29:57 -0800
4 [email protected] 15/581 test Mon, 30 Dec 2013 11:54:16 -0800
? q
Held 4 messages in /home/thufir/Maildir
thufir@dur:~$
thufir@dur:~$ swaks --to [email protected]
=== Trying dur.bounceme.net:25...
=== Connected to dur.bounceme.net.
<- 220 dur.bounceme.net ESMTP Postfix (Ubuntu)
-> EHLO dur.bounceme.net
<- 250-dur.bounceme.net
<- 250-PIPELINING
<- 250-SIZE 10240000
<- 250-VRFY
<- 250-ETRN
<- 250-STARTTLS
<- 250-ENHANCEDSTATUSCODES
<- 250-8BITMIME
<- 250 DSN
-> MAIL FROM:<[email protected]>
<- 250 2.1.0 Ok
-> RCPT TO:<[email protected]>
<- 250 2.1.5 Ok
-> DATA
<- 354 End data with <CR><LF>.<CR><LF>
-> Date: Mon, 30 Dec 2013 14:33:17 -0800
-> To: [email protected]
-> From: [email protected]
-> Subject: test Mon, 30 Dec 2013 14:33:17 -0800
-> X-Mailer: swaks v20130209.0 jetmore.org/john/code/swaks/
->
-> This is a test mailing
->
-> .
<- 250 2.0.0 Ok: queued as 52D162C3EFF
-> QUIT
<- 221 2.0.0 Bye
=== Connection closed with remote host.
thufir@dur:~$
thufir@dur:~$ mail -f Maildir
"/home/thufir/Maildir": 5 messages 1 new
1 [email protected] 15/553 test Mon, 30 Dec 2013 10:15:12 -0800
2 [email protected] 15/581 test Mon, 30 Dec 2013 10:15:55 -0800
3 [email protected] 15/581 test Mon, 30 Dec 2013 10:29:57 -0800
4 [email protected] 15/581 test Mon, 30 Dec 2013 11:54:16 -0800
>N 5 [email protected] 15/581 test Mon, 30 Dec 2013 14:33:17 -0800
? 5
Return-Path: <[email protected]>
X-Original-To: [email protected]
Delivered-To: [email protected]
Received: from dur.bounceme.net (localhost [127.0.0.1])
by dur.bounceme.net (Postfix) with ESMTP id 52D162C3EFF
for <[email protected]>; Mon, 30 Dec 2013 14:33:17 -0800 (PST)
Date: Mon, 30 Dec 2013 14:33:17 -0800
To: [email protected]
From: [email protected]
Subject: test Mon, 30 Dec 2013 14:33:17 -0800
X-Mailer: swaks v20130209.0 jetmore.org/john/code/swaks/
Message-Id: <[email protected]>
This is a test mailing
New mail has arrived.
? q
Held 5 messages in /home/thufir/Maildir
thufir@dur:~$
It's just one easy command.
No, there's no direct not operator. At least not the way you hope for.
You can use a zero-width negative lookahead, however:
\((?!2001)[0-9a-zA-z _\.\-:]*\)
The (?!...)
part means "only match if the text following (hence: lookahead) this doesn't (hence: negative) match this. But it doesn't actually consume the characters it matches (hence: zero-width).
There are actually 4 combinations of lookarounds with 2 axes:
Pragma mark is a way to improve the readability of your code. The pragma comments would appear like tags on the Xcode jumpbar.
//MARK: <Your comment goes here>
Example: In the code,
//MARK: Properties
// MARK: View Life cycle
//MARK: Helper methods
This is how it would appear in the Xcode jump bar.
You could also do something like this :
const str = "hi, there"_x000D_
_x000D_
const res = str.includes("hello") || str.includes("hi") || str.includes('howdy');_x000D_
_x000D_
console.log(res);
_x000D_
Whenever one of your includes return true, value will be true, otherwise, it's going to be false. This works perfectly fine with ES6.
Try =index(ARRAY, ROW, COLUMN)
where: Array: select the whole sheet Row, Column: Your row and column references
That should be easier to understand to those looking at the formula.
If you are running SQL Server 2012 or newer you can also use the new TRY_PARSE() function:
Returns the result of an expression, translated to the requested data type, or null if the cast fails in SQL Server. Use TRY_PARSE only for converting from string to date/time and number types.
Or TRY_CONVERT/TRY_CAST:
Returns a value cast to the specified data type if the cast succeeds; otherwise, returns null.
@elcool's solution is a smart idea, but you need to know total number of rows (which can even change while you are executing the query!). So I propose a modified version, which unfortunately needs 3 subqueries instead of 2:
select * from (
select * from (
select * from MYLIB.MYTABLE
order by MYID asc
fetch first {last} rows only
) I
order by MYID desc
fetch first {length} rows only
) II
order by MYID asc
where {last}
should be replaced with row number of the last record I need and {length}
should be replaced with the number of rows I need, calculated as last row - first row + 1
.
E.g. if I want rows from 10 to 25 (totally 16 rows), {last}
will be 25 and {length}
will be 25-10+1=16.
Another method to try out.
Also select
could be replaced when you set the initial column into a Range object. Performance wise it helps.
Dim rng as Range
Set rng = WorkSheets(1).Range("A1") '-- you may change the sheet name according to yours.
'-- here is your loop
i = 1
Do
'-- do something: e.g. show the address of the column that you are currently in
Msgbox rng.offset(0,i).Address
i = i + 1
Loop Until i > 10
** Two methods to get the column name using column number**
code
colName = Split(Range.Offset(0,i).Address, "$")(1)
code
Function myColName(colNum as Long) as String
myColName = Left(Range(0, colNum).Address(False, False), _
1 - (colNum > 10))
End Function
You can save the current cookies as a Python object using pickle. For example:
import pickle
import selenium.webdriver
driver = selenium.webdriver.Firefox()
driver.get("http://www.google.com")
pickle.dump( driver.get_cookies() , open("cookies.pkl","wb"))
And later to add them back:
import pickle
import selenium.webdriver
driver = selenium.webdriver.Firefox()
driver.get("http://www.google.com")
cookies = pickle.load(open("cookies.pkl", "rb"))
for cookie in cookies:
driver.add_cookie(cookie)
In Visual Studio: Tools -> Options -> Environment -> Keyboard -> Reset
Your code works. If you don't have any output, you may have "forgotten" to add some values to the list:
// add values
list.add("one");
list.add("two");
// your code
for (String object: list) {
System.out.println(object);
}
To complete the answer of @usethe4ce, if you have more than one device or emulators, the adb tcpip 5555
will give error: more than one device/emulator
.
In this case you need to give the serial number of the desired device:
adb devices
List of devices attached
33001229 device
emulator-5554 device
adb -s 33001229 tcpip 5555
adb connect xxx.xxx.xxx.xxx:5555
Agree with AshisKumar's answer,
there is a way to change image url on mouse over by using jQuery functionality as below:
$(function() {
$("img")
.mouseover(function() {
var src = $(this).attr("src").match(/[^\.]+/) + "over.gif";
$(this).attr("src", url1); //URL @the time of mouse over on image
})
.mouseout(function() {
var src = $(this).attr("src").replace("over", "");
$(this).attr("src", url2); //default URL
});
});
Best way is with a pre_save
signal. May not have been an option back in '09 when this question was asked and answered, but anyone seeing this today should do it this way:
@receiver(pre_save, sender=MyModel)
def do_something_if_changed(sender, instance, **kwargs):
try:
obj = sender.objects.get(pk=instance.pk)
except sender.DoesNotExist:
pass # Object is new, so field hasn't technically changed, but you may want to do something else here.
else:
if not obj.some_field == instance.some_field: # Field has changed
# do something
Firstly, if you're doing MVVM you would typically have this information available to your VM via separate properties bound from the view. That saves you having to pass any parameters at all to your commands.
However, you could also multi-bind and use a converter to create the parameters:
<Button Content="Zoom" Command="{Binding MyViewModel.ZoomCommand">
<Button.CommandParameter>
<MultiBinding Converter="{StaticResource YourConverter}">
<Binding Path="Width" ElementName="MyCanvas"/>
<Binding Path="Height" ElementName="MyCanvas"/>
</MultiBinding>
</Button.CommandParameter>
</Button>
In your converter:
public class YourConverter : IMultiValueConverter
{
public object Convert(object[] values, ...)
{
return values.Clone();
}
...
}
Then, in your command execution logic:
public void OnExecute(object parameter)
{
var values = (object[])parameter;
var width = (double)values[0];
var height = (double)values[1];
}
In my case, I could not get the answer by @Sampson to work for me, at best I got a single column centered on the page. In the process however, I learned how the float actually works and created this solution. At it's core the fix is very simple but hard to find as evident by this thread which has had more than 146k views at the time of this post without mention.
All that is needed is to total the amount of screen space width that the desired layout will occupy then make the parent the same width and apply margin:auto. That's it!
The elements in the layout will dictate the width and height of the "outer" div. Take each "myFloat" or element's width or height + its borders + its margins and its paddings and add them all together. Then add the other elements together in the same fashion. This will give you the parent width. They can all be somewhat different sizes and you can do this with fewer or more elements.
Ex.(each element has 2 sides so border, margin and padding get multiplied x2)
So an element that has a width of 10px, border 2px, margin 6px, padding 3px would look like this: 10 + 4 + 12 + 6 = 32
Then add all of your element's totaled widths together.
Element 1 = 32
Element 2 = 24
Element 3 = 32
Element 4 = 24
In this example the width for the "outer" div would be 112.
.outer {_x000D_
/* floats + margins + borders = 270 */_x000D_
max-width: 270px;_x000D_
margin: auto;_x000D_
height: 80px;_x000D_
border: 1px;_x000D_
border-style: solid;_x000D_
}_x000D_
_x000D_
.myFloat {_x000D_
/* 3 floats x 50px = 150px */_x000D_
width: 50px;_x000D_
/* 6 margins x 10px = 60 */_x000D_
margin: 10px;_x000D_
/* 6 borders x 10px = 60 */_x000D_
border: 10px solid #6B6B6B;_x000D_
float: left;_x000D_
text-align: center;_x000D_
height: 40px;_x000D_
}
_x000D_
<div class="outer">_x000D_
<div class="myFloat">Float 1</div>_x000D_
<div class="myFloat">Float 2</div>_x000D_
<div class="myFloat">Float 3</div>_x000D_
</div>
_x000D_
A TINYINT is an 8-bit integer value, a BIT field can store between 1 bit, BIT(1), and 64 bits, BIT(64). For a boolean values, BIT(1) is pretty common.
Well, I'm not sure to understand your question...
In C, Char[] and Char* are the same thing.
Edit : thanks for this interesting link.
You might also want to consider the Android specific TextUtils.split() method.
The difference between TextUtils.split() and String.split() is documented with TextUtils.split():
String.split() returns [''] when the string to be split is empty. This returns []. This does not remove any empty strings from the result.
I find this a more natural behavior. In essence TextUtils.split() is just a thin wrapper for String.split(), dealing specifically with the empty-string case. The code for the method is actually quite simple.
I was searching for a similar simple C++ config file parser and this tutorial website provided me with a basic yet working solution. Its quick and dirty soultion to get the job done.
myConfig.txt
gamma=2.8
mode = 1
path = D:\Photoshop\Projects\Workspace\Images\
The following program reads the previous configuration file:
#include <iostream>
#include <fstream>
#include <algorithm>
#include <string>
int main()
{
double gamma = 0;
int mode = 0;
std::string path;
// std::ifstream is RAII, i.e. no need to call close
std::ifstream cFile("myConfig.txt");
if (cFile.is_open())
{
std::string line;
while (getline(cFile, line))
{
line.erase(std::remove_if(line.begin(), line.end(), isspace),line.end());
if (line[0] == '#' || line.empty()) continue;
auto delimiterPos = line.find("=");
auto name = line.substr(0, delimiterPos);
auto value = line.substr(delimiterPos + 1);
//Custom coding
if (name == "gamma") gamma = std::stod(value);
else if (name == "mode") mode = std::stoi(value);
else if (name == "path") path = value;
}
}
else
{
std::cerr << "Couldn't open config file for reading.\n";
}
std::cout << "\nGamma=" << gamma;
std::cout << "\nMode=" << mode;
std::cout << "\nPath=" << path;
std::getchar();
}
For Symfony 3.2 and above use this,
public function buildErrorArray(FormInterface $form)
{
$errors = array();
foreach ($form->getErrors() as $key => $error) {
if ($form->isRoot()) {
$errors['#'][] = $error->getMessage();
} else {
$errors[] = $error->getMessage();
}
}
foreach ($form->all() as $child) {
if (!$child->isValid()) {
$errors[$child->getName()] = (string) $child->getErrors(true, false);
}
}
return $errors;
}
Use str_replace if you want to get rid of the annoying 'Error:' text in each error description text.
$errors[$child->getName()] = str_replace('ERROR:', '', (string) $child->getErrors(true, false));
If you are using babelify and watchify, go to:
package.json
and add this in "scripts":
"scripts": {
"start": "watchify the-path-to-your-source-jsx-file -v -t [ babelify --presets [ react ] ] -o the-path-to-your-output-js-file"
}
An example would be:
"scripts": {
"start": "watchify src/main.jsx -v -t [ babelify --presets [ react ] ] -o public/js/main.js"
}
Thanks to Mark Price from DevSlopes
I just had this error message running IIS Express in Visual Studio 2015. In my case I needed to be running the 64 bit version of IIS Express:
Tools ? Options ? Projects and Solutions ? Web Projects
Check the box that says "Use the 64 bit version of IIS Express for web sites and projects".
Screenshot:
mkdir -p Python/Beginner/CH01 && touch $_/hello_world.py
Explanation: -p -> use -p if you wanna create parent and child directories $_ -> use it for current directory we work with it inline
That's what I do and it works great for me, and many others. First, find the length of the video in the below snippet:
Seems stream 0 codec frame rate differs from container frame rate: 5994.00
(5994/1) -> 29.97 (30000/1001)
Input #0, mov,mp4,m4a,3gp,3g2,mj2, from '/Users/stu/Movies/District9.mov':
Duration: 00:02:32.20, start: 0.000000, bitrate: 9808 kb/s
Stream #0.0(eng): Video: h264, yuv420p, 1920x1056, 29.97tbr, 2997tbn, 5994tbc
Stream #0.1(eng): Audio: aac, 44100 Hz, 2 channels, s16
Stream #0.2(eng): Data: tmcd / 0x64636D74
You'll should be able to consistently and safely find Duration: hh:mm:ss.nn
to determine the source video clip size. Then, for each update line (CR, no LF) you can parse the text for the current time mark it is at:
frame= 84 fps= 18 q=10.0 size= 5kB time=1.68 bitrate= 26.1kbits/s
frame= 90 fps= 17 q=10.0 size= 6kB time=1.92 bitrate= 23.8kbits/s
frame= 94 fps= 16 q=10.0 size= 232kB time=2.08 bitrate= 913.0kbits/s
Just be careful to not always expect perfect output from these status lines. They can include error messages like here:
frame= 24 fps= 24 q=-1.0 size= 0kB time=1.42 bitrate= 0.3kbits/s
frame= 41 fps= 26 q=-1.0 size= 0kB time=2.41 bitrate= 0.2kbits/s
[h264 @ 0x1013000]Cannot parallelize deblocking type 1, decoding such frames in
sequential order
frame= 49 fps= 24 q=26.0 size= 4kB time=0.28 bitrate= 118.1kbits/s
frame= 56 fps= 22 q=23.0 size= 4kB time=0.56 bitrate= 62.9kbits/s
Once you have the time, it is simple math: time / duration * 100 = % done
.
AttributeError is raised when attribute of the object is not available.
An attribute reference is a primary followed by a period and a name:
attributeref ::= primary "." identifier
To return a list of valid attributes for that object, use dir()
, e.g.:
dir(scipy)
So probably you need to do simply: import scipy.sparse
To expand on user8266077's answer, I found that I still needed to supply OPTIONS response for preflight requests in .NET Core 2.1-preview for my use case:
// https://stackoverflow.com/a/45844400
public class CorsMiddleware
{
private readonly RequestDelegate _next;
public CorsMiddleware(RequestDelegate next)
{
_next = next;
}
public async Task Invoke(HttpContext context)
{
context.Response.Headers.Add("Access-Control-Allow-Origin", "*");
context.Response.Headers.Add("Access-Control-Allow-Credentials", "true");
// Added "Accept-Encoding" to this list
context.Response.Headers.Add("Access-Control-Allow-Headers", "Content-Type, X-CSRF-Token, X-Requested-With, Accept, Accept-Version, Accept-Encoding, Content-Length, Content-MD5, Date, X-Api-Version, X-File-Name");
context.Response.Headers.Add("Access-Control-Allow-Methods", "POST,GET,PUT,PATCH,DELETE,OPTIONS");
// New Code Starts here
if (context.Request.Method == "OPTIONS")
{
context.Response.StatusCode = (int)HttpStatusCode.OK;
await context.Response.WriteAsync(string.Empty);
}
// New Code Ends here
await _next(context);
}
}
and then enabled the middleware like so in Startup.cs
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
app.UseMiddleware(typeof(CorsMiddleware));
// ... other middleware inclusion such as ErrorHandling, Caching, etc
app.UseMvc();
}
My answer directly inspired from @valex very usefull, if you need several cols in the ORDER BY clause.
SELECT u.*
FROM users AS u
INNER JOIN (
SELECT p.*,
@num := if(@id = user_id, @num + 1, 1) as row_number,
@id := user_id as tmp
FROM (SELECT * FROM payments ORDER BY p.user_id ASC, date DESC) AS p,
(SELECT @num := 0) x,
(SELECT @id := 0) y
)
ON (p.user_id = u.id) and (p.row_number=1)
WHERE u.package = 1
SIGTERM is used to restart Apache (provided that it's setup in init to auto-restart): http://httpd.apache.org/docs/2.2/stopping.html
The entries you see in the logs are almost certainly there because your provider used SIGTERM for that purpose. If it's truly crashing, not even serving static content, then that sounds like some sort of a thread/connection exhaustion issue. Perhaps a DoS that holds connections open?
Should definitely be something for your provider to investigate.
This is a common question, and I was heavily on the side wanting the ability to mock HttpClient, but I think I finally came to the realization that you shouldn't be mocking HttpClient. It seems logical to do so, but I think we've been brainwashed by things we see in open source libraries.
We often see "Clients" out there that we mock in our code so that we can test in isolation, so we automatically try to apply the same principle to HttpClient. HttpClient actually does a lot; you can think of it as a manager for HttpMessageHandler, so you don't wanna mock that, and that's why it still doesn't have an interface. The part that you're really interested in for unit testing, or designing your services, even, is the HttpMessageHandler since that is what returns the response, and you can mock that.
It's also worth pointing out that you should probably start treating HttpClient like a bigger deal. For example: Keep your instatiating of new HttpClients to a minimum. Reuse them, they're designed to be reused and use a crap ton less resources if you do. If you start treating it like a bigger deal, it'll feel much more wrong wanting to mock it and now the message handler will start to be the thing that you're injecting, not the client.
In other words, design your dependencies around the handler instead of the client. Even better, abstract "services" that use HttpClient which allow you to inject a handler, and use that as your injectable dependency instead. Then in your tests, you can fake the handler to control the response for setting up your tests.
Wrapping HttpClient is an insane waste of time.
Update: See Joshua Dooms's example. It's exactly what I'm recommending.
Try this:
filed like "*AA*" and filed not like "*BB*"
From 2012 onward we can use
OFFSET 10 ROWS FETCH NEXT 10 ROWS ONLY
If you write both back and frontend, another simple solution is to attach a "/" at the end of the URL at front. If so, you don't need to change your backend...
somepath/[email protected]/
Be happy!
The easiest might be:
Array(1, 2, 3) :+ 4
Actually, Array can be implcitly transformed in a WrappedArray
Define class method:
class Foo(object):
bar = 1
@classmethod
def bah(cls):
print cls.bar
Now if bah()
has to be instance method (i.e. have access to self), you can still directly access the class variable.
class Foo(object):
bar = 1
def bah(self):
print self.bar
// Factory returns object and ownership
// Caller responsible for deletion.
#include <memory>
class FactoryReleaseOwnership{
public:
std::unique_ptr<Foo> createFooInSomeWay(){
return std::unique_ptr<Foo>(new Foo(some, args));
}
};
// Factory retains object ownership
// Thus returning a reference.
#include <boost/ptr_container/ptr_vector.hpp>
class FactoryRetainOwnership{
boost::ptr_vector<Foo> myFoo;
public:
Foo& createFooInSomeWay(){
// Must take care that factory last longer than all references.
// Could make myFoo static so it last as long as the application.
myFoo.push_back(new Foo(some, args));
return myFoo.back();
}
};
I have a stupid idea:
public class Pegasus {
private Horse horseFeatures;
private Bird birdFeatures;
public Pegasus(Horse horse, Bird bird) {
this.horseFeatures = horse;
this.birdFeatures = bird;
}
public void jump() {
horseFeatures.jump();
}
public void fly() {
birdFeatures.fly();
}
}
1st way is to use props
<Row id = "someRandomID">
Wherein, in the Definition, you may just go
const Row = props => {
div id = {props.id}
}
The same could be done with class, replacing id with className in the above example.
You might as well use react-html-id
, that is an npm package.
This is an npm package that allows you to use unique html IDs for components without any dependencies on other libraries.
Ref: react-html-id
Peace.
Not sure if this answers this question. But I was looking for something else. Highly recommend see this 2 minute video. If you wanted to get into more details then see docs - Handling Parameters and this link
And then if you have something like blue ocean, the choices would look something like this:
You define and access your variables like this:
pipeline {
agent any
parameters {
string(defaultValue: "TEST", description: 'What environment?', name: 'userFlag')
choice(choices: ['TESTING', 'STAGING', 'PRODUCTION'], description: 'Select field for target environment', name: 'DEPLOY_ENV')
}
stages {
stage("foo") {
steps {
echo "flag: ${params.userFlag}"
echo "flag: ${params.DEPLOY_ENV}"
}
}
}
}
Automated builds will pick up the default params. But if you do it manually then you get the option to choose.
And then assign values like this:
nth-last-child
sounds like it was specifically designed to solve this problem, so I doubt whether there is a more compatible alternative. Support looks pretty decent, though.
I was getting windows security alert whenever my application was opening. to resolve this issue i used following procedure
import org.openqa.selenium.security.UserAndPassword;
UserAndPassword UP = new UserAndPassword("userName","Password");
driver.switchTo().alert().authenticateUsing(UP);
this resolved my issue of logging into application. I hope this might help who are all looking for authenticating windows security alert.
This is not Windows, you do not "run the Terminal as admin". What you do is you run commands in the terminal as admin, typically using sudo
:
$ sudo some command here
You can replace the values "null" from the original file & field/column.
Here you are trying to execute IQueryable object on inactive DBContext. your DBcontext is already disposed of. you can only execute IQueryable object before DBContext is disposed of. Means you need to write users.Select(x => x.ToInfo()).ToList()
statement inside using scope
Try something like this in your aspx page
<asp:Label ID="myLabel" runat="server"></asp:Label>
and then in your codebehind you can just do
myLabel.Text = "My Label";
As mentioned, in Swift most of the time you can achieve what you need with the ?
optional unwrapper operator. This allows you to call a method on an object if and only if the object exists (not nil
) and the method is implemented.
In the case where you still need respondsToSelector:
, it is still there as part of the NSObject
protocol.
If you are calling respondsToSelector:
on an Obj-C type in Swift, then it works the same as you would expect. If you are using it on your own Swift class, you will need to ensure your class derives from NSObject
.
Here's an example of a Swift class that you can check if it responds to a selector:
class Worker : NSObject
{
func work() { }
func eat(food: AnyObject) { }
func sleep(hours: Int, minutes: Int) { }
}
let worker = Worker()
let canWork = worker.respondsToSelector(Selector("work")) // true
let canEat = worker.respondsToSelector(Selector("eat:")) // true
let canSleep = worker.respondsToSelector(Selector("sleep:minutes:")) // true
let canQuit = worker.respondsToSelector(Selector("quit")) // false
It is important that you do not leave out the parameter names. In this example, Selector("sleep::")
is not the same as Selector("sleep:minutes:")
.
You can try the following code to get time as HH:MM format:
SELECT CONVERT(VARCHAR(5),getdate(),108)
I really like the accepted answer but I want to add this:
Scope collects and maintains a look-up list of all the declared identifiers (variables), and enforces a strict set of rules as to how these are accessible to currently executing code.
Scope is a set of rules for looking up variables by their identifier name.
If it doesn't/wouldn't run on the CPU, it's a script to me. If an interpreter needs to run on the CPU below the program, then it's a script and a scripting language.
No reason to make it any more complicated than this?
Of course, in most (99%) of cases, it's clear whether a language is a scripting language. But consider that a VM can emulate the x86 instruction set, for example. Wouldn't this make the x86 bytecode a scripting language when run on a VM? What if someone was to write a compiler that would turn perl code into a native executable? In this case, I wouldn't know what to call the language itself anymore. It'd be the output that would matter, not the language.
Then again, I'm not aware of anything like this having been done, so for now I'm still comfortable calling interpreted languages scripting languages.
One option that is available is fooTable. Works great on a Responsive website and allows you to set multiple breakpoints... fooTable Link
This solution will apply to a very small percentage of people, typically people implementing their own JUnit test runners and using a separate ClassLoader.
This can happen when you load a class from a different ClassLoader, then attempt to run that test from an instance of JUnitCore loaded from the system class loader. Example:
// Load class
URLClassLoader cl = new URLClassLoader(myTestUrls, null);
Class<?>[] testCls = cl.loadClass("com.gubby.MyTest");
// Run test
JUnitCore junit = new JUnitCore();
junit.run(testCls); // Throws java.lang.Exception: No runnable methods
Looking at the stack trace:
java.lang.Exception: No runnable methods
at org.junit.runners.BlockJUnit4ClassRunner.validateInstanceMethods(BlockJUnit4ClassRunner.java:169)
at org.junit.runners.BlockJUnit4ClassRunner.collectInitializationErrors(BlockJUnit4ClassRunner.java:104)
at org.junit.runners.ParentRunner.validate(ParentRunner.java:355)
at org.junit.runners.ParentRunner.<init>(ParentRunner.java:76)
at org.junit.runners.BlockJUnit4ClassRunner.<init>(BlockJUnit4ClassRunner.java:57)
at org.junit.internal.builders.JUnit4Builder.runnerForClass(JUnit4Builder.java:10)
at org.junit.runners.model.RunnerBuilder.safeRunnerForClass(RunnerBuilder.java:59)
at org.junit.internal.builders.AllDefaultPossibilitiesBuilder.runnerForClass(AllDefaultPossibilitiesBuilder.java:26)
at org.junit.runners.model.RunnerBuilder.safeRunnerForClass(RunnerBuilder.java:59)
at org.junit.internal.requests.ClassRequest.getRunner(ClassRequest.java:26)
at org.junit.runner.JUnitCore.run(JUnitCore.java:138)
The problem actually occurs at BlockJUnit4ClassRunner:169 (assuming JUnit 4.11):
Where it checks which methods are annotated with @Test
:
protected List<FrameworkMethod> computeTestMethods() {
return getTestClass().getAnnotatedMethods(Test.class);
}
In this case, Test.class
will have been loaded with the system ClassLoader (i.e. the one that loaded JUnitCore), therefore technically none of your test methods will have been annotated with that annotation.
Solution is to load JUnitCore in the same ClassLoader as the tests themselves.
Edit: In answer to the question from user3486675, you need to create a ClassLoader that doesn't delegate to the system class loader, e.g.:
private static final class IsolatedURLClassLoader extends URLClassLoader {
private IsolatedURLClassLoader(URL[] urls) {
// Prevent delegation to the system class loader.
super(urls, null);
}
}
Pass this a set of URLs that includes everything you need. You can create this by filtering the system classpath. Note that you cannot simply delegate to the parent ClassLoader, because those classes would then get loaded by that rather than the ClassLoader of your test classes.
Then you need to kick off the whole JUnit job from a class loaded by this ClassLoader. It gets messy here. Something like this utter filth below:
public static final class ClassLoaderIsolatedTestRunner {
public ClassLoaderIsolatedTestRunner() {
// Disallow construction at all from wrong ClassLoader
ensureLoadedInIsolatedClassLoader(this);
}
// Do not rename.
public void run_invokedReflectively(List<String> testClasses) throws BuildException {
// Make sure we are not accidentally working in the system CL
ensureLoadedInIsolatedClassLoader(this);
// Load classes
Class<?>[] classes = new Class<?>[testClasses.size()];
for (int i=0; i<testClasses.size(); i++) {
String test = testClasses.get(i);
try {
classes[i] = Class.forName(test);
} catch (ClassNotFoundException e) {
String msg = "Unable to find class file for test ["+test+"]. Make sure all " +
"tests sources are either included in this test target via a 'src' " +
"declaration.";
throw new BuildException(msg, e);
}
}
// Run
JUnitCore junit = new JUnitCore();
ensureLoadedInIsolatedClassLoader(junit);
junit.addListener(...);
junit.run(classes);
}
private static void ensureLoadedInIsolatedClassLoader(Object o) {
String objectClassLoader = o.getClass().getClassLoader().getClass().getName();
// NB: Can't do instanceof here because they are not instances of each other.
if (!objectClassLoader.equals(IsolatedURLClassLoader.class.getName())) {
throw new IllegalStateException(String.format(
"Instance of %s not loaded by a IsolatedURLClassLoader (loaded by %s)",
cls, objectClassLoader));
}
}
}
THEN, you need to invoke the runner via reflection:
Class<?> runnerClass = isolatedClassLoader.loadClass(ClassLoaderIsolatedTestRunner.class.getName());
// Invoke via reflection (List.class is OK because it just uses the string form of it)
Object runner = runnerClass.newInstance();
Method method = runner.getClass().getMethod("run_invokedReflectively", List.class);
method.invoke(...);
Matthew Brindley, your code worked very good for some website I needed (with login), but I needed to change to HttpWebRequest
and HttpWebResponse
otherwise I get a 404 Bad Request from the remote server. Also I would like to share my workaround using your code, and is that I tried it to login to a website based on moodle, but it didn't work at your step "GETting the page behind the login form" because when successfully POSTing the login, the Header 'Set-Cookie'
didn't return anything despite other websites does.
So I think this where we need to store cookies for next Requests, so I added this.
To the "POSTing to the login form" code block :
var cookies = new CookieContainer();
HttpWebRequest req = (HttpWebRequest)WebRequest.Create(formUrl);
req.CookieContainer = cookies;
And To the "GETting the page behind the login form" :
HttpWebRequest getRequest = (HttpWebRequest)WebRequest.Create(getUrl);
getRequest.CookieContainer = new CookieContainer();
getRequest.CookieContainer.Add(resp.Cookies);
getRequest.Headers.Add("Cookie", cookieHeader);
Doing this, lets me Log me in and get the source code of the "page behind login" (website based moodle) I know this is a vague use of the CookieContainer
and HTTPCookies because we may ask first is there a previously set of cookies saved before sending the request to the server. This works without problem anyway, but here's a good info to read about WebRequest
and WebResponse
with sample projects and tutorial:
Retrieving HTTP content in .NET
How to use HttpWebRequest and HttpWebResponse in .NET
12 years later for anyone having similar problems.
try:
s.connect((address, '80'))
except:
alert('failed' + address, 'down')
doesn't work because the port '80' is a string. Your port needs to be int.
try:
s.connect((address, 80))
This should work. Not sure why even the best answer didnt see this.
There seems to be no problem since the int to bool cast is done implicitly. This works in Microsoft Visual C++, GCC and Intel C++ compiler. No problem in either C or C++.
Thanks for the answer @srohde. It has a small bug checking for newline character with 'is' operator, and I could not comment on the answer with 1 reputation. Also I'd like to manage file open outside because that enables me to embed my ramblings for luigi tasks.
What I needed to change has the form:
with open(filename) as fp:
for line in fp:
#print line, # contains new line
print '>{}<'.format(line)
I'd love to change to:
with open(filename) as fp:
for line in reversed_fp_iter(fp, 4):
#print line, # contains new line
print '>{}<'.format(line)
Here is a modified answer that wants a file handle and keeps newlines:
def reversed_fp_iter(fp, buf_size=8192):
"""a generator that returns the lines of a file in reverse order
ref: https://stackoverflow.com/a/23646049/8776239
"""
segment = None # holds possible incomplete segment at the beginning of the buffer
offset = 0
fp.seek(0, os.SEEK_END)
file_size = remaining_size = fp.tell()
while remaining_size > 0:
offset = min(file_size, offset + buf_size)
fp.seek(file_size - offset)
buffer = fp.read(min(remaining_size, buf_size))
remaining_size -= buf_size
lines = buffer.splitlines(True)
# the first line of the buffer is probably not a complete line so
# we'll save it and append it to the last line of the next buffer
# we read
if segment is not None:
# if the previous chunk starts right from the beginning of line
# do not concat the segment to the last line of new chunk
# instead, yield the segment first
if buffer[-1] == '\n':
#print 'buffer ends with newline'
yield segment
else:
lines[-1] += segment
#print 'enlarged last line to >{}<, len {}'.format(lines[-1], len(lines))
segment = lines[0]
for index in range(len(lines) - 1, 0, -1):
if len(lines[index]):
yield lines[index]
# Don't yield None if the file was empty
if segment is not None:
yield segment
you can use the following command to list the process
ps aux | grep -c myProcessName
if you need to check the count of that process then run
ps aux | grep -c myProcessName |grep -v grep
after which you can kill the process using
kill -9 $(ps aux | grep -e myProcessName | awk '{ print $2 }')
I just ran into this.
If you're not seeing curl in the list (see ibaralf's screenshot), then you may have out-of-date cygwin sources. In one of the screens in cygwin's setup.exe wizard, you have the option to "Install from Internet" or "Install from Local Directory". If you have the "Install from Local Directory" option enabled, then you may not see curl in the list. Switch to "Install from Internet" and select a mirror and then you should see curl.
Here's one reason you shouldn't use it: it's going to piss off most anti-virus programs running on Windows if you're passing the program over to another machine because it's a security threat. Even if your program only consists of a simple cout << "hello world\n"; system("pause");
It's resource heavy and the program gets access to the cmd command, which anti viruses see as a threat.
When using MatAutocompleteModule in your angular application, you need to import Input Module also in app.module.ts
Please import below:
import { MatInputModule } from '@angular/material';
This can also be done in the GUI:
Just be aware that on Unix/Linux your username/password can be seen by anyone that can run "ps -ef" command if you place it directly on the command line . Could be a big security issue (or turn into a big security issue).
I usually recommend creating a file or using here document so you can protect the username/password from being viewed with "ps -ef" command in Unix/Linux. If the username/password is contained in a script file or sql file you can protect using appropriate user/group read permissions. Then you can keep the user/pass inside the file like this in a shell script:
sqlplus -s /nolog <<EOF
connect user/pass
select blah;
quit
EOF
You need something like:
URL resource = this.getClass().getResource("/path/to/resource.res");
File is = null;
try {
is = new File(resource.toURI());
} catch (URISyntaxException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
try {
FileInputStream input = new FileInputStream(is);
} catch (FileNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
But it will work only within your IDE, not in runnable JAR. I had same problem explained here.
$('#btn1, #btn2').click(function() {
let clickedButton = $(this).attr('id');
console.log(clickedButton);
});
File.Move(@"c:\filename", @"c:\filenamet\filename.txt");
On CentOS Linux, Python3.6, I edited this file (make a backup copy first)
/usr/lib/python3.6/site-packages/certifi/cacert.pem
to the end of the file, I added my public certificate from my .pem file. you should be able to obtain the .pem file from your ssl certificate provider.
Change your systemPath.
<dependency>
<groupId>stuff</groupId>
<artifactId>library</artifactId>
<version>1.0</version>
<systemPath>${project.basedir}/MyLibrary.jar</systemPath>
<scope>system</scope>
</dependency>
In the version 3.2.4 of the XAMPP Control Panel, there is button that can open a command line prompt (red rectangle in the next figure)
After pressing the button, you will see the command prompt window.
From this window you can navigate through the different folders and start the different services available.
Add this is work for me
<repositories>
<!-- Repository for ORACLE JDBC Driver -->
<repository>
<id>codelds</id>
<url>https://code.lds.org/nexus/content/groups/main-repo</url>
</repository>
</repositories>
When creating a function, a property object called prototype is being created automatically (you didn't create it yourself) and is being attached to the function object (the constructor
).
Note: This new prototype object also points to, or has an internal-private link to, the native JavaScript Object.
Example:
function Foo () {
this.name = 'John Doe';
}
// Foo has an object property called prototype.
// prototype was created automatically when we declared the function Foo.
Foo.hasOwnProperty('prototype'); // true
// Now, we can assign properties and methods to it:
Foo.prototype.myName = function () {
return 'My name is ' + this.name;
}
If you create a new object out of Foo
using the new
keyword, you are basically creating (among other things) a new object that has an internal or private link to the function Foo
's prototype we discussed earlier:
var b = new Foo();
b.[[Prototype]] === Foo.prototype // true
[[Prototype]]
. Many browsers are providing us a public linkage to it that called __proto__
!
To be more specific, __proto__
is actually a getter function that belong to the native JavaScript Object. It returns the internal-private prototype linkage of whatever the this
binding is (returns the [[Prototype]]
of b
):
b.__proto__ === Foo.prototype // true
It is worth noting that starting of ECMAScript5
, you can also use the getPrototypeOf method to get the internal private linkage:
Object.getPrototypeOf(b) === b.__proto__ // true
__proto__
, prototype
and [[Prototype]]
and how it works.
To adjust the length of the samples:
set key samplen X
(default is 4)
To adjust the vertical spacing of the samples:
set key spacing X
(default is 1.25)
and (for completeness), to adjust the fontsize:
set key font "<face>,<size>"
(default depends on the terminal)
And of course, all these can be combined into one line:
set key samplen 2 spacing .5 font ",8"
Note that you can also change the position of the key using set key at <position>
or any one of the pre-defined positions (which I'll just defer to help key
at this point)
Try this Toggle Buttons
test_activity.xml
<ToggleButton
android:id="@+id/togglebutton"
android:layout_width="100px"
android:layout_height="50px"
android:layout_centerVertical="true"
android:layout_centerHorizontal="true"
android:onClick="toggleclick"/>
Test.java
public class Test extends Activity {
private ToggleButton togglebutton;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
togglebutton = (ToggleButton) findViewById(R.id.togglebutton);
}
public void toggleclick(View v){
if(togglebutton.isChecked())
Toast.makeText(TestActivity.this, "ON", Toast.LENGTH_SHORT).show();
else
Toast.makeText(TestActivity.this, "OFF", Toast.LENGTH_SHORT).show();
}
}
Here's my solution when working with hex integers and not hex strings:
def convert_hex_to_ascii(h):
chars_in_reverse = []
while h != 0x0:
chars_in_reverse.append(chr(h & 0xFF))
h = h >> 8
chars_in_reverse.reverse()
return ''.join(chars_in_reverse)
print convert_hex_to_ascii(0x7061756c)
I faced same issue, I uploaded ipa via Xcode7 and it get stuck for 48hrs. Number of times I mail to apple support but it won't work so I uploaded ipa multiple times, but no use then I made change in version number e.g. 2.2(33) to 2.3(1) and it works for me. So try at your side may be this will help you.
Finally I am able to upload image using Django. Here is my working code
views.py
class FileUploadView(APIView):
parser_classes = (FileUploadParser, )
def post(self, request, format='jpg'):
up_file = request.FILES['file']
destination = open('/Users/Username/' + up_file.name, 'wb+')
for chunk in up_file.chunks():
destination.write(chunk)
destination.close() # File should be closed only after all chuns are added
# ...
# do some stuff with uploaded file
# ...
return Response(up_file.name, status.HTTP_201_CREATED)
urls.py
urlpatterns = patterns('',
url(r'^imageUpload', views.FileUploadView.as_view())
curl request to upload
curl -X POST -S -H -u "admin:password" -F "[email protected];type=image/jpg" 127.0.0.1:8000/resourceurl/imageUpload
Also check the database version. I was having the problem with VBA CreateDatabase(sTempDBName, dbLangGeneral) in Access 2010 where I was using a 2003 database trying to link a table in a 2010 database. When I manually tried the link I got a message about no support for linking to a later version. Creating the temp database I was trying to link to using the option dbVersion40 "CreateDatabase(sTempDBName, dbLangGeneral, dbVersion40)" cured it.
I got a similar error (Incorrect string value: '\xD0\xBE\xDO\xB2. ...' for 'content' at row 1
). I have tried to change character set of column to utf8mb4
and after that the error has changed to 'Data too long for column 'content' at row 1'
.
It turned out that mysql shows me wrong error. I turned back character set of column to utf8
and changed type of the column to MEDIUMTEXT
. After that the error disappeared.
I hope it helps someone.
By the way MariaDB in same case (I have tested the same INSERT there) just cut a text without error.
From the CLI the best way is to use grep
like:
php -i | grep libxml
Your '/0'
should be '\0'
.. you got the slash reversed/leaning the wrong way. Your while
should look like:
while (*(forward++)!='\0')
though the != '\0'
part of your expression is optional here since the loop will continue as long as it evaluates to non-zero (null is considered zero and will terminate the loop).
All "special" characters (i.e., escape sequences for non-printable characters) use a backward slash, such as tab '\t'
, or newline '\n'
, and the same for null '\0'
so it's easy to remember.
In your .htaccess you can add:
PHP 5.x
<IfModule mod_php5.c>
php_value memory_limit 64M
</IfModule>
PHP 7.x
<IfModule mod_php7.c>
php_value memory_limit 64M
</IfModule>
If page breaks again, then you are using PHP as mod_php in apache, but error is due to something else.
If page does not break, then you are using PHP as CGI module and therefore cannot use php values - in the link I've provided might be solution but I'm not sure you will be able to apply it.
Read more on http://support.tigertech.net/php-value
We can update the First Season column in df with the following syntax:
df['First Season'] = expression_for_new_values
To map the values in First Season we can use pandas‘ .map() method with the below syntax:
data_frame(['column']).map({'initial_value_1':'updated_value_1','initial_value_2':'updated_value_2'})
Just adding what fixed it for me, where misspelling is the suspect as per this MSDN blog...
When splitting SQL strings over multiple lines, check that that you are comma separating your SQL string from your parameters (and not trying to concatenate them!) and not missing any spaces at the end of each split line. Not rocket science but hope I save someone a headache.
For example:
db.TableName.SqlQuery(
"SELECT Id, Timestamp, User " +
"FROM dbo.TableName " +
"WHERE Timestamp >= @from " +
"AND Timestamp <= @till;" + [USE COMMA NOT CONCATENATE!]
new SqlParameter("from", from),
new SqlParameter("till", till)),
.ToListAsync()
.Result;
I do it on the server side, at the begining of my init file, works like a charm and you don't have to do anything in angular or existing php code:
if ($_SERVER['REQUEST_METHOD'] == 'POST' && empty($_POST))
$_POST = json_decode(file_get_contents('php://input'), true);
Just a slight expansion on the 'angular' solution. I wanted to exclude an item based on it's numeric id, so the ! approach doesn't work. The more general solution which should work for { name: 'ted' } or { id: 42 } is:
mycollection = $filter('filter')(myCollection, { id: theId }, function (obj, test) {
return obj !== test; });
You can do this:
a = a || 0
...which will convert a from any "falsey" value to 0
.
The "falsey" values are:
false
null
undefined
0
""
( empty string )NaN
( Not a Number )Or this if you prefer:
a = a ? a : 0;
...which will have the same effect as above.
If the intent was to test for more than just NaN
, then you can do the same, but do a toNumber conversion first.
a = +a || 0
This uses the unary + operator to try to convert a
to a number. This has the added benefit of converting things like numeric strings '123'
to a number.
The only unexpected thing may be if someone passes an Array that can successfully be converted to a number:
+['123'] // 123
Here we have an Array that has a single member that is a numeric string. It will be successfully converted to a number.
Even if you use string formatting, sometimes you still need white spaces at the beginning or the end of your string. For these cases, neither escaping with \
, nor xml:space
attribute helps. You must use HTML entity  
for a whitespace.
Use  
for non-breakable whitespace.
Use  
for regular space.
You probably want ANSI color codes. Most *nix terminals support them.
No, you can't undo, rollback or reverse a commit.
(Note: if you deleted the data directory off the filesystem, do NOT stop the database. The following advice applies to an accidental commit of a DELETE
or similar, not an rm -rf /data/directory
scenario).
If this data was important, STOP YOUR DATABASE NOW and do not restart it. Use pg_ctl stop -m immediate
so that no checkpoint is run on shutdown.
You cannot roll back a transaction once it has commited. You will need to restore the data from backups, or use point-in-time recovery, which must have been set up before the accident happened.
If you didn't have any PITR / WAL archiving set up and don't have backups, you're in real trouble.
Once your database is stopped, you should make a file system level copy of the whole data directory - the folder that contains base
, pg_clog
, etc. Copy all of it to a new location. Do not do anything to the copy in the new location, it is your only hope of recovering your data if you do not have backups. Make another copy on some removable storage if you can, and then unplug that storage from the computer. Remember, you need absolutely every part of the data directory, including pg_xlog
etc. No part is unimportant.
Exactly how to make the copy depends on which operating system you're running. Where the data dir is depends on which OS you're running and how you installed PostgreSQL.
If you stop your DB quickly enough you might have a hope of recovering some data from the tables. That's because PostgreSQL uses multi-version concurrency control (MVCC) to manage concurrent access to its storage. Sometimes it will write new versions of the rows you update to the table, leaving the old ones in place but marked as "deleted". After a while autovaccum comes along and marks the rows as free space, so they can be overwritten by a later INSERT
or UPDATE
. Thus, the old versions of the UPDATE
d rows might still be lying around, present but inaccessible.
Additionally, Pg writes in two phases. First data is written to the write-ahead log (WAL). Only once it's been written to the WAL and hit disk, it's then copied to the "heap" (the main tables), possibly overwriting old data that was there. The WAL content is copied to the main heap by the bgwriter
and by periodic checkpoints. By default checkpoints happen every 5 minutes. If you manage to stop the database before a checkpoint has happened and stopped it by hard-killing it, pulling the plug on the machine, or using pg_ctl
in immediate
mode you might've captured the data from before the checkpoint happened, so your old data is more likely to still be in the heap.
Now that you have made a complete file-system-level copy of the data dir you can start your database back up if you really need to; the data will still be gone, but you've done what you can to give yourself some hope of maybe recovering it. Given the choice I'd probably keep the DB shut down just to be safe.
You may now need to hire an expert in PostgreSQL's innards to assist you in a data recovery attempt. Be prepared to pay a professional for their time, possibly quite a bit of time.
I posted about this on the Pg mailing list, and ?????? ?????? linked to depesz's post on pg_dirtyread, which looks like just what you want, though it doesn't recover TOAST
ed data so it's of limited utility. Give it a try, if you're lucky it might work.
See: pg_dirtyread on GitHub.
I've removed what I'd written in this section as it's obsoleted by that tool.
See also PostgreSQL row storage fundamentals
See my blog entry Preventing PostgreSQL database corruption.
On a semi-related side-note, if you were using two phase commit you could ROLLBACK PREPARED
for a transction that was prepared for commit but not fully commited. That's about the closest you get to rolling back an already-committed transaction, and does not apply to your situation.
I think the best ranking is
1.node-schedule
2.later
3.crontab
and the sample of node-schedule is below:
var schedule = require("node-schedule");
var rule = new schedule.RecurrenceRule();
//rule.minute = 40;
rule.second = 10;
var jj = schedule.scheduleJob(rule, function(){
console.log("execute jj");
});
Maybe you can find the answer from node modules.
You should definitely have a look at this answer of mine:
and also have a look at all the links included therein.
Tabula/TabulaPDF is currently the best table extraction tool that is available for PDF scraping.
I've had a lot of trouble over the years trying to get QApplication::processEvents to work, as is used in some of the top answers. IIRC, if multiple locations end up calling it, it can end up causing some signals to not get processed (https://doc.qt.io/archives/qq/qq27-responsive-guis.html). My usual preferred option is to utilize a QEventLoop (https://doc.qt.io/archives/qq/qq27-responsive-guis.html#waitinginalocaleventloop).
inline void delay(int millisecondsWait)
{
QEventLoop loop;
QTimer t;
t.connect(&t, &QTimer::timeout, &loop, &QEventLoop::quit);
t.start(millisecondsWait);
loop.exec();
}
Opaque will cause less system strain since 'transparent' will still attempt to apply alpha. The reason you see transparent used instead is because most web authors don't pay attention to detail (ie, just copy-pasted some embed code they found).
BTW, you are correct about it being undocumented. The best I've ever seen is a blog by a guy who claims to have talked to a Macromedia developer about it. Unfortunaetly I can't find the link.
EDIT: I think it was this one: http://www.communitymx.com/content/article.cfm?cid=e5141
I had a similar issue and was able to resolve it by identifying which JDBC driver I intended to use. In my case, I was connecting to an Oracle database. I placed the following statement, prior to creating the connection variable.
DriverManager.registerDriver( new oracle.jdbc.driver.OracleDriver());
I have tried to solve this question for years now, I thought I found a shorter solution but had to come back again to the long story. This function gives back the right ISO week notation:
/**
* calcweek("2018-12-31") => 1901
* This function calculates the production weeknumber according to the start on
* monday and with at least 4 days in the new year. Given that the $date has
* the following format Y-m-d then the outcome is and integer.
*
* @author M.S.B. Bachus
*
* @param date-notation PHP "Y-m-d" showing the data as yyyy-mm-dd
* @return integer
**/
function calcweek($date) {
// 1. Convert input to $year, $month, $day
$dateset = strtotime($date);
$year = date("Y", $dateset);
$month = date("m", $dateset);
$day = date("d", $dateset);
$referenceday = getdate(mktime(0,0,0, $month, $day, $year));
$jan1day = getdate(mktime(0,0,0,1,1,$referenceday[year]));
// 2. check if $year is a leapyear
if ( ($year%4==0 && $year%100!=0) || $year%400==0) {
$leapyear = true;
} else {
$leapyear = false;
}
// 3. check if $year-1 is a leapyear
if ( (($year-1)%4==0 && ($year-1)%100!=0) || ($year-1)%400==0 ) {
$leapyearprev = true;
} else {
$leapyearprev = false;
}
// 4. find the dayofyearnumber for y m d
$mnth = array(0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334);
$dayofyearnumber = $day + $mnth[$month-1];
if ( $leapyear && $month > 2 ) { $dayofyearnumber++; }
// 5. find the jan1weekday for y (monday=1, sunday=7)
$yy = ($year-1)%100;
$c = ($year-1) - $yy;
$g = $yy + intval($yy/4);
$jan1weekday = 1+((((intval($c/100)%4)*5)+$g)%7);
// 6. find the weekday for y m d
$h = $dayofyearnumber + ($jan1weekday-1);
$weekday = 1+(($h-1)%7);
// 7. find if y m d falls in yearnumber y-1, weeknumber 52 or 53
$foundweeknum = false;
if ( $dayofyearnumber <= (8-$jan1weekday) && $jan1weekday > 4 ) {
$yearnumber = $year - 1;
if ( $jan1weekday = 5 || ( $jan1weekday = 6 && $leapyearprev )) {
$weeknumber = 53;
} else {
$weeknumber = 52;
}
$foundweeknum = true;
} else {
$yearnumber = $year;
}
// 8. find if y m d falls in yearnumber y+1, weeknumber 1
if ( $yearnumber == $year && !$foundweeknum) {
if ( $leapyear ) {
$i = 366;
} else {
$i = 365;
}
if ( ($i - $dayofyearnumber) < (4 - $weekday) ) {
$yearnumber = $year + 1;
$weeknumber = 1;
$foundweeknum = true;
}
}
// 9. find if y m d falls in yearnumber y, weeknumber 1 through 53
if ( $yearnumber == $year && !$foundweeknum ) {
$j = $dayofyearnumber + (7 - $weekday) + ($jan1weekday - 1);
$weeknumber = intval( $j/7 );
if ( $jan1weekday > 4 ) { $weeknumber--; }
}
// 10. output iso week number (YYWW)
return ($yearnumber-2000)*100+$weeknumber;
}
I found out that my short solution missed the 2018-12-31 as it gave back 1801 instead of 1901. So I had to put in this long version which is correct.
Doe the following work?
resourcesloader.class.getClass().getResource("/package1/resources/repository/SSL-Key/cert.jks")
Is there a reason you can't specify the full path including the package?
Andy E's answer helped me get the correct way to working for me:
$.each(["input[type=text][value=]", "textarea"], function (index, element) {
if (!$(element).val() || !$(element).text()) {
$(element).css("background-color", "rgba(255,227,3, 0.2)");
}
});
This !$(element).val()
did not catch an empty textarea for me. but that whole bang (!) thing did work when combined with text.
FWIW, I was able to setup a local RTSP server for testing purposes using simple-rtsp-server and ffmpeg following these steps:
rtsp-simple-server.yml
with this single line:
protocols: [tcp]
$ docker run --rm -it -v $PWD/rtsp-simple-server.yml:/rtsp-simple-server.yml -p 8554:8554 aler9/rtsp-simple-server
$ ffmpeg -re -stream_loop -1 -i test.mp4 -f rtsp -rtsp_transport tcp rtsp://localhost:8554/live.stream
Once you have that running you can use ffplay to view the stream:
$ ffplay -rtsp_transport tcp rtsp://localhost:8554/live.stream
Note that simple-rtsp-server can also handle UDP streams (i.s.o. TCP) but that's tricky running the server as a Docker container.
getView()
method create new View
or ViewGroup
for each row of Listview
or Spinner . You can define this View
or ViewGroup
in a Layout XML
file in res/layout
folder and can give the reference it to Adapter
class Object.
if you have 4 item in a Array passed to Adapter. getView()
method will create 4 View for 4 rows of Adaper.
LayoutInflater class has a Method inflate() whic create View Object from XML resource layout.
This code will exit the loop after the first iteration in a for of
loop:
const objc = [{ name: 1 }, { name: 2 }, { name: 3 }];
for (const iterator of objc) {
if (iterator.name == 2) {
return;
}
console.log(iterator.name);// 1
}
the below code will jump on the condition and continue on a for of
loop:
const objc = [{ name: 1 }, { name: 2 }, { name: 3 }];
for (const iterator of objc) {
if (iterator.name == 2) {
continue;
}
console.log(iterator.name); // 1 , 3
}
Yes is it possible, but not as nice as in c# (in my opinion c# is BETTER!). Opinions that goto always obscures software are dull and silly! It's sad java don't have at least goto case xxx.
Jump to forward:
public static void main(String [] args) {
myblock: {
System.out.println("Hello");
if (some_condition)
break myblock;
System.out.println("Nice day");
}
// here code continue after performing break myblock
System.out.println("And work");
}
Jump to backward:
public static void main(String [] args) {
mystart: //here code continue after performing continue mystart
do {
System.out.println("Hello");
if (some_condition)
continue mystart;
System.out.println("Nice day");
} while (false);
System.out.println("And work");
}
These methods are in ObjectNode
: the division is such that most read operations are included in JsonNode
, but mutations in ObjectNode
and ArrayNode
.
Note that you can just change first line to be:
ObjectNode jNode = mapper.createObjectNode();
// version ObjectMapper has should return ObjectNode type
or
ObjectNode jNode = (ObjectNode) objectCodec.createObjectNode();
// ObjectCodec is in core part, must be of type JsonNode so need cast
The only way I can get this to work is to manually instantiate the section handler type, pass the raw XML to it, and cast the resulting object.
Seems pretty inefficient, but there you go.
I wrote an extension method to encapsulate this:
public static class ConfigurationSectionExtensions
{
public static T GetAs<T>(this ConfigurationSection section)
{
var sectionInformation = section.SectionInformation;
var sectionHandlerType = Type.GetType(sectionInformation.Type);
if (sectionHandlerType == null)
{
throw new InvalidOperationException(string.Format("Unable to find section handler type '{0}'.", sectionInformation.Type));
}
IConfigurationSectionHandler sectionHandler;
try
{
sectionHandler = (IConfigurationSectionHandler)Activator.CreateInstance(sectionHandlerType);
}
catch (InvalidCastException ex)
{
throw new InvalidOperationException(string.Format("Section handler type '{0}' does not implement IConfigurationSectionHandler.", sectionInformation.Type), ex);
}
var rawXml = sectionInformation.GetRawXml();
if (rawXml == null)
{
return default(T);
}
var xmlDocument = new XmlDocument();
xmlDocument.LoadXml(rawXml);
return (T)sectionHandler.Create(null, null, xmlDocument.DocumentElement);
}
}
The way you would call it in your example is:
var map = new ExeConfigurationFileMap
{
ExeConfigFilename = @"c:\\foo.config"
};
var configuration = ConfigurationManager.OpenMappedExeConfiguration(map, ConfigurationUserLevel.None);
var myParamsSection = configuration.GetSection("MyParams");
var myParamsCollection = myParamsSection.GetAs<NameValueCollection>();
if ( $('#whatever')[0] ) {...}
The jQuery object which is returned by all native jQuery methods is NOT an array, it is an object with many properties; one of them being a "length" property. You can also check for size() or get(0) or get() - 'get(0)' works the same as accessing the first element, i.e. $(elem)[0]
Don't forget to run:
/opt/android-studio/bin/studio.sh
when you are done installing.
Actually Opera doesn't have 5MB limit. It offers to increase limit as applications requires more. User can even choose "Unlimited storage" for a domain.
You can easily test localStorage limits/quota yourself.
We can utilize recursion for making deepCopy. It can create copy of array, object, array of object, object with function. if you want, you can add function for other type of data structure like map etc.
function deepClone(obj) {
var retObj;
_assignProps = function(obj, keyIndex, retObj) {
var subType = Object.prototype.toString.call(obj[keyIndex]);
if(subType === "[object Object]" || subType === "[object Array]") {
retObj[keyIndex] = deepClone(obj[keyIndex]);
}
else {
retObj[keyIndex] = obj[keyIndex];
}
};
if(Object.prototype.toString.call(obj) === "[object Object]") {
retObj = {};
for(key in obj) {
this._assignProps(obj, key, retObj);
}
}
else if(Object.prototype.toString.call(obj) == "[object Array]") {
retObj = [];
for(var i = 0; i< obj.length; i++) {
this._assignProps(obj, i, retObj);
}
};
return retObj;
};
I found that useful, stabbing service function as sinon.stub().returns($q.when({})):
this.myService = {
myFunction: sinon.stub().returns( $q.when( {} ) )
};
this.scope = $rootScope.$new();
this.angularStubs = {
myService: this.myService,
$scope: this.scope
};
this.ctrl = $controller( require( 'app/bla/bla.controller' ), this.angularStubs );
controller:
this.someMethod = function(someObj) {
myService.myFunction( someObj ).then( function() {
someObj.loaded = 'bla-bla';
}, function() {
// failure
} );
};
and test
const obj = {
field: 'value'
};
this.ctrl.someMethod( obj );
this.scope.$digest();
expect( this.myService.myFunction ).toHaveBeenCalled();
expect( obj.loaded ).toEqual( 'bla-bla' );
Short answer:
There is no difference in semantic.
Specifically, @GetMapping is a composed annotation that acts as a shortcut for @RequestMapping(method = RequestMethod.GET).
Further reading:
RequestMapping
can be used at class level:
This annotation can be used both at the class and at the method level. In most cases, at the method level applications will prefer to use one of the HTTP method specific variants @GetMapping, @PostMapping, @PutMapping, @DeleteMapping, or @PatchMapping.
while GetMapping
only applies to method:
Annotation for mapping HTTP GET requests onto specific handler methods.
http://en.wikipedia.org/wiki/Tempuri
tempuri.org is the default namespace URI used by Microsoft development products, like Visual Studio.
This answer seems good.
however, it lead me towards an error as it resulted with
Configuration 'xyz' could not be found in project ...
error in build.
It is requierd not only to updated build configurations, but also serve
ones.
So just to leave no confusions:
--env
is not supported in angular 6
--env
got changed into --configuration
|| -c
(and is now more powerful)angular.json
file:
{ ... "build": "configurations": ...
propertyfileReplacements
part, (but more options are available){ ... "serve": "configurations": ...
propertybrowserTarget="your-project-name:build:staging"
It depends on what you want to do with the script (or any other program you want to run).
If you just want to run the script system
is the easiest thing to do, but it does some other stuff too, including running a shell and having it run the command (/bin/sh under most *nix).
If you want to either feed the shell script via its standard input or consume its standard output you can use popen
(and pclose
) to set up a pipe. This also uses the shell (/bin/sh under most *nix) to run the command.
Both of these are library functions that do a lot under the hood, but if they don't meet your needs (or you just want to experiment and learn) you can also use system calls directly. This also allows you do avoid having the shell (/bin/sh) run your command for you.
The system calls of interest are fork
, execve
, and waitpid
. You may want to use one of the library wrappers around execve
(type man 3 exec
for a list of them). You may also want to use one of the other wait functions (man 2 wait
has them all). Additionally you may be interested in the system calls clone
and vfork
which are related to fork.
fork
duplicates the current program, where the only main difference is that the new process gets 0 returned from the call to fork. The parent process gets the new process's process id (or an error) returned.
execve
replaces the current program with a new program (keeping the same process id).
waitpid
is used by a parent process to wait on a particular child process to finish.
Having the fork and execve steps separate allows programs to do some setup for the new process before it is created (without messing up itself). These include changing standard input, output, and stderr to be different files than the parent process used, changing the user or group of the process, closing files that the child won't need, changing the session, or changing the environmental variables.
You may also be interested in the pipe
and dup2
system calls. pipe
creates a pipe (with both an input and an output file descriptor). dup2
duplicates a file descriptor as a specific file descriptor (dup
is similar but duplicates a file descriptor to the lowest available file descriptor).
It is a cheap way to comment out, but I suspect that it could have debugging potential. For example, let's suppose you have a build that output values to a file. You might not want that in a final version so you can use the #if 0... #endif.
Also, I suspect a better way of doing it for debug purpose would be to do:
#ifdef DEBUG
// output to file
#endif
You can do something like that and it might make more sense and all you have to do is define DEBUG to see the results.
First, I'm not certain that you need a second thread to set the shutdown_flag
.
Why not set it directly in the SIGTERM handler?
An alternative is to raise an exception from the SIGTERM
handler, which will be propagated up the stack. Assuming you've got proper exception handling (e.g. with with
/contextmanager
and try: ... finally:
blocks) this should be a fairly graceful shutdown, similar to if you were to Ctrl+C your program.
Example program signals-test.py
:
#!/usr/bin/python
from time import sleep
import signal
import sys
def sigterm_handler(_signo, _stack_frame):
# Raises SystemExit(0):
sys.exit(0)
if sys.argv[1] == "handle_signal":
signal.signal(signal.SIGTERM, sigterm_handler)
try:
print "Hello"
i = 0
while True:
i += 1
print "Iteration #%i" % i
sleep(1)
finally:
print "Goodbye"
Now see the Ctrl+C behaviour:
$ ./signals-test.py default
Hello
Iteration #1
Iteration #2
Iteration #3
Iteration #4
^CGoodbye
Traceback (most recent call last):
File "./signals-test.py", line 21, in <module>
sleep(1)
KeyboardInterrupt
$ echo $?
1
This time I send it SIGTERM
after 4 iterations with kill $(ps aux | grep signals-test | awk '/python/ {print $2}')
:
$ ./signals-test.py default
Hello
Iteration #1
Iteration #2
Iteration #3
Iteration #4
Terminated
$ echo $?
143
This time I enable my custom SIGTERM
handler and send it SIGTERM
:
$ ./signals-test.py handle_signal
Hello
Iteration #1
Iteration #2
Iteration #3
Iteration #4
Goodbye
$ echo $?
0
I just now downgraded my Python 3.9 to 3.6 because I wanted to use the librosa package but it does not support Python 3.9 still now.
Steps -
Run python3 --version
in the terminal and it will show this version of Python.
Check out the connection strings web site which has tons of example for your connection strings.
Basically, you need three things:
.
" or (local)
or localhost
for the local machine)For example, if you want to connect to your local machine and the AdventureWorks
database using integrated security, use:
server=(local);database=AdventureWorks;integrated security=SSPI;
Or if you have SQL Server Express on your machine in the default installation, and you want to connect to the AdventureWorksLT2008 database, use this:
server=.\SQLExpress;database=AdventureWorksLT2008;integrated Security=SSPI;
this is the best way to solve this
getWindow().addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN | WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
Casting is necessary to tell that you are calling a child and not a parent method. So it's ever downward. However if the method is already defined in the parent class and overriden in the child class, you don't any cast. Here an example:
class Parent{
void method(){ System.out.print("this is the parent"); }
}
class Child extends Parent{
@override
void method(){ System.out.print("this is the child"); }
}
...
Parent o = new Child();
o.method();
((Child)o).method();
The two method call will both print : "this is the child".
if its something you wish to switch, fading one out and fading another in the same place, you can place a {position:absolute} attribute on the divs, so both the animations play on top of one another, and you don't have to wait for one animation to be over before starting up the next.
CodeIgniter 3
Only:
$this->db->where('archived IS NOT NULL');
The generated query is:
WHERE archived IS NOT NULL;
$this->db->where('archived IS NOT NULL',null,false); << Not necessary
Inverse:
$this->db->where('archived');
The generated query is:
WHERE archived IS NULL;
using $(this) improves performance, as the class/whatever attr u are using to search, need not be searched for multiple times in the entire webpage content.
jcalfee314's idea worked for me - I had a window.onload = onLoad
which meant that the functions in <body onload="...">
were not being called (which I don't have control over).
This fixed it:
oldOnLoad = window.onload
window.onload = onLoad;
function onLoad()
{
oldOnLoad();
...
}
Edit: Firefox didn't like oldOnLoad = document.body.onload;
, so replaced with oldOnLoad = window.onload
.
As has been mentioned, slicing with None
or with np.newaxes
is a great way to do this.
Another alternative is to use transposes and broadcasting, as in
(data.T - vector).T
and
(data.T / vector).T
For higher dimensional arrays you may want to use the swapaxes
method of NumPy arrays or the NumPy rollaxis
function.
There really are a lot of ways to do this.
For a fuller explanation of broadcasting, see http://docs.scipy.org/doc/numpy/user/basics.broadcasting.html
I have been testing this out for my project.
If you are working with Windows and Visual Studio 2015
Enter the following commands
Here's a simpler (but not so short) version which doesn't require try-catch:
Map<String, String> data = new HashMap<>();
data.put("user", "[email protected]");
data.put("pass", "123");
JSONObject jsonData = new JSONObject(data);
If you want to add a jsonObject into a field, you can do this way:
data.put("socialMedia", (new JSONObject()).put("facebookId", "1174989895893400"));
data.put("socialMedia", (new JSONObject()).put("googleId", "106585039098745627377"));
Unfortunately it needs a try-catch because of the put() method.
IF you want to avoid try-catch again (not very recommended, but it's ok if you can guarantee well formated json strings), you might do this way:
data.put("socialMedia", "{ 'facebookId': '1174989895893400' }");
You can do the same about JsonArrays and so on.
Cheers.
What type is your output variable?
Python sets are what you need. Declare output like this:
output = set() # initialize an empty set
and you're ready to go adding elements with output.add(elem)
and be sure they're unique.
Warning: sets DO NOT preserve the original order of the list.
I experienced this issue today and started searching on internet. In my case there was no table in my DB. I forgot to import the tables on the online server. I did it and all works fine.
This might be a little late. But here is one of the usage. This to get the count of the number of files.
Create a pointer to memory (a new obj in this case) and have the property of the object modified. Java 8 stream doesn't allow to modify the pointer itself and hence if you declare just count as a variable and try to increment within the stream it will never work and throw a compiler exception in the first place
Path path = Paths.get("/Users/XXXX/static/test.txt");
Count c = new Count();
c.setCount(0);
Files.lines(path).forEach(item -> {
c.setCount(c.getCount()+1);
System.out.println(item);});
System.out.println("line count,"+c);
public static class Count{
private int count;
public int getCount() {
return count;
}
public void setCount(int count) {
this.count = count;
}
@Override
public String toString() {
return "Count [count=" + count + "]";
}
}
With recent browsers you can use the HTML5 download attribute as well:
<a download="quot.pdf" href="../doc/quot.pdf">Click here to Download quotation</a>
It is supported by most of the recent browsers except MSIE11. You can use a polyfill, something like this (note that this is for data uri only, but it is a good start):
(function (){
addEvent(window, "load", function (){
if (isInternetExplorer())
polyfillDataUriDownload();
});
function polyfillDataUriDownload(){
var links = document.querySelectorAll('a[download], area[download]');
for (var index = 0, length = links.length; index<length; ++index) {
(function (link){
var dataUri = link.getAttribute("href");
var fileName = link.getAttribute("download");
if (dataUri.slice(0,5) != "data:")
throw new Error("The XHR part is not implemented here.");
addEvent(link, "click", function (event){
cancelEvent(event);
try {
var dataBlob = dataUriToBlob(dataUri);
forceBlobDownload(dataBlob, fileName);
} catch (e) {
alert(e)
}
});
})(links[index]);
}
}
function forceBlobDownload(dataBlob, fileName){
window.navigator.msSaveBlob(dataBlob, fileName);
}
function dataUriToBlob(dataUri) {
if (!(/base64/).test(dataUri))
throw new Error("Supports only base64 encoding.");
var parts = dataUri.split(/[:;,]/),
type = parts[1],
binData = atob(parts.pop()),
mx = binData.length,
uiArr = new Uint8Array(mx);
for(var i = 0; i<mx; ++i)
uiArr[i] = binData.charCodeAt(i);
return new Blob([uiArr], {type: type});
}
function addEvent(subject, type, listener){
if (window.addEventListener)
subject.addEventListener(type, listener, false);
else if (window.attachEvent)
subject.attachEvent("on" + type, listener);
}
function cancelEvent(event){
if (event.preventDefault)
event.preventDefault();
else
event.returnValue = false;
}
function isInternetExplorer(){
return /*@cc_on!@*/false || !!document.documentMode;
}
})();
You can use a binding source to bind to with your datagridview. Set your class or list of data. Set a bindingsource.datasource equal to that. Set the datasource of your datagridview to your bindingsource.
I guess something like this would work:
Add System.ServiceProcess
to your project references (It's on the .NET tab).
using System.ServiceProcess;
ServiceController sc = new ServiceController(SERVICENAME);
switch (sc.Status)
{
case ServiceControllerStatus.Running:
return "Running";
case ServiceControllerStatus.Stopped:
return "Stopped";
case ServiceControllerStatus.Paused:
return "Paused";
case ServiceControllerStatus.StopPending:
return "Stopping";
case ServiceControllerStatus.StartPending:
return "Starting";
default:
return "Status Changing";
}
Edit: There is also a method sc.WaitforStatus()
that takes a desired status and a timeout, never used it but it may suit your needs.
Edit: Once you get the status, to get the status again you will need to call sc.Refresh()
first.
Reference: ServiceController object in .NET.
If you're interested in learning a language which supports massive parallelism better go for OpenCL since you don't have an NVIDIA GPU. You can run OpenCL on Intel CPUs, but at best you can learn to program SIMDs. Optimization on CPU and GPU are different. I really don't think you can use Intel card for GPGPU.
The PostgreSQL manual indicates that this means the transaction is open (inside BEGIN) and idle. It's most likely a user connected using the monitor who is thinking or typing. I have plenty of those on my system, too.
If you're using Slony for replication, however, the Slony-I FAQ suggests idle in transaction
may mean that the network connection was terminated abruptly. Check out the discussion in that FAQ for more details.
ArrayUtils.isNotEmpty(testArrayName)
from the package org.apache.commons.lang3
ensures Array is not null or empty
There is the solution if you need only outline without border. It's not mine. I got if from Bootstrap css file. If you specify outline: 1px auto certain_color
, you'll get thin outer line around div of certain color. In this case the specified width has no matter, even if you specify 10 px width, anyway it will be thin line. The key word in mentioned rule is "auto".
If you need outline with rounded corners and certain width, you may add css rule on border with needed width and same color. It makes outline thicker.
As of September 2017 (node version=v6.11.3, npm version=3.10.10), this is what worked for me (thanks @Zze):
Edit polyfills.ts
and uncomment the imports that are necessary for IE11.
More preciselly, edit polyfills.ts
(located in the src
folder by default) and just uncomment all lines required for IE11 (the comments inside the file explain exactly what imports are necessary to run on IE11).
A small warning: pay attention when uncommenting the lines for classlist.js
and web-animations-js
. These commented lines have a specific comment each: you must run the associated npm commands before uncommenting them or processing of polyfills.ts will break.
As a word of explanation, the polyfills are pieces of code that implement a feature on a web browser that do not support it. This is why in the default polyfills.ts configuration only a minimal set of imports is active (because it's aiming the so-called "evergreen" browsers; the last versions of browsers that automatically update themselves).
If you already have a number of dates already highlighted and want to determine which date was last clicked then you'll need the following:
$('#startdate').data('datepicker').viewDate
viewDate
returns a JavaScript date object so you'll need to handle it accordingly.
Use CSS:
<html>
<head>
<style>
.Large
{
font-size: 16pt;
height: 50px;
}
</style>
<body>
<input type="text" class="Large">
</body>
</html>
Step 1: You have to add the line: default-storage-engine = InnoDB under the [mysqld] section of your mysql config file (my.cnf or my.ini depending on your OS) and restart the mysqld service.
Step 2: Now when you create the table you will see the type of table is: InnoDB
Step 3: Create both Parent and Child table. Now open the Child table and select the column U like to have the Foreign Key: Select the Index Key from Action Label as shown below.
Step 4: Now open the Relation View in the same child table from bottom near the Print View as shown below.
Step 5: Select the column U like to have the Foreign key as Select the Parent column from the drop down. dbName.TableName.ColumnName
The thing is that .replace()
does not modify the string itself, so you should write something like:
strInputString = strInputString.replace(...
It also seems like you're not doing character escaping correctly. The following worked for me:
strInputString = strInputString.replace(/'/g, "\\'");
The accepted answer by Francisco Spaeth works and is easy to follow. However, I think that method of building JSON sucks! This was really driven home for me as I converted some Python to Java where I could use dictionaries and nested lists, etc. to build JSON with ridiculously greater ease.
What I really don't like is having to instantiate separate objects (and generally even name them) to build up these nestings. If you have a lot of objects or data to deal with, or your use is more abstract, that is a real pain!
I tried getting around some of that by attempting to clear and reuse temp json objects and lists, but that didn't work for me because all the puts and gets, etc. in these Java objects work by reference not value. So, I'd end up with JSON objects containing a bunch of screwy data after still having some ugly (albeit differently styled) code.
So, here's what I came up with to clean this up. It could use further development, but this should help serve as a base for those of you looking for more reasonable JSON building code:
import java.util.AbstractMap.SimpleEntry;
import java.util.ArrayList;
import java.util.List;
import org.json.simple.JSONObject;
// create and initialize an object
public static JSONObject buildObject( final SimpleEntry... entries ) {
JSONObject object = new JSONObject();
for( SimpleEntry e : entries ) object.put( e.getKey(), e.getValue() );
return object;
}
// nest a list of objects inside another
public static void putObjects( final JSONObject parentObject, final String key,
final JSONObject... objects ) {
List objectList = new ArrayList<JSONObject>();
for( JSONObject o : objects ) objectList.add( o );
parentObject.put( key, objectList );
}
Implementation example:
JSONObject jsonRequest = new JSONObject();
putObjects( jsonRequest, "parent1Key",
buildObject(
new SimpleEntry( "child1Key1", "someValue" )
, new SimpleEntry( "child1Key2", "someValue" )
)
, buildObject(
new SimpleEntry( "child2Key1", "someValue" )
, new SimpleEntry( "child2Key2", "someValue" )
)
);