Pure POSIX shell:
#!/bin/sh
CURRENT_DIR=`pwd`
case "$CURRENT_DIR" in
*String1*) echo "String1 present" ;;
*String2*) echo "String2 present" ;;
*) echo "else" ;;
esac
Extended shells like ksh or bash have fancy matching mechanisms, but the old-style case
is surprisingly powerful.
The solution is fairly straight forward. To ensure that we don't impact the width of the cells in the table, we'll turn off white-space. To ensure we get a horizontal scroll bar, we'll turn on overflow-x. And that's pretty much it:
.container {
width: 30em;
overflow-x: auto;
white-space: nowrap;
}
You can see the end-result here, or in the animation below. If the table determines the height of your container, you should not need to explicitly set overflow-y
to hidden
. But understand that is also an option.
The ajax is going to be a javascript snippet that passes information to a small php file that does what you want. So in your page, instead of all that php, you want a little javascript, preferable jquery:
function fun()
{
$.get('\addEmail.php', {email : $(this).val()}, function(data) {
//here you would write the "you ve been successfully subscribed" div
});
}
also you input would have to be:
<input type="button" value="subscribe" class="submit" onclick="fun();" />
last the file addEmail.php should look something like:
mysql_connect("localhost","root","");
mysql_select_db("eciticket_db");
error_reporting(E_ALL && ~E_NOTICE);
$email=mysql_real_escape_string($_GET['email']);
$sql="INSERT INTO newsletter_email(email) VALUES ('$email')";
$result=mysql_query($sql);
if($result){
echo "You have been successfully subscribed.";
}
if(!$sql)
die(mysql_error());
mysql_close();
Also sergey is right, you should use mysqli. That's not everything, but enough to get you started.
I had this issue until I removed the project in question from the server's deployments (in JBoss Dev Studio, right-click the server and "Remove" the project in the Servers view), then did the following:
After this, just restart the server (in debug or run mode) by selecting the server, NOT the project itself.
This seemed to flush any previous settings/states/memory/whatever that was causing the issue, and I no longer got the error.
A small improvement to @FishBoy's suggestion is to use the id projection, so you don't have to hard-code the identifier property name.
criteria.setProjection(Projections.distinct(Projections.id()));
if you have Mac just use help option (usually the last option on Mac's menu bar) then type: "tab indentation" and choose a tab indentation width
but generally, you can follow this path: view -> indentation
I'f you're suppsed to be able to use it, then 3rd-party library should have a *.lib file as well as a *.dll file. You simply need to add the *.lib to the list of input file in your project's 'Linker' options.
This *.lib file isn't necessarily a 'static' library (which contains code): instead a *.lib can be just a file that links your executable to the DLL.
background
is shorthand property for the following:
- background-color
- background-image
- background-repeat
- background-attachment
- background-position
You can detailed info on every property here
Properties order
In most of browser implementation (i think maybe older browser could present issues) the order of the properties does not matter, except for:
background-origin
and background-clip
: when both of this properties are present, the first one refer to -origin
and the second to -clip
.
Example:
background: content-box green padding-box;
Is equivalent to:
background-origin: content-box;
background-color: green;
background-clip: padding-box;
background-size
must always follow background-position
and the properties must be separated by /
if background-position
is composed by two numbers, the first one is the horizontal value and the second the vertical value.
Example for String Methods
Given a list of filenames, we want to rename all the files with extension hpp to the extension h. To do this, we would like to generate a new list called newfilenames, consisting of the new filenames. Fill in the blanks in the code using any of the methods you’ve learned thus far, like a for loop or a list comprehension.
filenames = ["program.c", "stdio.hpp", "sample.hpp", "a.out", "math.hpp", "hpp.out"]
# Generate newfilenames as a list containing the new filenames
# using as many lines of code as your chosen method requires.
newfilenames = []
for i in filenames:
if i.endswith(".hpp"):
x = i.replace("hpp", "h")
newfilenames.append(x)
else:
newfilenames.append(i)
print(newfilenames)
# Should be ["program.c", "stdio.h", "sample.h", "a.out", "math.h", "hpp.out"]
I guess you want it along the curvature of the earth. Your two points and the center of the earth are on a plane. The center of the earth is the center of a circle on that plane and the two points are (roughly) on the perimeter of that circle. From that you can calculate the distance by finding out what the angle from one point to the other is.
If the points are not the same heights, or if you need to take into account that the earth is not a perfect sphere it gets a little more difficult.
how about:
def fix_unicode(data):
if isinstance(data, unicode):
return data.encode('utf-8')
elif isinstance(data, dict):
data = dict((fix_unicode(k), fix_unicode(data[k])) for k in data)
elif isinstance(data, list):
for i in xrange(0, len(data)):
data[i] = fix_unicode(data[i])
return data
Based on your desire that 1317427200
be the output, there are several layers of issue to address.
First as others have mentioned, java already uses a UTC 1/1/1970 epoch. There is normally no need to calculate the epoch and perform subtraction unless you have weird locale rules.
Second, when you create a new Calendar it's initialized to 'now' so it includes the time of day. Changing the year/month/day doesn't affect the time of day fields. So if you want it to represent midnight of the date, you need to zero out the calendar before you set the date.
Third, you haven't specified how you're supposed to handle time zones. Daylight Savings can cause differences in the absolute number of seconds represented by a particular calendar-on-the-wall-date, depending on where your JVM is running. Since epoch is in UTC, we probably want to work in UTC times? You may need to seek clarification from the makers of the system you're interfacing with.
Fourth, months in Java are zero indexed. January is 0, October is 9.
Putting all that together
Calendar calendar = Calendar.getInstance(TimeZone.getTimeZone("UTC"));
calendar.clear();
calendar.set(2011, Calendar.OCTOBER, 1);
long secondsSinceEpoch = calendar.getTimeInMillis() / 1000L;
that will give you 1317427200
If you are trying to force a floating div to match another to create a column effect, this is what I do. I like it because it's simple and clean.
<div style="background-color: #CCC; width:300px; overflow:hidden; ">
<!-- Padding-Bottom is equal to 100% of the container's size, Margin-bottom hides everything beyond
the container equal to the container size. This allows the column to grow with the largest
column. -->
<div style="float: left;width: 100px; background:yellow; padding-bottom:100%; margin-bottom:-100%;">column a</div>
<div style="float: left;width: 100px; background:#09F;">column b<br />Line 2<br />Line 3<br />Line 4<br />Line 5</div>
<div style="float:left; width:100px; background: yellow; padding-bottom:100%; margin-bottom:-100%;">Column C</div>
<div style="clear: both;"></div>
</div>
I think this makes sense. It seems to work well even with dynamic content.
Try this:
public ActionResult CreatePerson(int id) //controller
window.location.href = "@Url.Action("CreatePerson", "Person")?Id='+Id+'";
it's working fine passing parameter.
You need to use the files
parameter to send a multipart form POST request even when you do not need to upload any files.
From the original requests source:
def request(method, url, **kwargs):
"""Constructs and sends a :class:`Request <Request>`.
...
:param files: (optional) Dictionary of ``'name': file-like-objects``
(or ``{'name': file-tuple}``) for multipart encoding upload.
``file-tuple`` can be a 2-tuple ``('filename', fileobj)``,
3-tuple ``('filename', fileobj, 'content_type')``
or a 4-tuple ``('filename', fileobj, 'content_type', custom_headers)``,
where ``'content-type'`` is a string
defining the content type of the given file
and ``custom_headers`` a dict-like object
containing additional headers to add for the file.
The relevant part is: file-tuple can be a
2-tuple
, 3-tuple
or a
4-tuple
.
Based on the above, the simplest multipart form request that includes both files to upload and form fields will look like this:
multipart_form_data = {
'file2': ('custom_file_name.zip', open('myfile.zip', 'rb')),
'action': (None, 'store'),
'path': (None, '/path1')
}
response = requests.post('https://httpbin.org/post', files=multipart_form_data)
print(response.content)
☝ Note the None
as the first argument in the tuple for plain text fields — this is a placeholder for the filename field which is only used for file uploads, but for text fields passing None
as the first parameter is required in order for the data to be submitted.
If you need to post multiple fields with the same name then instead of a dictionary you can define your payload as a list (or a tuple) of tuples:
multipart_form_data = (
('file2', ('custom_file_name.zip', open('myfile.zip', 'rb'))),
('action', (None, 'store')),
('path', (None, '/path1')),
('path', (None, '/path2')),
('path', (None, '/path3')),
)
If the above API is not pythonic enough for you, then consider using requests toolbelt (pip install requests_toolbelt
) which is an extension of the core requests module that provides support for file upload streaming as well as the MultipartEncoder which can be used instead of files
, and which also lets you define the payload as a dictionary, tuple or list.
MultipartEncoder
can be used both for multipart requests with or without actual upload fields. It must be assigned to the data
parameter.
import requests
from requests_toolbelt.multipart.encoder import MultipartEncoder
multipart_data = MultipartEncoder(
fields={
# a file upload field
'file': ('file.zip', open('file.zip', 'rb'), 'text/plain')
# plain text fields
'field0': 'value0',
'field1': 'value1',
}
)
response = requests.post('http://httpbin.org/post', data=multipart_data,
headers={'Content-Type': multipart_data.content_type})
If you need to send multiple fields with the same name, or if the order of form fields is important, then a tuple or a list can be used instead of a dictionary:
multipart_data = MultipartEncoder(
fields=(
('action', 'ingest'),
('item', 'spam'),
('item', 'sausage'),
('item', 'eggs'),
)
)
In case you get a cross-domain error:
If you have control over the content of the iframe - that is, if it is merely loaded in a cross-origin setup such as on Amazon Mechanical Turk - you can circumvent this problem with the <body onload='my_func(my_arg)'>
attribute for the inner html.
For example, for the inner html, use the this
html parameter (yes - this
is defined and it refers to the parent window of the inner body element):
<body onload='changeForm(this)'>
In the inner html :
function changeForm(window) {
console.log('inner window loaded: do whatever you want with the inner html');
window.document.getElementById('mturk_form').style.display = 'none';
</script>
Now I've found the problem.
Removing the obj_exception_throw
from my breakpoints solved this. Now it's caught by the @try
block and also, NSSetUncaughtExceptionHandler
will handle this if a @try
block is missing.
"Impersonation" in the .NET space generally means running code under a specific user account. It is a somewhat separate concept than getting access to that user account via a username and password, although these two ideas pair together frequently. I will describe them both, and then explain how to use my SimpleImpersonation library, which uses them internally.
The APIs for impersonation are provided in .NET via the System.Security.Principal
namespace:
Newer code (.NET 4.6+, .NET Core, etc.) should generally use WindowsIdentity.RunImpersonated
, which accepts a handle to the token of the user account, and then either an Action
or Func<T>
for the code to execute.
WindowsIdentity.RunImpersonated(tokenHandle, () =>
{
// do whatever you want as this user.
});
or
var result = WindowsIdentity.RunImpersonated(tokenHandle, () =>
{
// do whatever you want as this user.
return result;
});
Older code used the WindowsIdentity.Impersonate
method to retrieve a WindowsImpersonationContext
object. This object implements IDisposable
, so generally should be called from a using
block.
using (WindowsImpersonationContext context = WindowsIdentity.Impersonate(tokenHandle))
{
// do whatever you want as this user.
}
While this API still exists in .NET Framework, it should generally be avoided, and is not available in .NET Core or .NET Standard.
The API for using a username and password to gain access to a user account in Windows is LogonUser
- which is a Win32 native API. There is not currently a built-in .NET API for calling it, so one must resort to P/Invoke.
[DllImport("advapi32.dll", SetLastError = true, CharSet = CharSet.Unicode)]
internal static extern bool LogonUser(String lpszUsername, String lpszDomain, String lpszPassword, int dwLogonType, int dwLogonProvider, out IntPtr phToken);
This is the basic call definition, however there is a lot more to consider to actually using it in production:
SecureString
when you can collect one safely via user keystrokes.The amount of code to write to illustrate all of this is beyond what should be in a StackOverflow answer, IMHO.
Instead of writing all of this yourself, consider using my SimpleImpersonation library, which combines impersonation and user access into a single API. It works well in both modern and older code bases, with the same simple API:
var credentials = new UserCredentials(domain, username, password);
Impersonation.RunAsUser(credentials, logonType, () =>
{
// do whatever you want as this user.
});
or
var credentials = new UserCredentials(domain, username, password);
var result = Impersonation.RunAsUser(credentials, logonType, () =>
{
// do whatever you want as this user.
return something;
});
Note that it is very similar to the WindowsIdentity.RunImpersonated
API, but doesn't require you know anything about token handles.
This is the API as of version 3.0.0. See the project readme for more details. Also note that a previous version of the library used an API with the IDisposable
pattern, similar to WindowsIdentity.Impersonate
. The newer version is much safer, and both are still used internally.
My workabout: I use asynchronous requests dumping the code to a buffer. I have a loop checking the buffer every second. When the dump has arrived to the buffer I execute the code. I also use a timeout. For the end user the page works as if synchronous requests would be used.
On modern browsers it's easy: just use the input event along with the inputType attribute:
$(document).on('input', 'input, textarea', function(e){
if (e.originalEvent.inputType == 'insertFromPaste') {
alert($(this).val());
}
});
@Entity
class Employee {
@OneToOne(orphanRemoval=true)
private Address address;
}
See here.
I'm still kind of learning Javascript but I came up with this function in C awhile ago, which uses math and a while loop rather than a string so I re-wrote it for Javascript. Maybe this could be done recursively somehow but I still haven't really grasped the concept :( This is the best I could come up with. I'm not sure how large of numbers it works with, it worked when I put in a hundred digits.
function count_digits(n) {
numDigits = 0;
integers = Math.abs(n);
while (integers > 0) {
integers = (integers - integers % 10) / 10;
numDigits++;
}
return numDigits;
}
edit: only works with integer values
As you know, MVC supports asynchronous controllers and you should take advantage of it. In case your Controller, performs a lengthy operation, (it might be a disk based I/o or a network call to another remote service), if the request is handled in synchronous manner, the IIS thread is busy the whole time. As a result, the thread is just waiting for the lengthy operation to complete. It can be better utilized by serving other requests while the operation requested in first is under progress. This will help in serving more concurrent requests. Your webservice will be highly scalable and will not easily run into C10k problem. It is a good idea to use async/await for db queries. and yes you can use them as many number of times as you deem fit.
Take a look here for excellent advise.
What do I need to do to make this function wait for the result of the promise?
Use async/await
(NOT Part of ECMA6, but
available for Chrome, Edge, Firefox and Safari since end of 2017, see canIuse)
MDN
async function waitForPromise() {
// let result = await any Promise, like:
let result = await Promise.resolve('this is a sample promise');
}
Added due to comment: An async function always returns a Promise, and in TypeScript it would look like:
async function waitForPromise(): Promise<string> {
// let result = await any Promise, like:
let result = await Promise.resolve('this is a sample promise');
}
Yes, just delete the branch by running git push origin :branchname
. To fix a new issue later, branch off from master again.
System.Diagnostics.Process.Start("PATH to exe", "Command Line Arguments");
The following simply returns 4 as an answer. When you replace the add expressions for strings it returns the first string.
Function StartingMain {
$a = 1 + 3
$b = 2 + 5
$c = 3 + 7
Return $a
}
Function StartingEnd($b) {
Write-Host $b
}
StartingEnd(StartingMain)
This can also be done for an array. The example below will return "Text 2"
Function StartingMain {
$a = ,@("Text 1","Text 2","Text 3")
Return $a
}
Function StartingEnd($b) {
Write-Host $b[1]
}
StartingEnd(StartingMain)
Note that you have to call the function below the function itself. Otherwise, the first time it runs it will return an error that it doesn't know what "StartingMain" is.
<TextView
android:id="@+id/layone"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Previous Page"
android:textColor="#000000"
android:textSize="16dp"
android:paddingLeft="10dp"
android:layout_marginTop="10dp"
android:visibility="gone" />
layone is a TextView.
You got your id wrong.
LinearLayout layone= (LinearLayout) view.findViewById(R.id.laytwo);// change id here
layone.setVisibility(View.VISIBLE);
should do the job.
or change like this to show the TextView:
TextView layone= (TextView) view.findViewById(R.id.layone);
layone.setVisibility(View.VISIBLE);
Add a backward slash in FIELDS TERMINATED BY '\;'
For Example:
CREATE TABLE demo_table_1_csv
COMMENT 'my_csv_table 1'
ROW FORMAT DELIMITED
FIELDS TERMINATED BY '\;'
LINES TERMINATED BY '\n'
STORED AS TEXTFILE
LOCATION 'your_hdfs_path'
AS
select a.tran_uuid,a.cust_id,a.risk_flag,a.lookback_start_date,a.lookback_end_date,b.scn_name,b.alerted_risk_category,
CASE WHEN (b.activity_id is not null ) THEN 1 ELSE 0 END as Alert_Flag
FROM scn1_rcc1_agg as a LEFT OUTER JOIN scenario_activity_alert as b ON a.tran_uuid = b.activity_id;
I have tested it, and it worked.
A class that is declared using the abstract keyword is known as abstract class
.
Abstraction is a process of hiding the data implementation details, and showing only functionality to the user. Abstraction lets you focus on what the object does instead of how it does it.
Main things of abstract class
An abstract class may or may not contain abstract methods.There can be non abstract methods.
An abstract method is a method that is declared without an implementation (without braces, and followed by a semicolon), like this:
ex : abstract void moveTo(double deltaX, double deltaY);
If a class has at least one abstract method then that class must be abstract
Abstract classes may not be instantiated (You are not allowed to create object of Abstract class)
To use an abstract class, you have to inherit it from another class. Provide implementations to all the abstract methods in it.
If you inherit an abstract class, you have to provide implementations to all the abstract methods in it.
Declare abstract class
Specifying abstract
keyword before the class during declaration makes it abstract. Have a look at the code below:
abstract class AbstractDemo{ }
Declare abstract method
Specifying abstract
keyword before the method during declaration makes it abstract. Have a look at the code below,
abstract void moveTo();//no body
Why we need to abstract classes
In an object-oriented drawing application, you can draw circles, rectangles, lines, Bezier curves, and many other graphic objects. These objects all have certain states (for ex -: position, orientation, line color, fill color) and behaviors (for ex -: moveTo, rotate, resize, draw) in common. Some of these states and behaviors are the same for all graphic objects (for ex : fill color, position, and moveTo). Others require different implementation(for ex: resize or draw). All graphic objects must be able to draw or resize themselves, they just differ in how they do it.
This is a perfect situation for an abstract superclass. You can take advantage of the similarities, and declare all the graphic objects to inherit from the same abstract parent object (for ex : GraphicObject
) as shown in the following figure.
First, you declare an abstract class, GraphicObject
, to provide member variables and methods that are wholly shared by all subclasses, such as the current position and the moveTo method. GraphicObject
also declared abstract methods, such as draw or resize, that need to be a implemented by all subclasses but must be implemented in different ways. The GraphicObject
class can look something like this:
abstract class GraphicObject {
void moveTo(int x, int y) {
// Inside this method we have to change the position of the graphic
// object according to x,y
// This is the same in every GraphicObject. Then we can implement here.
}
abstract void draw(); // But every GraphicObject drawing case is
// unique, not common. Then we have to create that
// case inside each class. Then create these
// methods as abstract
abstract void resize();
}
Usage of abstract method in sub classes
Each non abstract subclasses of GraphicObject
, such as Circle
and Rectangle
, must provide implementations for the draw
and resize
methods.
class Circle extends GraphicObject {
void draw() {
//Add to some implementation here
}
void resize() {
//Add to some implementation here
}
}
class Rectangle extends GraphicObject {
void draw() {
//Add to some implementation here
}
void resize() {
//Add to some implementation here
}
}
Inside the main
method you can call all methods like this:
public static void main(String args[]){
GraphicObject c = new Circle();
c.draw();
c.resize();
c.moveTo(4,5);
}
Ways to achieve abstraction in Java
There are two ways to achieve abstraction in java
Abstract class with constructors, data members, methods, etc
abstract class GraphicObject {
GraphicObject (){
System.out.println("GraphicObject is created");
}
void moveTo(int y, int x) {
System.out.println("Change position according to "+ x+ " and " + y);
}
abstract void draw();
}
class Circle extends GraphicObject {
void draw() {
System.out.println("Draw the Circle");
}
}
class TestAbstract {
public static void main(String args[]){
GraphicObject grObj = new Circle ();
grObj.draw();
grObj.moveTo(4,6);
}
}
Output:
GraphicObject is created
Draw the Circle
Change position according to 6 and 4
Remember two rules:
If the class has few abstract methods and few concrete methods,
declare it as an abstract
class.
If the class has only abstract methods, declare it as an interface
.
References:
I was facing same error. I have configured slf4j-api, slf4j-log4j12 and log4j, in my local development. All configuration was fine, but slf4j-log4j12 dependency which I copied from mvnrepository had test scope <scope>test</scope>
. When I removed this every thing is fine.
Some times silly mistakes breaks our head ;)
I have tried every method mentioned above and nothing worked, except installing jupyter in the new environment.
to activate the new environment
conda activate new_env
replace 'new_env' with your environment name.
next install jupyter 'pip install jupyter'
you can also install jupyter by going to anaconda navigator and selecting the right environment, and installing jupyter notebook from Home tab
It's even easier to do without a library
window.onload = function() {
// code
};
Beware: The correct answer is below. This no longer works
Create a file called .ember-cli
in your project, and include in it these contents:
{
"output-path": "./location/to/your/dist/"
}
At a guess, you used Code::Blocks to create a Console Application project. Such a project does not link in the GDI stuff, because console applications are generally not intended to do graphics, and TextOut
is a graphics function. If you want to use the features of the GDI, you should create a Win32 Gui Project, which will be set up to link in the GDI for you.
The HttpServletRequest
has the following methods:
getRequestURL()
- returns the part of the full URL before query string separator character ?
getQueryString()
- returns the part of the full URL after query string separator character ?
So, to get the full URL, just do:
public static String getFullURL(HttpServletRequest request) {
StringBuilder requestURL = new StringBuilder(request.getRequestURL().toString());
String queryString = request.getQueryString();
if (queryString == null) {
return requestURL.toString();
} else {
return requestURL.append('?').append(queryString).toString();
}
}
$created_po = array();
$challan = modelname::where('fieldname','!=', 0)->get();
// dd($challan);
foreach ($challan as $rec){
$created_po[] = array_push($created_po,$rec->fieldname);
}
$data = modelname::whereNotIn('fieldname',$created_po)->orderBy('fieldname','desc')->with('modelfunction')->get();
i myself like setTimeout
more that setInterval
but didn't find a solution in class based component .you could use sth like this in class based components:
class Clock extends React.Component {
constructor(props) {
super(props);
this.state = {
date: new Date()
};
}
componentDidMount() {
this.timerID = setInterval(
() => this.tick(),
1000
);
}
componentWillUnmount() {
clearInterval(this.timerID);
}
tick() {
this.setState({
date: new Date()
});
}
render() {
return (
this.state.date.toLocaleTimeString()
);
}
}
ReactDOM.render(
<Clock / > ,
document.getElementById('app')
);
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
<div id="app" />
_x000D_
https://codesandbox.io/s/sweet-diffie-wsu1t?file=/src/index.js
try:
r = requests.post(url, data=data, verify='/path/to/public_key.pem')
For non-object return types, you have to assign the value to the name of your function, like this:
Public Function test() As Integer
test = 1
End Function
Example usage:
Dim i As Integer
i = test()
If the function returns an Object type, then you must use the Set
keyword like this:
Public Function testRange() As Range
Set testRange = Range("A1")
End Function
Example usage:
Dim r As Range
Set r = testRange()
Note that assigning a return value to the function name does not terminate the execution of your function. If you want to exit the function, then you need to explicitly say Exit Function
. For example:
Function test(ByVal justReturnOne As Boolean) As Integer
If justReturnOne Then
test = 1
Exit Function
End If
'more code...
test = 2
End Function
Documentation: http://msdn.microsoft.com/en-us/library/office/gg264233%28v=office.14%29.aspx
I know my solution is not very popular from the pythonic point of view, but I prefer to use the Java approach of one module->one class, with the module named as the class. I do understand the reason behind the python style, but I am not too fond of having a very large file containing a lot of classes. I find it difficult to browse, despite folding.
Another reason is version control: having a large file means that your commits tend to concentrate on that file. This can potentially lead to a higher quantity of conflicts to be resolved. You also loose the additional log information that your commit modifies specific files (therefore involving specific classes). Instead you see a modification to the module file, with only the commit comment to understand what modification has been done.
Summing up, if you prefer the python philosophy, go for the suggestions of the other posts. If you instead prefer the java-like philosophy, create a Nib.py containing class Nib.
[Edit] Very wrong! The setdefault would always trigger long_computation, Python being eager.
Expanding on Tuttle's answer. For me the best use case is cache mechanism. Instead of:
if x not in memo:
memo[x]=long_computation(x)
return memo[x]
which consumes 3 lines and 2 or 3 lookups, I would happily write :
return memo.setdefault(x, long_computation(x))
You can use the custom TextView for whole app with custom font here is an example for that
public class MyTextView extends TextView {
Typeface normalTypeface = Typeface.createFromAsset(getContext().getAssets(), Constants.FONT_REGULAR);
Typeface boldTypeface = Typeface.createFromAsset(getContext().getAssets(), Constants.FONT_BOLD);
public MyTextView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
public MyTextView(Context context, AttributeSet attrs) {
super(context, attrs);
}
public MyTextView(Context context) {
super(context);
}
public void setTypeface(Typeface tf, int style) {
if (style == Typeface.BOLD) {
super.setTypeface(boldTypeface/*, -1*/);
} else {
super.setTypeface(normalTypeface/*, -1*/);
}
}
}
Ok so here's how I figured this out. It all has to do with CORS policy. Before the POST request, Chrome was doing a preflight OPTIONS request, which should be handled and acknowledged by the server prior to the actual request. Now this is really not what I wanted for such a simple server. Hence, resetting the headers client side prevents the preflight:
app.config(function ($httpProvider) {
$httpProvider.defaults.headers.common = {};
$httpProvider.defaults.headers.post = {};
$httpProvider.defaults.headers.put = {};
$httpProvider.defaults.headers.patch = {};
});
The browser will now send a POST directly. Hope this helps a lot of folks out there... My real problem was not understanding CORS enough.
Link to a great explanation: http://www.html5rocks.com/en/tutorials/cors/
Kudos to this answer for showing me the way.
import UIKit
import SafariServices
let url = URL(string: "https://sprotechs.com")
let vc = SFSafariViewController(url: url!)
present(vc, animated: true, completion: nil)
Yes assuming you have this:
var WhatIsThe = AnswerToLife()
func AnswerToLife() int {
return 42
}
func init() {
WhatIsThe = 0
}
func main() {
if WhatIsThe == 0 {
fmt.Println("It's all a lie.")
}
}
AnswerToLife()
is guaranteed to run before init()
is called, and init()
is guaranteed to run before main()
is called.
Keep in mind that init()
is always called, regardless if there's main or not, so if you import a package that has an init
function, it will be executed.
Additionally, you can have multiple init()
functions per package; they will be executed in the order they show up in the file (after all variables are initialized of course). If they span multiple files, they will be executed in lexical file name order (as pointed out by @benc):
It seems that
init()
functions are executed in lexical file name order. The Go spec says "build systems are encouraged to present multiple files belonging to the same package in lexical file name order to a compiler". It seems thatgo build
works this way.
A lot of the internal Go packages use init()
to initialize tables and such, for example https://github.com/golang/go/blob/883bc6/src/compress/bzip2/bzip2.go#L480
First go to the pip documentation if not install before: http://pip.readthedocs.org/en/stable/installing/
and follow the install pip which is first download get-pip.py from https://bootstrap.pypa.io/get-pip.py
Then run the following (which may require administrator access): python get-pip.py
Using apache's rewrite_module can change your script extensions. Give this thread a good read.
Just do:
SET
You can also do SET prefix
to see all variables with names starting with prefix
.
For example, if you want to read only derbydb from the environment variables, do the following:
set derby
...and you will get the following:
DERBY_HOME=c:\Users\amro-a\Desktop\db-derby-10.10.1.1-bin\db-derby-10.10.1.1-bin
Create a shortcut with something like this as the "Target":
powershell.exe -command "& 'C:\A path with spaces\MyScript.ps1' -MyArguments blah"
Since it wasn't stated clearly, I just add this:
I was looking for a way to create a table which holds the number of occurrences of all the data types.
Say we have a data.frame
with two numeric and one logical column
dta <- data.frame(a = c(1,2,3),
b = c(4,5,6),
c = c(TRUE, FALSE, TRUE))
You can summarize the number of columns of each data type with that
table(unlist(lapply(dta, class)))
# logical numeric
# 1 2
This comes extremely handy, if you have a lot of columns and want to get a quick overview.
To give credit: This solution was inspired by the answer of @Cybernetic.
since it's a list it cannot be taken directly into range function as the singular integer value of the list is missing.
use this
for i in range(len(myList)):
with this, we get the singular integer value which can be used easily
Selects a subset of the array to return based on the specified condition. Returns an array with only those elements that match the condition. The returned elements are in the original order.
db.test.aggregate([
{$match: {"list.a": {$gt:3}}}, // <-- match only the document which have a matching element
{$project: {
list: {$filter: {
input: "$list",
as: "list",
cond: {$gt: ["$$list.a", 3]} //<-- filter sub-array based on condition
}}
}}
]);
Here is a simple context manager that prints to the console and writes the same output to an file. It also writes any exceptions to the file.
import traceback
import sys
# Context manager that copies stdout and any exceptions to a log file
class Tee(object):
def __init__(self, filename):
self.file = open(filename, 'w')
self.stdout = sys.stdout
def __enter__(self):
sys.stdout = self
def __exit__(self, exc_type, exc_value, tb):
sys.stdout = self.stdout
if exc_type is not None:
self.file.write(traceback.format_exc())
self.file.close()
def write(self, data):
self.file.write(data)
self.stdout.write(data)
def flush(self):
self.file.flush()
self.stdout.flush()
To use the context manager:
print("Print")
with Tee('test.txt'):
print("Print+Write")
raise Exception("Test")
print("Print")
Just add C:\OpenCV2.0\bin
into your PATH environment variable
or
When you install OpenCV,
Choose the option, Add OpenCV to the system PATH for current user
which is not default one
$.getJSON
is an asynchronous request, meaning the code will continue to run even though the request is not yet done. You should trigger the second request when the first one is done, one of the choices you seen already in ComFreek's answer.
Alternatively you could use jQuery's $.when/.then(), similar to this:
var input = "netuetamundis"; var sID; $(document).ready(function () { $.when($.getJSON("https://prod.api.pvp.net/api/lol/eune/v1.1/summoner/by-name/" + input + "?api_key=API_KEY_HERE", function () { obj = name; sID = obj.id; console.log(sID); })).then(function () { $.getJSON("https://prod.api.pvp.net/api/lol/eune/v1.2/stats/by-summoner/" + sID + "/summary?api_key=API_KEY_HERE", function (stats) { console.log(stats); }); }); });
This would be more open for future modification and separates out the responsibility for the first call to know about the second call.
The first call can simply complete and do it's own thing not having to be aware of any other logic you may want to add, leaving the coupling of the logic separated.
If you are using Outlook 2010, you can define your own style and select your formatting you want, in the Format options there is one option for Language, here you can specify the language and specify whether you want spell checker to ignore the text with this style.
With this style you can now paste the code as text and select your new style. Outlook will not correct the text and will not perform the spell check on it.
Below is the summary of the style I have defined for emailing the code snippets.
Do not check spelling or grammar, Border:
Box: (Single solid line, Orange, 0.5 pt Line width)
Pattern: Clear (Custom Color(RGB(253,253,217))), Style: Linked, Automatically update, Quick Style
Based on: HTML Preformatted
here's a pure Javascript alternative:
var mydiv = document.getElementById("myDiv");
var aTag = document.createElement('a');
aTag.setAttribute('href',"yourlink.htm");
aTag.innerText = "link text";
mydiv.appendChild(aTag);
Have seen so many that don't really work. when a temp table is created it must be deleted from the tempdb!
The only code that works is:
IF OBJECT_ID('tempdb..#tempdbname') IS NOT NULL --Remove dbo here
DROP TABLE #tempdbname -- Remoeve "tempdb.dbo"
Saving (w/o exception handling code):
FileOutputStream fos = context.openFileOutput(fileName, Context.MODE_PRIVATE);
ObjectOutputStream os = new ObjectOutputStream(fos);
os.writeObject(this);
os.close();
fos.close();
Loading (w/o exception handling code):
FileInputStream fis = context.openFileInput(fileName);
ObjectInputStream is = new ObjectInputStream(fis);
SimpleClass simpleClass = (SimpleClass) is.readObject();
is.close();
fis.close();
You can also take advantage of the built-in Service Parameters system, which lets you isolate or reuse the value:
# app/config/parameters.yml
parameters:
ga_tracking: UA-xxxxx-x
# app/config/config.yml
twig:
globals:
ga_tracking: "%ga_tracking%"
Now, the variable ga_tracking is available in all Twig templates:
<p>The google tracking code is: {{ ga_tracking }}</p>
The parameter is also available inside the controllers:
$this->container->getParameter('ga_tracking');
You can also define a service as a global Twig variable (Symfony2.2+):
# app/config/config.yml
twig:
# ...
globals:
user_management: "@acme_user.user_management"
http://symfony.com/doc/current/templating/global_variables.html
If the global variable you want to set is more complicated - say an object - then you won't be able to use the above method. Instead, you'll need to create a Twig Extension and return the global variable as one of the entries in the getGlobals method.
As Robert has pointed out in his answer: DecimalFormat is neither synchronized nor does the API guarantee thread safety (it might depend on the JVM version/vendor you are using).
Use Spring's Numberformatter instead, which is thread safe.
In my case, I was trying to embed the Facebook SDK and I was having the wrong Application ID; thus the error was popping up. In your manifest file, you should have the proper meta data:
<meta-data
android:name="com.facebook.sdk.ApplicationId"
android:value="@string/facebook_app_id" />
Try Demo Here
var list ={}; var count= Object.keys(list).length;
It is also worth noting that in the cascade, an id (#
) selector is more specific than a b (.
) selector. Therefore, rules in the id statement will override rules in the class statement.
For example, if both of the following statements:
.headline {
color:red;
font-size: 3em;
}
#specials {
color:blue;
font-style: italic;
}
are applied to the same HTML element:
<h1 id="specials" class="headline">Today's Specials</h1>
the color:blue rule would override the color:red rule.
I try to set type of column as 'timestamp' and it works for me.
Contrary to Mark Novakowski answer, which for some reason has been upvoted by many, yes, it is a valid and satisfiable request.
In fact the standard, as Wrikken pointed out, makes just such an example. In practice, Apache responds to such requests as expected (with a 206 code), and this is exactly what I use to implement progressive download, that is, only get the tail of a long log file which grows in real time with polling.
The comp.lang.c FAQ list shares three different ways to easily generate random numbers with a Gaussian distribution.
You may take a look of it: http://c-faq.com/lib/gaussian.html
You are using two WHERE
clauses but only one is allowed. Use it like this:
SELECT table1.f_id FROM table1
INNER JOIN table2 ON table2.f_id = table1.f_id
WHERE
table1.f_com_id = '430'
AND table1.f_status = 'Submitted'
AND table2.f_type = 'InProcess'
To install specific version of laravel try this & simply command on terminal
composer create-project --prefer-dist laravel/laravel:5.5.0 {dir-name}
Apple's Technote on App Transport Security is very handy; it helped us find a more secure solution to our issue.
Hopefully this will help someone else. We were having issues connecting to Amazon S3 URLs that appeared to be perfectly valid, TLSv12 HTTPS URLs. Turns out we had to disable NSExceptionRequiresForwardSecrecy
to enable another handful of ciphers that S3 uses.
In our Info.plist
:
<key>NSAppTransportSecurity</key>
<dict>
<key>NSExceptionDomains</key>
<dict>
<key>amazonaws.com</key>
<dict>
<key>NSIncludesSubdomains</key>
<true/>
<key>NSExceptionRequiresForwardSecrecy</key>
<false/>
</dict>
</dict>
</dict>
You can have all the different styles to datetime conversion
:
https://www.w3schools.com/sql/func_sqlserver_convert.asp
This has range of values :-
CONVERT(data_type(length),expression,style)
For style values,
Choose anyone you need like I needed 106.
Even though it's convenient to use, it seems like the convert-to-hash solution costs quite a lot of performance, which was an issue for me.
#!/usr/bin/perl
use Benchmark;
my @list;
for (1..10_000) {
push @list, $_;
}
timethese(10000, {
'grep' => sub {
if ( grep(/^5000$/o, @list) ) {
# code
}
},
'hash' => sub {
my %params = map { $_ => 1 } @list;
if ( exists($params{5000}) ) {
# code
}
},
});
Output of benchmark test:
Benchmark: timing 10000 iterations of grep, hash...
grep: 8 wallclock secs ( 7.95 usr + 0.00 sys = 7.95 CPU) @ 1257.86/s (n=10000)
hash: 50 wallclock secs (49.68 usr + 0.01 sys = 49.69 CPU) @ 201.25/s (n=10000)
use
console.log(variable)
and if you using google chrome open Console by using Ctrl+Shift+j
Goto >> Console
Following code will generate a random sample of size 4:
import random
sample_size = 4
sorted_sample = [
mylist[i] for i in sorted(random.sample(range(len(mylist)), sample_size))
]
(note: with Python 2, better use xrange
instead of range
)
Explanation
random.sample(range(len(mylist)), sample_size)
generates a random sample of the indices of the original list.
These indices then get sorted to preserve the ordering of elements in the original list.
Finally, the list comprehension pulls out the actual elements from the original list, given the sampled indices.
I've wrote such a simple class:
public static class WatermarkExtension
{
public static MvcHtmlString WatermarkFor<TModel, TValue>(this HtmlHelper<TModel> html, Expression<Func<TModel, TValue>> expression)
{
var watermark = ModelMetadata.FromLambdaExpression(expression, html.ViewData).Watermark;
var htmlEncoded = HttpUtility.HtmlEncode(watermark);
return new MvcHtmlString(htmlEncoded);
}
}
The usage as such:
@Html.TextBoxFor(model => model.AddressSuffix, new {placeholder = Html.WatermarkFor(model => model.AddressSuffix)})
And property in a viewmodel:
[Display(ResourceType = typeof (Resources), Name = "AddressSuffixLabel", Prompt = "AddressSuffixPlaceholder")]
public string AddressSuffix
{
get { return _album.AddressSuffix; }
set { _album.AddressSuffix = value; }
}
Notice Prompt parameter. In this case I use strings from resources for localization but you can use just strings, just avoid ResourceType parameter.
Use a PHP Excel for generatingExcel file. You can find a good one called PHPExcel here: https://github.com/PHPOffice/PHPExcel
And for PDF
generation use http://princexml.com/
For multiple plots in a single pdf file you can use PdfPages
In the plotGraph
function you should return the figure and than call savefig
of the figure object.
------ plotting module ------
def plotGraph(X,Y):
fig = plt.figure()
### Plotting arrangements ###
return fig
------ plotting module ------
----- mainModule ----
from matplotlib.backends.backend_pdf import PdfPages
plot1 = plotGraph(tempDLstats, tempDLlabels)
plot2 = plotGraph(tempDLstats_1, tempDLlabels_1)
plot3 = plotGraph(tempDLstats_2, tempDLlabels_2)
pp = PdfPages('foo.pdf')
pp.savefig(plot1)
pp.savefig(plot2)
pp.savefig(plot3)
pp.close()
See the official documentation (http://docs.oracle.com/cd/B19306_01/server.102/b14200/sql_elements001.htm#i54330)
Variable-length character string having maximum length size bytes or characters. Maximum size is 4000 bytes or characters, and minimum is 1 byte or 1 character. You must specify size for VARCHAR2. BYTE indicates that the column will have byte length semantics; CHAR indicates that the column will have character semantics.
But in Oracle Databast 12c maybe 32767 (http://docs.oracle.com/database/121/SQLRF/sql_elements001.htm#SQLRF30020)
Variable-length character string having maximum length size bytes or characters. You must specify size for VARCHAR2. Minimum size is 1 byte or 1 character. Maximum size is: 32767 bytes or characters if MAX_STRING_SIZE = EXTENDED 4000 bytes or characters if MAX_STRING_SIZE = STANDARD
NaN
means "Not a number." It's a special floating point value that means that the result of an operation was not defined or not representable as a real number.
See here for more explanation of this value.
I have to work in tcsh, and I know this is not an elegant solution, but for example, if I had to change folders to a path where one word is different, the whole thing can be done in the alias
a alias_name 'set a = `pwd`; set b = `echo $a | replace "Trees" "Tests"` ; cd $b'
If the path is always fixed, the just
a alias_name2 'cd path/you/always/need'
should work In the line above, the new folder path is set
This is the complete answer to my question. I had originally marked @Colin Williams' answer as the correct answer, as it helped me get to the complete solution. A community member, @Slipp D. Thompson edited my question, after about 2.5 years of me having asked it, and told me I was abusing SO's Q & A format. He also told me to separately post this as the answer. So here's the complete answer that solved my problem:
@Colin Williams, thank you! Your answer and the article you linked out to gave me a lead to try something with CSS.
So, I was using translate3d before. It produced unwanted results. Basically, it would chop off and NOT RENDER elements that were offscreen, until I interacted with them. So, basically, in landscape orientation, half of my site that was offscreen was not being shown. This is a iPad web app, owing to which I was in a fix.
Applying translate3d to relatively positioned elements solved the problem for those elements, but other elements stopped rendering, once offscreen. The elements that I couldn't interact with (artwork) would never render again, unless I reloaded the page.
The complete solution:
*:not(html) {
-webkit-transform: translate3d(0, 0, 0);
}
Now, although this might not be the most "efficient" solution, it was the only one that works. Mobile Safari does not render the elements that are offscreen, or sometimes renders erratically, when using -webkit-overflow-scrolling: touch
. Unless a translate3d is applied to all other elements that might go offscreen owing to that scroll, those elements will be chopped off after scrolling.
So, thanks again, and hope this helps some other lost soul. This surely helped me big time!
Here is my class, works like a charm :
public static class IniFileManager
{
[DllImport("kernel32")]
private static extern long WritePrivateProfileString(string section,
string key, string val, string filePath);
[DllImport("kernel32")]
private static extern int GetPrivateProfileString(string section,
string key, string def, StringBuilder retVal,
int size, string filePath);
[DllImport("kernel32.dll")]
private static extern int GetPrivateProfileSection(string lpAppName,
byte[] lpszReturnBuffer, int nSize, string lpFileName);
/// <summary>
/// Write Data to the INI File
/// </summary>
/// <PARAM name="Section"></PARAM>
/// Section name
/// <PARAM name="Key"></PARAM>
/// Key Name
/// <PARAM name="Value"></PARAM>
/// Value Name
public static void IniWriteValue(string sPath,string Section, string Key, string Value)
{
WritePrivateProfileString(Section, Key, Value, sPath);
}
/// <summary>
/// Read Data Value From the Ini File
/// </summary>
/// <PARAM name="Section"></PARAM>
/// <PARAM name="Key"></PARAM>
/// <PARAM name="Path"></PARAM>
/// <returns></returns>
public static string IniReadValue(string sPath,string Section, string Key)
{
StringBuilder temp = new StringBuilder(255);
int i = GetPrivateProfileString(Section, Key, "", temp,
255, sPath);
return temp.ToString();
}
}
The use is obviouse since its a static class, just call IniFileManager.IniWriteValue for readsing a section or IniFileManager.IniReadValue for reading a section.
Steps to start Apache Tomcat using cmd:
1. Firstly check that the JRE_HOME or JAVA_HOME is a variable available in environment variables.(If it is not create a new variable JRE_HOME or JAVA_HOME)
2. Goto cmd and change your working directory to bin path where apache is installed (or extracted).
3. Type Command -> catalina.bat start
to start the server.
4. Type Command -> catalina.bat stop
to stop the server.
If you're in a heavily concurrent environment, then pure functional programming is useful. The lack of mutable state makes concurrency almost trivial. See Erlang.
In a multiparadigm language, you may want to model some things functionally if the existence of mutable state is must an implementation detail, and thus FP is a good model for the problem domain. For example, see list comprehensions in Python or std.range in the D programming language. These are inspired by functional programming.
execCommand('SaveAs', false, filename);
functionalityEdit: No longer works. This Javascript function used to work across all browsers, but now only on IE, due to browser security considerations. It presented a "Save As" Dialog to the user who runs this function through their browser, the user presses OK and the file is saved by javascript on the server side.
Now this code is an rare antique zero day collectible.
// content is the data (a string) you'll write to file.
// filename is a string filename to write to on server side.
// This function uses iFrame as a buffer, it fills it up with your content
// and prompts the user to save it out.
function save_content_to_file(content, filename){
var dlg = false;
with(document){
ir=createElement('iframe');
ir.id='ifr';
ir.location='about.blank';
ir.style.display='none';
body.appendChild(ir);
with(getElementById('ifr').contentWindow.document){
open("text/plain", "replace");
charset = "utf-8";
write(content);
close();
document.charset = "utf-8";
dlg = execCommand('SaveAs', false, filename);
}
body.removeChild(ir);
}
return dlg;
}
Invoke the function like this:
msg = "I am the president of tautology club.";
save_content_to_file(msg, "C:\\test");
C++ answer, flexible API, assumes little-endian system to code-golf it a bit. Note this uses the bmp native y-axis (0 at the bottom).
#include <vector>
#include <fstream>
struct image
{
image(int width, int height)
: w(width), h(height), rgb(w * h * 3)
{}
uint8_t & r(int x, int y) { return rgb[(x + y*w)*3 + 2]; }
uint8_t & g(int x, int y) { return rgb[(x + y*w)*3 + 1]; }
uint8_t & b(int x, int y) { return rgb[(x + y*w)*3 + 0]; }
int w, h;
std::vector<uint8_t> rgb;
};
template<class Stream>
Stream & operator<<(Stream & out, image const& img)
{
uint32_t w = img.w, h = img.h;
uint32_t pad = w * -3 & 3;
uint32_t total = 54 + 3*w*h + pad*h;
uint32_t head[13] = {total, 0, 54, 40, w, h, (24<<16)|1};
char const* rgb = (char const*)img.rgb.data();
out.write("BM", 2);
out.write((char*)head, 52);
for(uint32_t i=0 ; i<h ; i++)
{ out.write(rgb + (3 * w * i), 3 * w);
out.write((char*)&pad, pad);
}
return out;
}
int main()
{
image img(100, 100);
for(int x=0 ; x<100 ; x++)
{ for(int y=0 ; y<100 ; y++)
{ img.r(x,y) = x;
img.g(x,y) = y;
img.b(x,y) = 100-x;
}
}
std::ofstream("/tmp/out.bmp") << img;
}
...none of the other answers seem to do what the asker asked.
For table named 'things' with column 'group':
SELECT
things.*, counter.count
FROM
things
LEFT JOIN (
SELECT
things.group, count(things.group) as count
FROM
things
GROUP BY
things.group
) counter ON counter.group = things.group
ORDER BY
counter.count ASC;
which gives:
id | name | group | count
---------------------------
3 | Cat | B | 1
1 | Apple | A | 2
2 | Boy | A | 2
4 | Dog | C | 3
5 | Elep | C | 3
6 | Fish | C | 3
From a child component you can access the properties and methods of the parent component with 'require'. Here is an example:
Parent:
.component('myParent', mymodule.MyParentComponent)
...
controllerAs: 'vm',
...
var vm = this;
vm.parentProperty = 'hello from parent';
Child:
require: {
myParentCtrl: '^myParent'
},
controllerAs: 'vm',
...
var vm = this;
vm.myParentCtrl.parentProperty = 'hello from child';
You can do it like... Just give the proper path of your json file...
<!doctype html>
<html>
<head>
<script type="text/javascript" src="abc.json"></script>
<script type="text/javascript" >
function load() {
var mydata = JSON.parse(data);
alert(mydata.length);
var div = document.getElementById('data');
for(var i = 0;i < mydata.length; i++)
{
div.innerHTML = div.innerHTML + "<p class='inner' id="+i+">"+ mydata[i].name +"</p>" + "<br>";
}
}
</script>
</head>
<body onload="load()">
<div id= "data">
</div>
</body>
</html>
Simply getting the data and appending it to a div... Initially printing the length in alert.
Here is my Json file: abc.json
data = '[{"name" : "Riyaz"},{"name" : "Javed"},{"name" : "Arun"},{"name" : "Sunil"},{"name" : "Rahul"},{"name" : "Anita"}]';
Firstly for technical accuracy, border-radius
is not a HTML5 feature, it's a CSS3 feature.
The best script I've found to render box shadows & rounded corners in older IE versions is IE-CSS3. It translates CSS3 syntax into VML (an IE-specific Vector language like SVG) and renders them on screen.
It works a lot better on IE7-8 than on IE6, but does support IE6 as well. I didn't think much to PIE when I used it and found that (like HTC) it wasn't really built to be functional.
import UIKit
// MARK: - UITableView reloading functions
protocol ReloadCompletable: class { func reloadData() }
extension ReloadCompletable {
func run(transaction closure: (() -> Void)?, completion: (() -> Void)?) {
guard let closure = closure else { return }
CATransaction.begin()
CATransaction.setCompletionBlock(completion)
closure()
CATransaction.commit()
}
func run(transaction closure: (() -> Void)?, completion: ((Self) -> Void)?) {
run(transaction: closure) { [weak self] in
guard let self = self else { return }
completion?(self)
}
}
func reloadData(completion closure: ((Self) -> Void)?) {
run(transaction: { [weak self] in self?.reloadData() }, completion: closure)
}
}
// MARK: - UITableView reloading functions
extension ReloadCompletable where Self: UITableView {
func reloadRows(at indexPaths: [IndexPath], with animation: UITableView.RowAnimation, completion closure: ((Self) -> Void)?) {
run(transaction: { [weak self] in self?.reloadRows(at: indexPaths, with: animation) }, completion: closure)
}
func reloadSections(_ sections: IndexSet, with animation: UITableView.RowAnimation, completion closure: ((Self) -> Void)?) {
run(transaction: { [weak self] in self?.reloadSections(sections, with: animation) }, completion: closure)
}
}
// MARK: - UICollectionView reloading functions
extension ReloadCompletable where Self: UICollectionView {
func reloadSections(_ sections: IndexSet, completion closure: ((Self) -> Void)?) {
run(transaction: { [weak self] in self?.reloadSections(sections) }, completion: closure)
}
func reloadItems(at indexPaths: [IndexPath], completion closure: ((Self) -> Void)?) {
run(transaction: { [weak self] in self?.reloadItems(at: indexPaths) }, completion: closure)
}
}
UITableView
// Activate
extension UITableView: ReloadCompletable { }
// ......
let tableView = UICollectionView()
// reload data
tableView.reloadData { tableView in print(collectionView) }
// or
tableView.reloadRows(at: indexPathsToReload, with: rowAnimation) { tableView in print(tableView) }
// or
tableView.reloadSections(IndexSet(integer: 0), with: rowAnimation) { _tableView in print(tableView) }
UICollectionView
// Activate
extension UICollectionView: ReloadCompletable { }
// ......
let collectionView = UICollectionView()
// reload data
collectionView.reloadData { collectionView in print(collectionView) }
// or
collectionView.reloadItems(at: indexPathsToReload) { collectionView in print(collectionView) }
// or
collectionView.reloadSections(IndexSet(integer: 0)) { collectionView in print(collectionView) }
Do not forget to add the solution code here
import UIKit
class ViewController: UIViewController {
private weak var navigationBar: UINavigationBar?
private weak var tableView: UITableView?
override func viewDidLoad() {
super.viewDidLoad()
setupNavigationItem()
setupTableView()
}
}
// MARK: - Activate UITableView reloadData with completion functions
extension UITableView: ReloadCompletable { }
// MARK: - Setup(init) subviews
extension ViewController {
private func setupTableView() {
guard let navigationBar = navigationBar else { return }
let tableView = UITableView()
view.addSubview(tableView)
tableView.translatesAutoresizingMaskIntoConstraints = false
tableView.topAnchor.constraint(equalTo: navigationBar.bottomAnchor).isActive = true
tableView.leftAnchor.constraint(equalTo: view.leftAnchor).isActive = true
tableView.rightAnchor.constraint(equalTo: view.rightAnchor).isActive = true
tableView.bottomAnchor.constraint(equalTo: view.bottomAnchor).isActive = true
tableView.dataSource = self
self.tableView = tableView
}
private func setupNavigationItem() {
let navigationBar = UINavigationBar()
view.addSubview(navigationBar)
self.navigationBar = navigationBar
navigationBar.translatesAutoresizingMaskIntoConstraints = false
navigationBar.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor).isActive = true
navigationBar.leftAnchor.constraint(equalTo: view.leftAnchor).isActive = true
navigationBar.rightAnchor.constraint(equalTo: view.rightAnchor).isActive = true
let navigationItem = UINavigationItem()
navigationItem.rightBarButtonItem = UIBarButtonItem(title: "all", style: .plain, target: self, action: #selector(reloadAllCellsButtonTouchedUpInside(source:)))
let buttons: [UIBarButtonItem] = [
.init(title: "row", style: .plain, target: self,
action: #selector(reloadRowButtonTouchedUpInside(source:))),
.init(title: "section", style: .plain, target: self,
action: #selector(reloadSectionButtonTouchedUpInside(source:)))
]
navigationItem.leftBarButtonItems = buttons
navigationBar.items = [navigationItem]
}
}
// MARK: - Buttons actions
extension ViewController {
@objc func reloadAllCellsButtonTouchedUpInside(source: UIBarButtonItem) {
let elementsName = "Data"
print("-- Reloading \(elementsName) started")
tableView?.reloadData { taleView in
print("-- Reloading \(elementsName) stopped \(taleView)")
}
}
private var randomRowAnimation: UITableView.RowAnimation {
return UITableView.RowAnimation(rawValue: (0...6).randomElement() ?? 0) ?? UITableView.RowAnimation.automatic
}
@objc func reloadRowButtonTouchedUpInside(source: UIBarButtonItem) {
guard let tableView = tableView else { return }
let elementsName = "Rows"
print("-- Reloading \(elementsName) started")
let indexPathToReload = tableView.indexPathsForVisibleRows?.randomElement() ?? IndexPath(row: 0, section: 0)
tableView.reloadRows(at: [indexPathToReload], with: randomRowAnimation) { _tableView in
//print("-- \(taleView)")
print("-- Reloading \(elementsName) stopped in \(_tableView)")
}
}
@objc func reloadSectionButtonTouchedUpInside(source: UIBarButtonItem) {
guard let tableView = tableView else { return }
let elementsName = "Sections"
print("-- Reloading \(elementsName) started")
tableView.reloadSections(IndexSet(integer: 0), with: randomRowAnimation) { _tableView in
//print("-- \(taleView)")
print("-- Reloading \(elementsName) stopped in \(_tableView)")
}
}
}
extension ViewController: UITableViewDataSource {
func numberOfSections(in tableView: UITableView) -> Int { return 1 }
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return 20 }
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = UITableViewCell()
cell.textLabel?.text = "\(Date())"
return cell
}
}
You can let PHP do a POST, but then your php will get the return, with all sorts of complications. I think the simplest would be to actually let the user do the POST.
So, kind-of what you suggested, you'll get indeed this part:
Customer fill detail in Page A, then in Page B we create another page show all the customer detail there, click a CONFIRM button then POST to Page C.
But you can actually do a javascript submit on page B, so there is no need for a click. Make it a "redirecting" page with a loading animation, and you're set.
$('.handle').css('left','300px')
try this, identificator first then the value
Set a https://mitmproxy.org/ as proxy on a same LAN
Go to Control Panel\All Control Panel Items\User Accounts using Explorer (not Internet Explorer!)
or
Change my environment variables
New...
(if you don't have enough permissions to add it in the System variables section, add it to the User variables section)
Add JAVA_HOME as Variable name and the JDK location as Variable value > OK
Test:
set JAVA_HOME
JAVA_HOME=C:\Program Files\Java\jdk1.8.0_60
For Ruby 2.5 or newer with transform_keys and delete_prefix / delete_suffix methods:
hash1 = { '_id' => 'random1' }
hash2 = { 'old_first' => '123456', 'old_second' => '234567' }
hash3 = { 'first_com' => 'google.com', 'second_com' => 'amazon.com' }
hash1.transform_keys { |key| key.delete_prefix('_') }
# => {"id"=>"random1"}
hash2.transform_keys { |key| key.delete_prefix('old_') }
# => {"first"=>"123456", "second"=>"234567"}
hash3.transform_keys { |key| key.delete_suffix('_com') }
# => {"first"=>"google.com", "second"=>"amazon.com"}
You can use a RegularExpression validator. The ValidationExpression property has a button you can press in Visual Studio's property's panel that gets lists a lot of useful expressions. The one they use for email addresses is:
\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*
As mainframer said, you can use grep, but i would use exit status for testing, try this:
#!/bin/bash
# Test if anotherstring is contained in teststring
teststring="put you string here"
anotherstring="string"
echo ${teststring} | grep --quiet "${anotherstring}"
# Exit status 0 means anotherstring was found
# Exit status 1 means anotherstring was not found
if [ $? = 1 ]
then
echo "$anotherstring was not found"
fi
In HTTP the error occurs.
Set permission for localhost in bellow label(Accept requests from these HTTP referrers (web sites)).
It worked for me.
Your code would be like this:
int *p = (int *)0x28ff44;
int
needs to be the type of the object that you are referencing or it can be void
.
But be careful so that you don't try to access something that doesn't belong to your program.
hashCode()
method is used to get a unique integer for given object. This integer is used for determining the bucket location, when this object needs to be stored in some HashTable
, HashMap
like data structure. By default, Object’s hashCode()
method returns and integer representation of memory address where object is stored.
The hashCode()
method of objects is used when we insert them into a HashTable
, HashMap
or HashSet
. More about HashTables
on Wikipedia.org for reference.
To insert any entry in map data structure, we need both key and value. If both key and values are user define data types, the hashCode()
of the key will be determine where to store the object internally. When require to lookup the object from the map also, the hash code of the key will be determine where to search for the object.
The hash code only points to a certain "area" (or list, bucket etc) internally. Since different key objects could potentially have the same hash code, the hash code itself is no guarantee that the right key is found. The HashTable
then iterates this area (all keys with the same hash code) and uses the key's equals()
method to find the right key. Once the right key is found, the object stored for that key is returned.
So, as we can see, a combination of the hashCode()
and equals()
methods are used when storing and when looking up objects in a HashTable
.
NOTES:
Always use same attributes of an object to generate hashCode()
and equals()
both. As in our case, we have used employee id.
equals()
must be consistent (if the objects are not modified, then it must keep returning the same value).
Whenever a.equals(b)
, then a.hashCode()
must be same as b.hashCode()
.
If you override one, then you should override the other.
http://parameshk.blogspot.in/2014/10/examples-of-comparable-comporator.html
First thing to do is run this:
SHOW GRANTS;
You will quickly see you were assigned the anonymous user to authenticate into mysql.
Instead of logging into mysql with
mysql
login like this:
mysql -uroot
By default, root@localhost has all rights and no password.
If you cannot login as root without a password, do the following:
Step 01) Add the two options in the mysqld section of my.ini:
[mysqld]
skip-grant-tables
skip-networking
Step 02) Restart mysql
net stop mysql
<wait 10 seconds>
net start mysql
Step 03) Connect to mysql
mysql
Step 04) Create a password from root@localhost
UPDATE mysql.user SET password=password('whateverpasswordyoulike')
WHERE user='root' AND host='localhost';
exit
Step 05) Restart mysql
net stop mysql
<wait 10 seconds>
net start mysql
Step 06) Login as root with password
mysql -u root -p
You should be good from there.
Here are three Observables A
, B
, and C
with marble diagrams to explore the difference between first
, take
, and single
operators:
* Legend:
--o--
value
----!
error
----|
completion
Play with it at https://thinkrx.io/rxjs/first-vs-take-vs-single/ .
Already having all the answers, I wanted to add a more visual explanation
Hope it helps someone
your validation should be occur before your event suppose you are going to submit your form.
anyway if you want this on onchange, so here is code.
function valid(id)
{
var textVal=document.getElementById(id).value;
if (!textVal.match(/\S/))
{
alert("Field is blank");
return false;
}
else
{
return true;
}
}
It is the difference between greedy and non-greedy quantifiers.
Consider the input 101000000000100
.
Using 1.*1
, *
is greedy - it will match all the way to the end, and then backtrack until it can match 1
, leaving you with 1010000000001
.
.*?
is non-greedy. *
will match nothing, but then will try to match extra characters until it matches 1
, eventually matching 101
.
All quantifiers have a non-greedy mode: .*?
, .+?
, .{2,6}?
, and even .??
.
In your case, a similar pattern could be <([^>]*)>
- matching anything but a greater-than sign (strictly speaking, it matches zero or more characters other than >
in-between <
and >
).
"Stubbing-out a function means you'll write only enough to show that the function was called, leaving the details for later when you have more time."
From: SAMS Teach yourself C++, Jesse Liberty and Bradley Jones
Here is an example to fully programmatically:
I am using the following class vars:
Spinner varSpinner;
List<String> varSpinnerData;
float varScaleX;
float varScaleY;
A - Init and render the Spinner (varRoot is a pointer to my main Activity):
public void renderSpinner() {
List<String> myArraySpinner = new ArrayList<String>();
myArraySpinner.add("red");
myArraySpinner.add("green");
myArraySpinner.add("blue");
varSpinnerData = myArraySpinner;
Spinner mySpinner = new Spinner(varRoot);
varSpinner = mySpinner;
ArrayAdapter<String> spinnerArrayAdapter = new ArrayAdapter<String>(varRoot, android.R.layout.simple_spinner_item, myArraySpinner);
spinnerArrayAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); // The drop down vieww
mySpinner.setAdapter(spinnerArrayAdapter);
B - Resize and Add the Spinner to my View:
FrameLayout.LayoutParams myParamsLayout = new FrameLayout.LayoutParams(
FrameLayout.LayoutParams.MATCH_PARENT,
FrameLayout.LayoutParams.WRAP_CONTENT);
myParamsLayout.gravity = Gravity.NO_GRAVITY;
myParamsLayout.leftMargin = (int) (100 * varScaleX);
myParamsLayout.topMargin = (int) (350 * varScaleY);
myParamsLayout.width = (int) (300 * varScaleX);;
myParamsLayout.height = (int) (60 * varScaleY);;
varLayoutECommerce_Dialogue.addView(mySpinner, myParamsLayout);
C - Make the Click handler and use this to set the font.
mySpinner.setOnItemSelectedListener(new OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> parentView, View selectedItemView, int myPosition, long myID) {
Log.i("renderSpinner -> ", "onItemSelected: " + myPosition + "/" + myID);
((TextView) parentView.getChildAt(0)).setTextColor(Color.GREEN);
((TextView) parentView.getChildAt(0)).setTextSize(TypedValue.COMPLEX_UNIT_PX, (int) (varScaleY * 22.0f) );
((TextView) parentView.getChildAt(0)).setPadding(1,1,1,1);
}
@Override
public void onNothingSelected(AdapterView<?> parentView) {
// your code here
}
});
}
D - Update the Spinner with new data:
private void updateInitSpinners(){
String mySelected = varSpinner.getSelectedItem().toString();
Log.i("TPRenderECommerce_Dialogue -> ", "updateInitSpinners -> mySelected: " + mySelected);
varSpinnerData.clear();
varSpinnerData.add("Hello World");
varSpinnerData.add("Hello World 2");
((BaseAdapter) varSpinner.getAdapter()).notifyDataSetChanged();
varSpinner.invalidate();
varSpinner.setSelection(1);
}
}
What I have not been able to solve in the updateInitSpinners, is to do varSpinner.setSelection(0); and have the custom font settings activated automatically.
UPDATE:
This "ugly" solution solves the varSpinner.setSelection(0); issue, but I am not very happy with it:
private void updateInitSpinners(){
String mySelected = varSpinner.getSelectedItem().toString();
Log.i("TPRenderECommerce_Dialogue -> ", "updateInitSpinners -> mySelected: " + mySelected);
varSpinnerData.clear();
ArrayAdapter<String> spinnerArrayAdapter = new ArrayAdapter<String>(varRoot, android.R.layout.simple_spinner_item, varSpinnerData);
spinnerArrayAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
varSpinner.setAdapter(spinnerArrayAdapter);
varSpinnerData.add("Hello World");
varSpinnerData.add("Hello World 2");
((BaseAdapter) varSpinner.getAdapter()).notifyDataSetChanged();
varSpinner.invalidate();
varSpinner.setSelection(0);
}
}
Hope this helps......
You can do in this way also
var prop = $('.someProperty').closest('tr');
If the number of tr is in array
$.each(prop , function() {
var gotTD = $(this).find('td:eq(1)');
});
when all else fails I just
<center> content </center>
I know its not "up to standards" any more, but if it works it works
Just in case this helps, I solved this by checking the server date format:
SELECT * FROM nls_session_parameters WHERE parameter = 'NLS_DATE_FORMAT';
then by using the following comparison (the left field is a date+time):
AND EV_DTTM >= ('01-DEC-16')
I was trying this with TO_DATE
but kept getting an error. But when I matched my string with the NLS_DATE_FORMAT
and removed TO_DATE
, it worked...
this sample code loads the Japanese yield curve, and creates PCA components. It then estimates a given date's move using the PCA and compares it against the actual move.
%matplotlib inline
import numpy as np
import scipy as sc
from scipy import stats
from IPython.display import display, HTML
import pandas as pd
import matplotlib
import matplotlib.pyplot as plt
import datetime
from datetime import timedelta
import quandl as ql
start = "2016-10-04"
end = "2019-10-04"
ql_data = ql.get("MOFJ/INTEREST_RATE_JAPAN", start_date = start, end_date = end).sort_index(ascending= False)
eigVal_, eigVec_ = np.linalg.eig(((ql_data[:300]).diff(-1)*100).cov()) # take latest 300 data-rows and normalize to bp
print('number of PCA are', len(eigVal_))
loc_ = 10
plt.plot(eigVec_[:,0], label = 'PCA1')
plt.plot(eigVec_[:,1], label = 'PCA2')
plt.plot(eigVec_[:,2], label = 'PCA3')
plt.xticks(range(len(eigVec_[:,0])), ql_data.columns)
plt.legend()
plt.show()
x = ql_data.diff(-1).iloc[loc_].values * 100 # set the differences
x_ = x[:,np.newaxis]
a1, _, _, _ = np.linalg.lstsq(eigVec_[:,0][:, np.newaxis], x_) # linear regression without intercept
a2, _, _, _ = np.linalg.lstsq(eigVec_[:,1][:, np.newaxis], x_)
a3, _, _, _ = np.linalg.lstsq(eigVec_[:,2][:, np.newaxis], x_)
pca_mv = m1 * eigVec_[:,0] + m2 * eigVec_[:,1] + m3 * eigVec_[:,2] + c1 + c2 + c3
pca_MV = a1[0][0] * eigVec_[:,0] + a2[0][0] * eigVec_[:,1] + a3[0][0] * eigVec_[:,2]
pca_mV = b1 * eigVec_[:,0] + b2 * eigVec_[:,1] + b3 * eigVec_[:,2]
display(pd.DataFrame([eigVec_[:,0], eigVec_[:,1], eigVec_[:,2], x, pca_MV]))
print('PCA1 regression is', a1, a2, a3)
plt.plot(pca_MV)
plt.title('this is with regression and no intercept')
plt.plot(ql_data.diff(-1).iloc[loc_].values * 100, )
plt.title('this is with actual moves')
plt.show()
To achieve similar functionality you could use anonymous inner classes.
If you were to define a interface Foo
:
interface Foo {
Object myFunc(Object arg);
}
Create a method bar
which will receive a 'function pointer' as an argument:
public void bar(Foo foo) {
// .....
Object object = foo.myFunc(argValue);
// .....
}
Finally call the method as follows:
bar(new Foo() {
public Object myFunc(Object arg) {
// Function code.
}
}
def LongestEntry(lstName):
totalEntries = len(lstName)
currentEntry = 0
longestLength = 0
while currentEntry < totalEntries:
thisEntry = len(str(lstName[currentEntry]))
if int(thisEntry) > int(longestLength):
longestLength = thisEntry
longestEntry = currentEntry
currentEntry += 1
return longestLength
Take a look at Blaze-Persistence Entity Views which works on top of JPA and provides first class DTO support. You can project anything to attributes within Entity Views and it will even reuse existing join nodes for associations if possible.
Here is an example mapping
@EntityView(Order.class)
interface OrderSummary {
Integer getId();
@Mapping("SUM(orderPositions.price * orderPositions.amount * orderPositions.tax)")
BigDecimal getOrderAmount();
@Mapping("COUNT(orderPositions)")
Long getItemCount();
}
Fetching this will generate a JPQL/HQL query similar to this
SELECT
o.id,
SUM(p.price * p.amount * p.tax),
COUNT(p.id)
FROM
Order o
LEFT JOIN
o.orderPositions p
GROUP BY
o.id
Here is a blog post about custom subquery providers which might be interesting to you as well: https://blazebit.com/blog/2017/entity-view-mapping-subqueries.html
Have you considered applying ON DELETE CASCADE
where relevant?
To call POST/PUT/DELETE/GET Restful methods with custom header or json data the following Async class can be used
public class HttpUrlConnectionUtlity extends AsyncTask<Integer, Void, String> {
private static final String TAG = "HttpUrlConnectionUtlity";
Context mContext;
public static final int GET_METHOD = 0,
POST_METHOD = 1,
PUT_METHOD = 2,
HEAD_METHOD = 3,
DELETE_METHOD = 4,
TRACE_METHOD = 5,
OPTIONS_METHOD = 6;
HashMap<String, String> headerMap;
String entityString;
String url;
int requestType = -1;
final String timeOut = "TIMED_OUT";
int TIME_OUT = 60 * 1000;
public HttpUrlConnectionUtlity (Context mContext) {
this.mContext = mContext;
this.callback = callback;
}
@Override
protected void onPreExecute() {
super.onPreExecute();
}
@Override
protected String doInBackground(Integer... params) {
int requestType = getRequestType();
String response = "";
try {
URL url = getUrl();
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
urlConnection = setRequestMethod(urlConnection, requestType);
urlConnection.setConnectTimeout(TIME_OUT);
urlConnection.setReadTimeout(TIME_OUT);
urlConnection.setDoOutput(true);
urlConnection = setHeaderData(urlConnection);
urlConnection = setEntity(urlConnection);
if (urlConnection.getResponseCode() == HttpURLConnection.HTTP_OK) {
response = readResponseStream(urlConnection.getInputStream());
Logger.v(TAG, response);
}
urlConnection.disconnect();
return response;
} catch (ProtocolException e) {
e.printStackTrace();
} catch (SocketTimeoutException e) {
return timeOut;
} catch (IOException e) {
e.printStackTrace();
} catch (IllegalStateException e) {
Logger.e(TAG, "ALREADY CONNECTED");
}
return response;
}
@Override
protected void onPostExecute(String response) {
super.onPostExecute(response);
if (TextUtils.isEmpty(response)) {
//empty response
} else if (response != null && response.equals(timeOut)) {
//request timed out
} else {
//process your response
}
}
private String getEntityString() {
return entityString;
}
public void setEntityString(String s) {
this.entityString = s;
}
private String readResponseStream(InputStream in) {
BufferedReader reader = null;
StringBuffer response = new StringBuffer();
try {
reader = new BufferedReader(new InputStreamReader(in));
String line = "";
while ((line = reader.readLine()) != null) {
response.append(line);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return response.toString();
}
private HttpURLConnection setEntity(HttpURLConnection urlConnection) throws IOException {
if (getEntityString() != null) {
OutputStream outputStream = urlConnection.getOutputStream();
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(outputStream, "UTF-8"));
writer.write(getEntityString());
writer.flush();
writer.close();
outputStream.close();
} else {
Logger.w(TAG, "NO ENTITY DATA TO APPEND ||NO ENTITY DATA TO APPEND ||NO ENTITY DATA TO APPEND");
}
return urlConnection;
}
private HttpURLConnection setHeaderData(HttpURLConnection urlConnection) throws UnsupportedEncodingException {
urlConnection.setRequestProperty("Content-Type", "application/json");
urlConnection.setRequestProperty("Accept", "application/json");
if (getHeaderMap() != null) {
for (Map.Entry<String, String> entry : getHeaderMap().entrySet()) {
urlConnection.setRequestProperty(entry.getKey(), entry.getValue());
}
} else {
Logger.w(TAG, "NO HEADER DATA TO APPEND ||NO HEADER DATA TO APPEND ||NO HEADER DATA TO APPEND");
}
return urlConnection;
}
private HttpURLConnection setRequestMethod(HttpURLConnection urlConnection, int requestMethod) {
try {
switch (requestMethod) {
case GET_METHOD:
urlConnection.setRequestMethod("GET");
break;
case POST_METHOD:
urlConnection.setRequestMethod("POST");
break;
case PUT_METHOD:
urlConnection.setRequestMethod("PUT");
break;
case DELETE_METHOD:
urlConnection.setRequestMethod("DELETE");
break;
case OPTIONS_METHOD:
urlConnection.setRequestMethod("OPTIONS");
break;
case HEAD_METHOD:
urlConnection.setRequestMethod("HEAD");
break;
case TRACE_METHOD:
urlConnection.setRequestMethod("TRACE");
break;
}
} catch (ProtocolException e) {
e.printStackTrace();
}
return urlConnection;
}
public int getRequestType() {
return requestType;
}
public void setRequestType(int requestType) {
this.requestType = requestType;
}
public URL getUrl() throws MalformedURLException {
return new URL(url);
}
public void setUrl(String url) {
this.url = url;
}
public HashMap<String, String> getHeaderMap() {
return headerMap;
}
public void setHeaderMap(HashMap<String, String> headerMap) {
this.headerMap = headerMap;
} }
And The Usage is
HttpUrlConnectionUtlity httpMethod = new HttpUrlConnectionUtlity (mContext);
JSONObject jsonEntity = new JSONObject();
try {
jsonEntity.put("key1", value1);
jsonEntity.put("key2", value2);
} catch (JSONException e) {
e.printStackTrace();
}
httpMethod.setUrl(YOUR_URL_STRING);
HashMap<String, String> headerMap = new HashMap<>();
headerMap.put("key",value);
headerMap.put("key1",value1);
httpMethod.setHeaderMap(headerMap);
httpMethod.setRequestType(WiseConnectHttpMethod.POST_METHOD); //specify POST/GET/DELETE/PUT
httpMethod.setEntityString(jsonEntity.toString());
httpMethod.execute();
In your GET action, create an object of your view model, load the EmployeeList
collection property and send that to the view.
public IActionResult Create()
{
var vm = new MyViewModel();
vm.EmployeesList = new List<Employee>
{
new Employee { Id = 1, FullName = "Shyju" },
new Employee { Id = 2, FullName = "Bryan" }
};
return View(vm);
}
And in your create view, create a new SelectList
object from the EmployeeList
property and pass that as value for the asp-items
property.
@model MyViewModel
<form asp-controller="Home" asp-action="Create">
<select asp-for="EmployeeId"
asp-items="@(new SelectList(Model.EmployeesList,"Id","FullName"))">
<option>Please select one</option>
</select>
<input type="submit"/>
</form>
And your HttpPost action method to accept the submitted form data.
[HttpPost]
public IActionResult Create(MyViewModel model)
{
// check model.EmployeeId
// to do : Save and redirect
}
Or
If your view model has a List<SelectListItem>
as the property for your dropdown items.
public class MyViewModel
{
public int EmployeeId { get; set; }
public string Comments { get; set; }
public List<SelectListItem> Employees { set; get; }
}
And in your get action,
public IActionResult Create()
{
var vm = new MyViewModel();
vm.Employees = new List<SelectListItem>
{
new SelectListItem {Text = "Shyju", Value = "1"},
new SelectListItem {Text = "Sean", Value = "2"}
};
return View(vm);
}
And in the view, you can directly use the Employees
property for the asp-items
.
@model MyViewModel
<form asp-controller="Home" asp-action="Create">
<label>Comments</label>
<input type="text" asp-for="Comments"/>
<label>Lucky Employee</label>
<select asp-for="EmployeeId" asp-items="@Model.Employees" >
<option>Please select one</option>
</select>
<input type="submit"/>
</form>
The class SelectListItem
belongs to Microsoft.AspNet.Mvc.Rendering
namespace.
Make sure you are using an explicit closing tag for the select element. If you use the self closing tag approach, the tag helper will render an empty SELECT element!
The below approach will not work
<select asp-for="EmployeeId" asp-items="@Model.Employees" />
But this will work.
<select asp-for="EmployeeId" asp-items="@Model.Employees"></select>
The above examples are using hard coded items for the options. So i thought i will add some sample code to get data using Entity framework as a lot of people use that.
Let's assume your DbContext object has a property called Employees
, which is of type DbSet<Employee>
where the Employee
entity class has an Id
and Name
property like this
public class Employee
{
public int Id { set; get; }
public string Name { set; get; }
}
You can use a LINQ query to get the employees and use the Select method in your LINQ expression to create a list of SelectListItem
objects for each employee.
public IActionResult Create()
{
var vm = new MyViewModel();
vm.Employees = context.Employees
.Select(a => new SelectListItem() {
Value = a.Id.ToString(),
Text = a.Name
})
.ToList();
return View(vm);
}
Assuming context
is your db context object. The view code is same as above.
Some people prefer to use SelectList
class to hold the items needed to render the options.
public class MyViewModel
{
public int EmployeeId { get; set; }
public SelectList Employees { set; get; }
}
Now in your GET action, you can use the SelectList
constructor to populate the Employees
property of the view model. Make sure you are specifying the dataValueField
and dataTextField
parameters.
public IActionResult Create()
{
var vm = new MyViewModel();
vm.Employees = new SelectList(GetEmployees(),"Id","FirstName");
return View(vm);
}
public IEnumerable<Employee> GetEmployees()
{
// hard coded list for demo.
// You may replace with real data from database to create Employee objects
return new List<Employee>
{
new Employee { Id = 1, FirstName = "Shyju" },
new Employee { Id = 2, FirstName = "Bryan" }
};
}
Here I am calling the GetEmployees
method to get a list of Employee objects, each with an Id
and FirstName
property and I use those properties as DataValueField
and DataTextField
of the SelectList
object we created. You can change the hardcoded list to a code which reads data from a database table.
The view code will be same.
<select asp-for="EmployeeId" asp-items="@Model.Employees" >
<option>Please select one</option>
</select>
Sometimes you might want to render a select element from a list of strings. In that case, you can use the SelectList
constructor which only takes IEnumerable<T>
var vm = new MyViewModel();
var items = new List<string> {"Monday", "Tuesday", "Wednesday"};
vm.Employees = new SelectList(items);
return View(vm);
The view code will be same.
Some times,you might want to set one option as the default option in the SELECT element (For example, in an edit screen, you want to load the previously saved option value). To do that, you may simply set the EmployeeId
property value to the value of the option you want to be selected.
public IActionResult Create()
{
var vm = new MyViewModel();
vm.Employees = new List<SelectListItem>
{
new SelectListItem {Text = "Shyju", Value = "11"},
new SelectListItem {Text = "Tom", Value = "12"},
new SelectListItem {Text = "Jerry", Value = "13"}
};
vm.EmployeeId = 12; // Here you set the value
return View(vm);
}
This will select the option Tom in the select element when the page is rendered.
If you want to render a multi select dropdown, you can simply change your view model property which you use for asp-for
attribute in your view to an array type.
public class MyViewModel
{
public int[] EmployeeIds { get; set; }
public List<SelectListItem> Employees { set; get; }
}
This will render the HTML markup for the select element with the multiple
attribute which will allow the user to select multiple options.
@model MyViewModel
<select id="EmployeeIds" multiple="multiple" name="EmployeeIds">
<option>Please select one</option>
<option value="1">Shyju</option>
<option value="2">Sean</option>
</select>
Similar to single select, set the EmployeeIds
property value to the an array of values you want.
public IActionResult Create()
{
var vm = new MyViewModel();
vm.Employees = new List<SelectListItem>
{
new SelectListItem {Text = "Shyju", Value = "11"},
new SelectListItem {Text = "Tom", Value = "12"},
new SelectListItem {Text = "Jerry", Value = "13"}
};
vm.EmployeeIds= new int[] { 12,13} ;
return View(vm);
}
This will select the option Tom and Jerry in the multi select element when the page is rendered.
If you do not prefer to keep a collection type property to pass the list of options to the view, you can use the dynamic ViewBag to do so.(This is not my personally recommended approach as viewbag is dynamic and your code is prone to uncatched typo errors)
public IActionResult Create()
{
ViewBag.Employees = new List<SelectListItem>
{
new SelectListItem {Text = "Shyju", Value = "1"},
new SelectListItem {Text = "Sean", Value = "2"}
};
return View(new MyViewModel());
}
and in the view
<select asp-for="EmployeeId" asp-items="@ViewBag.Employees">
<option>Please select one</option>
</select>
It is same as above. All you have to do is, set the property (for which you are binding the dropdown for) value to the value of the option you want to be selected.
public IActionResult Create()
{
ViewBag.Employees = new List<SelectListItem>
{
new SelectListItem {Text = "Shyju", Value = "1"},
new SelectListItem {Text = "Bryan", Value = "2"},
new SelectListItem {Text = "Sean", Value = "3"}
};
vm.EmployeeId = 2; // This will set Bryan as selected
return View(new MyViewModel());
}
and in the view
<select asp-for="EmployeeId" asp-items="@ViewBag.Employees">
<option>Please select one</option>
</select>
The select tag helper method supports grouping options in a dropdown. All you have to do is, specify the Group
property value of each SelectListItem
in your action method.
public IActionResult Create()
{
var vm = new MyViewModel();
var group1 = new SelectListGroup { Name = "Dev Team" };
var group2 = new SelectListGroup { Name = "QA Team" };
var employeeList = new List<SelectListItem>()
{
new SelectListItem() { Value = "1", Text = "Shyju", Group = group1 },
new SelectListItem() { Value = "2", Text = "Bryan", Group = group1 },
new SelectListItem() { Value = "3", Text = "Kevin", Group = group2 },
new SelectListItem() { Value = "4", Text = "Alex", Group = group2 }
};
vm.Employees = employeeList;
return View(vm);
}
There is no change in the view code. the select tag helper will now render the options inside 2 optgroup items.
Is the image file ayrton_senna_movie_wallpaper_by_bashgfx-d4cm6x6.jpg in your static
directory? If you move it to your static directory and update your HTML as such:
<img src="/static/ayrton_senna_movie_wallpaper_by_bashgfx-d4cm6x6.jpg">
It should work.
Also, it is worth noting, there is a better way to structure this.
File structure:
app.py
static
|----ayrton_senna_movie_wallpaper_by_bashgfx-d4cm6x6.jpg
templates
|----index.html
app.py
from flask import Flask, render_template, url_for
app = Flask(__name__)
@app.route('/index', methods=['GET', 'POST'])
def lionel():
return render_template('index.html')
if __name__ == '__main__':
app.run()
templates/index.html
<html>
<head>
</head>
<body>
<h1>Hi Lionel Messi</h1>
<img src="{{url_for('static', filename='ayrton_senna_movie_wallpaper_by_bashgfx-d4cm6x6.jpg')}}" />
</body>
</html>
Doing it this way ensures that you are not hard-coding a URL path for your static assets.
Use MethodInvoker for updating label text in other thread.
private void AggiornaContatore()
{
MethodInvoker inv = delegate
{
this.lblCounter.Text = this.index.ToString();
}
this.Invoke(inv);
}
You are getting the error because your UI thread is holding the label, and since you are trying to update it through another thread you are getting cross thread exception.
You may also see: Threading in Windows Forms
Try to reinstall:
localess apt-get install --reinstall locales
Read more in How to change the default locale
Here is the step by step process to include php code in html file ( Tested )
If PHP is working there is only one step left to use PHP scripts in files with *.html or *.htm extensions as well. The magic word is ".htaccess". Please see the Wikipedia definition of .htaccess to learn more about it. According to Wikipedia it is "a directory-level configuration file that allows for decentralized management of web server configuration."
You can probably use such a .htaccess configuration file for your purpose. In our case you want the webserver to parse HTML files like PHP files.
First, create a blank text file and name it ".htaccess". You might ask yourself why the file name starts with a dot. On Unix-like systems this means it is a dot-file is a hidden file. (Note: If your operating system does not allow file names starting with a dot just name the file "xyz.htaccess" temporarily. As soon as you have uploaded it to your webserver in a later step you can rename the file online to ".htaccess") Next, open the file with a simple text editor like the "Editor" in MS Windows. Paste the following line into the file: AddType application/x-httpd-php .html .htm If this does not work, please remove the line above from your file and paste this alternative line into it, for PHP5: AddType application/x-httpd-php5 .html .htm Now upload the .htaccess file to the root directory of your webserver. Make sure that the name of the file is ".htaccess". Your webserver should now parse *.htm and *.html files like PHP files.
You can try if it works by creating a HTML-File like the following. Name it "php-in-html-test.htm", paste the following code into it and upload it to the root directory of your webserver:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<HTML>
<HEAD>
<TITLE>Use PHP in HTML files</TITLE>
</HEAD>
<BODY>
<h1>
<?php echo "It works!"; ?>
</h1>
</BODY>
</HTML>
Try to open the file in your browser by typing in: http://www.your-domain.com/php-in-html-test.htm (once again, please replace your-domain.com by your own domain...) If your browser shows the phrase "It works!" everything works fine and you can use PHP in .*html and *.htm files from now on. However, if not, please try to use the alternative line in the .htaccess file as we showed above. If is still does not work please contact your hosting provider.
To fill a list with seperate instances of a class, you can use a for loop in the declaration of the list. The * multiply will link each copy to the same instance.
instancelist = [ MyClass() for i in range(29)]
and then access the instances through the index of the list.
instancelist[5].attr1 = 'whamma'
-split outputs an array, and you can save it to a variable like this:
$a = -split 'Once upon a time'
$a[0]
Once
Another cute thing, you can have arrays on both sides of an assignment statement:
$a,$b,$c = -split 'Once upon a'
$c
a
how to club the 4 query's as a single query
show below query
nsc = nature of case
report is taken on 06th of every month
( monthly report will be counted from 05th previous month to 05th present of present month)
The top-voted answer will probably be enough for most people. However, in some circumstances, you could continue getting a "Could not create SSL/TLS secure channel" error even after forcing TLS 1.2. If so, you may want to consult this helpful article for additional troubleshooting steps. To summarize: independent of the TLS/SSL version issue, the client and server must agree on a "cipher suite." During the "handshake" phase of the SSL connection, the client will list its supported cipher-suites for the server to check against its own list. But on some Windows machines, certain common cipher-suites may have been disabled (seemingly due to well-intentioned attempts to limit attack surface), decreasing the possibility of the client & server agreeing on a cipher suite. If they cannot agree, then you may see "fatal alert code 40" in the event viewer and "Could not create SSL/TLS secure channel" in your .NET program.
The aforementioned article explains how to list all of a machine's potentially-supported cipher suites and enable additional cipher suites through the Windows Registry. To help check which cipher suites are enabled on the client, try visiting this diagnostic page in MSIE. (Using System.Net tracing may give more definitive results.) To check which cipher suites are supported by the server, try this online tool (assuming that the server is Internet-accessible). It should go without saying that Registry edits must be done with caution, especially where networking is involved. (Is your machine a remote-hosted VM? If you were to break networking, would the VM be accessible at all?)
In my company's case, we enabled several additional "ECDHE_ECDSA" suites via Registry edit, to fix an immediate problem and guard against future problems. But if you cannot (or will not) edit the Registry, then numerous workarounds (not necessarily pretty) come to mind. For example: your .NET program could delegate its SSL traffic to a separate Python program (which may itself work, for the same reason that Chrome requests may succeed where MSIE requests fail on an affected machine).
Assuming you're wanting to undo the effects of git rm <file>
or rm <file>
followed by git add -A
or something similar:
# this restores the file status in the index
git reset -- <file>
# then check out a copy from the index
git checkout -- <file>
To undo git add <file>
, the first line above suffices, assuming you haven't committed yet.
pip show <package name>
will provide the location for Windows and macOS, and I'm guessing any system. :)
For example:
> pip show cvxopt
Name: cvxopt
Version: 1.2.0
...
Location: /usr/local/lib/python2.7/site-packages
There is a built in function to compare lists:
Following is the syntax for cmp() method -
cmp(list1, list2)
#!/usr/bin/python
list1, list2 = [123, 'xyz'], [123, 'xyz']
print cmp(list1,list2)
When we run above program, it produces following result -
0
If the result is a tie, meaning that 0 is returned
1) "container" is a class and not an ID 2) .container - set z-index and display: none in your CSS and not inline unless there is a really good reason to do so. Demo@fiddle
$("#button").click(function() {
$(".container").css("opacity", 0.2);
$("#loading-img").css({"display": "block"});
});
CSS:
#loading-img {
background: url(http://web.bogdanteodoru.com/wp-content/uploads/2012/01/bouncy-css3-loading-animation.jpg) center center no-repeat; /* different for testing purposes */
display: none;
height: 100px; /* for testing purposes */
z-index: 12;
}
And a demo with animated image.
It's also useful to have a slightly different name for the output executable. You can't use something like:
release: Target = ProgramName
debug: Target = ProgramName_d
Why it doesn't work is not clear, but it does not. But:
CONFIG(debug, debug|release) {
TARGET = ProgramName
} else {
TARGET = ProgramName_d
}
This does work as long as the CONFIG +=
line precedes it.
You can do this with jQuery. Using their selectors, you can select by attributes, such as type. This does, however, require that your users have Javascript turned on, and an additional file to download, but if it works...
Excel only shows 255 characters but in fact if more than 255 characters are saved, to see the complete string, consult it in the immediate window
Press Crl + G and type ?RunWhat
in the immediate window and press Enter
Simply delete your local master branch and recreate it like so:
git branch -D master
git checkout origin/master -b master
I tried the following:
Check if it works the same with you.
You can use
<li ng-repeat="(name, age) in items">{{name}}: {{age}}</li>
See ngRepeat documentation. Example: http://jsfiddle.net/WRtqV/1/
Although the following is not way to do it in GUI but you can get autoincrementing simply using the IDENTITY datatype(start, increment):
CREATE TABLE "dbo"."TableName"
(
id int IDENTITY(1,1) PRIMARY KEY NOT NULL,
name varchar(20),
);
the insert statement should list all columns except the id column (it will be filled with autoincremented value):
INSERT INTO "dbo"."TableName" (name) VALUES ('alpha');
INSERT INTO "dbo"."TableName" (name) VALUES ('beta');
and the result of
SELECT id, name FROM "dbo"."TableName";
will be
id name
--------------------------
1 alpha
2 beta
Here is the solution in raw code (put together thanks to stjohnroe and Shamik):
Endpoint ep = Endpoint.create(new WebserviceImpl());
List<Handler> handlerChain = ep.getBinding().getHandlerChain();
handlerChain.add(new SOAPLoggingHandler());
ep.getBinding().setHandlerChain(handlerChain);
ep.publish(publishURL);
Where SOAPLoggingHandler is (ripped from linked examples):
package com.myfirm.util.logging.ws;
import java.io.PrintStream;
import java.util.Map;
import java.util.Set;
import javax.xml.namespace.QName;
import javax.xml.soap.SOAPMessage;
import javax.xml.ws.handler.MessageContext;
import javax.xml.ws.handler.soap.SOAPHandler;
import javax.xml.ws.handler.soap.SOAPMessageContext;
/*
* This simple SOAPHandler will output the contents of incoming
* and outgoing messages.
*/
public class SOAPLoggingHandler implements SOAPHandler<SOAPMessageContext> {
// change this to redirect output if desired
private static PrintStream out = System.out;
public Set<QName> getHeaders() {
return null;
}
public boolean handleMessage(SOAPMessageContext smc) {
logToSystemOut(smc);
return true;
}
public boolean handleFault(SOAPMessageContext smc) {
logToSystemOut(smc);
return true;
}
// nothing to clean up
public void close(MessageContext messageContext) {
}
/*
* Check the MESSAGE_OUTBOUND_PROPERTY in the context
* to see if this is an outgoing or incoming message.
* Write a brief message to the print stream and
* output the message. The writeTo() method can throw
* SOAPException or IOException
*/
private void logToSystemOut(SOAPMessageContext smc) {
Boolean outboundProperty = (Boolean)
smc.get (MessageContext.MESSAGE_OUTBOUND_PROPERTY);
if (outboundProperty.booleanValue()) {
out.println("\nOutbound message:");
} else {
out.println("\nInbound message:");
}
SOAPMessage message = smc.getMessage();
try {
message.writeTo(out);
out.println(""); // just to add a newline
} catch (Exception e) {
out.println("Exception in handler: " + e);
}
}
}
You can see Hive MetaStore tables,Partitions information in table of "PARTITIONS". You could use "TBLS" join "Partition" to query special table partitions.
This is how to retrieve a Column Name from a DataColumn:
MyDataTable.Columns(1).ColumnName
To get the name of all DataColumns within your DataTable:
Dim name(DT.Columns.Count) As String
Dim i As Integer = 0
For Each column As DataColumn In DT.Columns
name(i) = column.ColumnName
i += 1
Next
References
Whilst you certainly can use MySQL's IF()
control flow function as demonstrated by dbemerlin's answer, I suspect it might be a little clearer to the reader (i.e. yourself, and any future developers who might pick up your code in the future) to use a CASE
expression instead:
UPDATE Table
SET A = CASE
WHEN A > 0 AND A < 1 THEN 1
WHEN A > 1 AND A < 2 THEN 2
ELSE A
END
WHERE A IS NOT NULL
Of course, in this specific example it's a little wasteful to set A
to itself in the ELSE
clause—better entirely to filter such conditions from the UPDATE
, via the WHERE
clause:
UPDATE Table
SET A = CASE
WHEN A > 0 AND A < 1 THEN 1
WHEN A > 1 AND A < 2 THEN 2
END
WHERE (A > 0 AND A < 1) OR (A > 1 AND A < 2)
(The inequalities entail A IS NOT NULL
).
Or, if you want the intervals to be closed rather than open (note that this would set values of 0
to 1
—if that is undesirable, one could explicitly filter such cases in the WHERE
clause, or else add a higher precedence WHEN
condition):
UPDATE Table
SET A = CASE
WHEN A BETWEEN 0 AND 1 THEN 1
WHEN A BETWEEN 1 AND 2 THEN 2
END
WHERE A BETWEEN 0 AND 2
Though, as dbmerlin also pointed out, for this specific situation you could consider using CEIL()
instead:
UPDATE Table SET A = CEIL(A) WHERE A BETWEEN 0 AND 2
Expanding on Jaime Cham's answer I created a NSObject+Blocks category as below. I felt these methods better matched the existing performSelector:
NSObject methods
NSObject+Blocks.h
#import <Foundation/Foundation.h>
@interface NSObject (Blocks)
- (void)performBlock:(void (^)())block afterDelay:(NSTimeInterval)delay;
@end
NSObject+Blocks.m
#import "NSObject+Blocks.h"
@implementation NSObject (Blocks)
- (void)performBlock:(void (^)())block
{
block();
}
- (void)performBlock:(void (^)())block afterDelay:(NSTimeInterval)delay
{
void (^block_)() = [block copy]; // autorelease this if you're not using ARC
[self performSelector:@selector(performBlock:) withObject:block_ afterDelay:delay];
}
@end
and use like so:
[anyObject performBlock:^{
[anotherObject doYourThings:stuff];
} afterDelay:0.15];
Macros in Notepad++ are just a bunch of encoded operations: you start recording, operate on the buffer, perhaps activating menus, stop recording then play the macro.
After investigation, I found out they are saved in the file shortcuts.xml in the Macros section. For example, I have there:
<Macro name="Trim Trailing and save" Ctrl="no" Alt="yes" Shift="yes" Key="83">
<Action type="1" message="2170" wParam="0" lParam="0" sParam=" " />
<Action type="1" message="2170" wParam="0" lParam="0" sParam=" " />
<Action type="1" message="2170" wParam="0" lParam="0" sParam=" " />
<Action type="0" message="2327" wParam="0" lParam="0" sParam="" />
<Action type="0" message="2327" wParam="0" lParam="0" sParam="" />
<Action type="2" message="0" wParam="42024" lParam="0" sParam="" />
<Action type="2" message="0" wParam="41006" lParam="0" sParam="" />
</Macro>
I haven't looked at the source, but from the look, I would say we have messages sent to Scintilla (the editing component, perhaps type 0 and 1), and to Notepad++ itself (probably activating menu items).
I don't think it will record actions in dialogs (like search/replace).
Looking at Scintilla.iface file, we can see that 2170 is the code of ReplaceSel (ie. insert string is nothing is selected), 2327 is Tab command, and Resource Hacker (just have it handy...) shows that 42024 is "Trim Trailing Space" menu item and 41006 is "Save".
I guess action type 0 is for Scintilla commands with numerical params, type 1 is for commands with string parameter, 2 is for Notepad++ commands.
Problem: Scintilla doesn't have a "Replace all" command: it is the task of the client to do the iteration, with or without confirmation, etc.
Another problem: it seems type 1 action is limited to 1 char (I edited manually, when exiting N++ it was truncated).
I tried some tricks, but I fear such task is beyond the macro capabilities.
Maybe that's where SciTE with its Lua scripting ability (or Programmer's Notepad which seems to be scriptable with Python) has an edge... :-)
[EDIT] Looks like I got the above macro from this thread or a similar place... :-) I guess the first lines are unnecessary (side effect or recording) but they were good examples of macro code anyway.
you can try quoting it which will keep the link as text. see the code blocks section: https://get.slack.help/hc/en-us/articles/202288908-Format-your-messages#code-blocks
One way to find out:
sudo /usr/libexec/locate.updatedb
# wait a few minutes for it to finish
locate my.cnf
You have too many redundant nested arrays inside your jSON data, but it is possible to retrieve the information. Though like others have said you might want to clean it up.
use each() wrap within another each() until the last array.
for result.data[0].stuff[0].onetype[0]
in jQuery you could do the following:
`
$.each(data.result.data, function(index0, v) {
$.each(v, function (index1, w) {
$.each(w, function (index2, x) {
alert(x.id);
});
});
});
`
Another option is, instead of floating, to set the white-space property nowrap to a parent div:
.parent {
white-space: nowrap;
}
and reset the white-space and use an inline-block display so the divs stay on the same line but you can still give it a width.
.child {
display:inline-block;
width:300px;
white-space: normal;
}
Here is a JSFiddle: https://jsfiddle.net/9g8ud31o/
I Solved this problem adding @Cascade to the @ManyToOne attribute.
import org.hibernate.annotations.Cascade;
import org.hibernate.annotations.CascadeType;
@ManyToOne
@JoinColumn(name="BLOODGRUPID")
@Cascade({CascadeType.MERGE, CascadeType.SAVE_UPDATE})
private Bloodgroup bloodgroup;
You could use jQuery and an Ajax call to post the specific update back to your server with Javascript.
It would look something like this:
function updatePostID(val, comment)
{
var args = {};
args.PostID = val;
args.Comment = comment;
$.ajax({
type: "POST",
url: controllerActionMethodUrlHere,
contentType: "application/json; charset=utf-8",
data: args,
dataType: "json",
success: function(msg)
{
// Something afterwards here
}
});
}
It seems that linux will say "command not found" even if you explicitly give the path to the file.
[veeam@jsandbox ~]$ sudo /tmp/uid.sh;echo $?
sudo: /tmp/uid.sh: command not found
1
[veeam@jsandbox ~]$ chmod +x /tmp/uid.sh
[veeam@jsandbox ~]$ sudo /tmp/uid.sh;echo $?
0
It's a somewhat misleading error, however it's probably technically correct. A file is not a command until its executable, and so cannot be found.
Everything here was failing as wrong path. Then I remembered a trick from the old Win95 days. Open the program folder where the .dll resides, open C:/Windows/System32 scroll down to regsvr32 and drag and drop the dll from the program folder onto rgsrver32. Boom,done.
If you have to write static methods in ES5 I found a great tutorial for that:
//Constructor
var Person = function (name, age){
//private properties
var priv = {};
//Public properties
this.name = name;
this.age = age;
//Public methods
this.sayHi = function(){
alert('hello');
}
}
// A static method; this method only
// exists on the class and doesn't exist
// on child objects
Person.sayName = function() {
alert("I am a Person object ;)");
};
see @https://abdulapopoola.com/2013/03/30/static-and-instance-methods-in-javascript/
I am a little late for the show but in case the above answer didn't solve the query then I found another way. Simply remove the specific large file from .pack. I had this issue where I checked in a large 2GB file accidentally. I followed the steps explained in this link: http://www.ducea.com/2012/02/07/howto-completely-remove-a-file-from-git-history/
As for me, curly braces serve as a substitution for concatenation, they are quicker to type and code looks cleaner. Remember to use double quotes (" ") as their content is parsed by PHP, because in single quotes (' ') you'll get the literal name of variable provided:
<?php
$a = '12345';
// This works:
echo "qwe{$a}rty"; // qwe12345rty, using braces
echo "qwe" . $a . "rty"; // qwe12345rty, concatenation used
// Does not work:
echo 'qwe{$a}rty'; // qwe{$a}rty, single quotes are not parsed
echo "qwe$arty"; // qwe, because $a became $arty, which is undefined
?>
CODE:
import codecs
path="D:\\Users\\html\\abc.html"
file=codecs.open(path,"rb")
file1=file.read()
file1=str(file1)
The problem is that the command gets run under sudo
, but the redirection gets run under your user. This is done by the shell and there is very little you can do about it.
sudo command > /some/file.log
`-----v-----'`-------v-------'
command redirection
The usual ways of bypassing this are:
Wrap the commands in a script which you call under sudo.
If the commands and/or log file changes, you can make the script take these as arguments. For example:
sudo log_script command /log/file.txt
Call a shell and pass the command line as a parameter with -c
This is especially useful for one off compound commands. For example:
sudo bash -c "{ command1 arg; command2 arg; } > /log/file.txt"
Converting the date without specifying the current format can bring this error to you easily.
sdate <- "2015.10.10"
date <- as.Date(sdate4) # ==> This will generate the same error"""Error in charToDate(x): character string is not in a standard unambiguous format""".
date <- as.Date(sdate4, format = "%Y.%m.%d") # ==> Error Free Date Conversion.
In this case, there can be use ScrollView and added to TextField
in ScrollView and I want Tap the ScrollView
and View then Dismiss the Keyboard. I tried to create sample code just in case. Like this,
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var scrollView: UIScrollView!
@IBOutlet weak var textField: UITextField!
override func viewDidLoad() {
super.viewDidLoad()
let tapGesture = UITapGestureRecognizer(target: self, action: #selector(ViewController.tap(_:)))
view.addGestureRecognizer(tapGesture)
// Do any additional setup after loading the view, typically from a nib.
}
func tap(gesture: UITapGestureRecognizer) {
textField.resignFirstResponder()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
Your Storyboard Look at that Just Like.
Another option is to use showtext
package which supports more types of fonts (TrueType, OpenType, Type 1, web fonts, etc.) and more graphics devices, and avoids using external software such as Ghostscript.
# install.packages('showtext', dependencies = TRUE)
library(showtext)
Import some Google Fonts
# https://fonts.google.com/featured/Superfamilies
font_add_google("Montserrat", "Montserrat")
font_add_google("Roboto", "Roboto")
Load font from the current search path into showtext
# Check the current search path for fonts
font_paths()
#> [1] "C:\\Windows\\Fonts"
# List available font files in the search path
font_files()
#> [1] "AcadEref.ttf"
#> [2] "AGENCYB.TTF"
#> [428] "pala.ttf"
#> [429] "palab.ttf"
#> [430] "palabi.ttf"
#> [431] "palai.ttf"
# syntax: font_add(family = "<family_name>", regular = "/path/to/font/file")
font_add("Palatino", "pala.ttf")
font_families()
#> [1] "sans" "serif" "mono" "wqy-microhei"
#> [5] "Montserrat" "Roboto" "Palatino"
## automatically use showtext for new devices
showtext_auto()
Plot: need to open Windows graphics device as showtext
does not work well with RStudio built-in graphics device
# https://github.com/yixuan/showtext/issues/7
# https://journal.r-project.org/archive/2015-1/qiu.pdf
# `x11()` on Linux, or `quartz()` on Mac OS
windows()
myFont1 <- "Montserrat"
myFont2 <- "Roboto"
myFont3 <- "Palatino"
library(ggplot2)
a <- ggplot(mtcars, aes(x = wt, y = mpg)) +
geom_point() +
ggtitle("Fuel Efficiency of 32 Cars") +
xlab("Weight (x1000 lb)") + ylab("Miles per Gallon") +
theme(text = element_text(size = 16, family = myFont1)) +
annotate("text", 4, 30, label = 'Palatino Linotype',
family = myFont3, size = 10) +
annotate("text", 1, 11, label = 'Roboto', hjust = 0,
family = myFont2, size = 10)
## On-screen device
print(a)
## Save to PNG
ggsave("plot_showtext.png", plot = a,
type = 'cairo',
width = 6, height = 6, dpi = 150)
## Save to PDF
ggsave("plot_showtext.pdf", plot = a,
device = cairo_pdf,
width = 6, height = 6, dpi = 150)
## turn showtext off if no longer needed
showtext_auto(FALSE)
Edit: another workaround to use showtext
in RStudio. Run the following code at the beginning of the R session (source)
trace(grDevices::png, exit = quote({
showtext::showtext_begin()
}), print = FALSE)
Code below does not print boolean, but allows for dataframe subsetting by index... I understand this is likely not the most efficient way to solve the problem, but I (1) like the way this reads and (2) you can easily subset where df1 index exists in df2:
df3 = df1[df1.index.isin(df2.index)]
or where df1 index does not exist in df2...
df3 = df1[~df1.index.isin(df2.index)]
This VB.Net version works for my situation. I removed thread collection semaphore, instead using RemoveHandler and AddHandler. Also, since a FlowDocument can only be bound to one RichTextBox at a time, I put in a check that the RichTextBox's IsLoaded=True. Let's begin with how I used the class in a MVVM app which uses ResourceDictionary instead of Window.
' Loaded and Unloaded events seems to be the only way to initialize a control created from a Resource Dictionary
' Loading document here because Loaded is the last available event to create a document
Private Sub Rtb_Loaded(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs)
' only good place to initialize RichTextBox.Document with DependencyProperty
Dim rtb As RichTextBox = DirectCast(sender, RichTextBox)
Try
rtb.Document = RichTextBoxHelper.GetDocumentXaml(rtb)
Catch ex As Exception
Debug.WriteLine("Rtb_Loaded: Message:" & ex.Message)
End Try
End Sub
' Loaded and Unloaded events seems to be the only way to initialize a control created from a Resource Dictionary
' Free document being held by RichTextBox.Document by assigning New FlowDocument to RichTextBox.Document. Otherwise we'll see an of "Document belongs to another RichTextBox"
Private Sub Rtb_Unloaded(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs)
Dim rtb As RichTextBox = DirectCast(sender, RichTextBox)
Dim fd As New FlowDocument
RichTextBoxHelper.SetDocumentXaml(rtb, fd)
Try
rtb.Document = fd
Catch ex As Exception
Debug.WriteLine("PoemDocument.PoemDocumentView.PoemRtb_Unloaded: Message:" & ex.Message)
End Try
End Sub
Public Class RichTextBoxHelper
Inherits DependencyObject
Public Shared Function GetDocumentXaml(ByVal depObj As DependencyObject) As FlowDocument
Return depObj.GetValue(DocumentXamlProperty)
End Function
Public Shared Sub SetDocumentXaml(ByVal depObj As DependencyObject, ByVal value As FlowDocument)
depObj.SetValue(DocumentXamlProperty, value)
End Sub
Public Shared ReadOnly DocumentXamlProperty As DependencyProperty = DependencyProperty.RegisterAttached("DocumentXaml", GetType(FlowDocument), GetType(RichTextBoxHelper), New FrameworkPropertyMetadata(Nothing, FrameworkPropertyMetadataOptions.AffectsRender Or FrameworkPropertyMetadataOptions.BindsTwoWayByDefault, Sub(depObj, e)
RegisterIt(depObj, e)
End Sub))
Private Shared Sub RegisterIt(ByVal depObj As System.Windows.DependencyObject, ByVal e As System.Windows.DependencyPropertyChangedEventArgs)
Dim rtb As RichTextBox = DirectCast(depObj, RichTextBox)
If rtb.IsLoaded Then
RemoveHandler rtb.TextChanged, AddressOf TextChanged
Try
rtb.Document = GetDocumentXaml(rtb)
Catch ex As Exception
Debug.WriteLine("RichTextBoxHelper.RegisterIt: ex:" & ex.Message)
rtb.Document = New FlowDocument()
End Try
AddHandler rtb.TextChanged, AddressOf TextChanged
Else
Debug.WriteLine("RichTextBoxHelper: Unloaded control ignored:" & rtb.Name)
End If
End Sub
' When a RichTextBox Document changes, update the DependencyProperty so they're in sync.
Private Shared Sub TextChanged(ByVal sender As Object, ByVal e As TextChangedEventArgs)
Dim rtb As RichTextBox = TryCast(sender, RichTextBox)
If rtb IsNot Nothing Then
SetDocumentXaml(sender, rtb.Document)
End If
End Sub
End Class
To avoid using curl or Chrome plugins you can just use the the built in windows Powershell. From the Powershell command window run
Invoke-WebRequest -UseBasicParsing "http://127.0.0.1:9200/sampleindex/sampleType/" -
Method POST -ContentType "application/json" -Body '{
"user" : "Test",
"post_date" : "2017/11/13 11:07:00",
"message" : "trying out Elasticsearch"
}'
Note the Index name MUST be in lowercase.
Every process running under the Linux kernel receives its own, unique environment that it inherits from its parent. In this case, the parent will be either a shell itself (spawning a sub shell), or the 'login' program (on a typical system).
As each process' environment is protected, there is no way to 'inject' an environmental variable to every running process, so even if you modify the default shell .rc / profile, it won't go into effect until each process exits and reloads its start up settings.
Look in /etc/ to modify the default start up variables for any particular shell. Just realize that users can (and often do) change them in their individual settings.
Unix is designed to obey the user, within limits.
NB: Bash is not the only shell on your system. Pay careful attention to what the /bin/sh symbolic link actually points to. On many systems, this could actually be dash which is (by default, with no special invocation) POSIXLY correct. Therefore, you should take care to modify both defaults, or scripts that start with /bin/sh will not inherit your global defaults. Similarly, take care to avoid syntax that only bash understands when editing both, aka avoiding bashisms
.
The following ways work.
// The old way of using ParameterizedThreadStart. This requires a
// method which takes ONE object as the parameter so you need to
// encapsulate the parameters inside one object.
Thread t = new Thread(new ParameterizedThreadStart(StartupA));
t.Start(new MyThreadParams(path, port));
// You can also use an anonymous delegate to do this.
Thread t2 = new Thread(delegate()
{
StartupB(port, path);
});
t2.Start();
// Or lambda expressions if you are using C# 3.0
Thread t3 = new Thread(() => StartupB(port, path));
t3.Start();
The Startup methods have following signature for these examples.
public void StartupA(object parameters);
public void StartupB(int port, string path);
I know this question is old -- but here's another, extremely simple solution ...
var elements = Array.from(document.querySelectorAll("div"));
Then it can be used like any, standard array.
//here is how to do it in Windows App.Config
public static bool ChangeConnectionString(string Name, string value, string providerName, string AppName)
{
bool retVal = false;
try
{
string FILE_NAME = string.Concat(Application.StartupPath, "\\", AppName.Trim(), ".exe.Config"); //the application configuration file name
XmlTextReader reader = new XmlTextReader(FILE_NAME);
XmlDocument doc = new XmlDocument();
doc.Load(reader);
reader.Close();
string nodeRoute = string.Concat("connectionStrings/add");
XmlNode cnnStr = null;
XmlElement root = doc.DocumentElement;
XmlNodeList Settings = root.SelectNodes(nodeRoute);
for (int i = 0; i < Settings.Count; i++)
{
cnnStr = Settings[i];
if (cnnStr.Attributes["name"].Value.Equals(Name))
break;
cnnStr = null;
}
cnnStr.Attributes["connectionString"].Value = value;
cnnStr.Attributes["providerName"].Value = providerName;
doc.Save(FILE_NAME);
retVal = true;
}
catch (Exception ex)
{
retVal = false;
//Handle the Exception as you like
}
return retVal;
}
Okay, with a little HTML in your R code, I did the following code to generate pure text in R Markdown. The <h3 style="text-indent: 15em;">
indents the text 15 spaces. For the original question, change the 15 to 6.
## Option: Du Pont Ratio Concept - (ROE Decomposition)
### (Closed Quotes/Total Premium) = (Closed Quotes/Quotes Issued) X <br>
<h3 style="text-indent: 15em;">
(Quotes Issued/Renewal Premium) X <br></h3>
<h3 style="text-indent: 15em;">
(Renewal Premium/Total Premium)</h3>
So the resulting code gives my desired output format. I am using tabs for the Markdown document and was looking to line up the () text which worked.
Use .push:
items.push({'id':5});
This works for csv and all files containing strings in Unix-based OSes:
import os
numOfLines = int(os.popen('wc -l < file.csv').read()[:-1])
In case the csv file contains a fields row you can deduct one from numOfLines
above:
numOfLines = numOfLines - 1
in my case: make sure not exist any form element in your page other than top main form, this cause events not fired
You can perform bulk insert using mongoDB shell using inserting the values in an array.
db.collection.insert([{values},{values},{values},{values}]);
You can try this way:
open('u.item', encoding='utf8', errors='ignore')
You must create them under strings.xml
<string name="close">Close</string>
You must replace and reference like this
android:text="@string/close"/>
Do not use @strings even though the XML file says strings.xml or else it will not work.
As mentioned you need to use obj.getTile()
But, in this case I think you are looking to use a Property.
public class Pin
{
private string title;
public Pin() { }
public setTitle(string title) {
this.title = title;
}
public String Title
{
get { return title; }
}
}
This will allow you to use
foreach (Pin obj in ClassListPin.pins)
{
string t = obj.Title;
}
This will work. Link to your SVG using the following pattern:
https://cdn.rawgit.com/<repo-owner>/<repo>/<branch>/path/to.svg
The downside is hardcoding the owner and repo in the path, meaning the svg will break if either of those are renamed.
You can check for yourself.
In this fiddle, I ran a test to demonstrate the blocking nature of await
, as opposed to Promise.all
which will start all of the promises and while one is waiting it will go on with the others.
The html_safe version works well in Rails 4...
<%= "<center style=\"color: green; font-size: 1.1em\" > Administrators only </center>".html_safe if current_user.admin? %
>
Open a new worksheet on the related instance (Alt-F10)
and run the following query
SELECT view_name, owner
FROM sys.all_views
ORDER BY owner, view_name
Should be something similar to:
//a[text()='text_i_want_to_find']/@href
Try this
Go to the properties
of the shortcut that points to the program (ALT ENTER or right
click
->properties
); if there is no shortcut to it, you can make it by dragging and dropping the program while holding CTRL SHIFT;
Click in the Normal window
dropdown, and choose minimized
;
Save and run the shortcut.
You can also do:
(from u in table
orderby u.Status descending
select u).Take(1);
Using reshape2
and dplyr
. Your data:
df <- read.table(text=
"tea coke beer water gender
14.55 26.50793651 22.53968254 40 1
24.92997199 24.50980392 26.05042017 24.50980393 2
23.03732304 30.63063063 25.41827542 20.91377091 1
225.51781276 24.6064623 24.85501243 50.80645161 1
24.53662842 26.03706973 25.24271845 24.18358341 2", header=TRUE)
Getting data into correct form:
library(reshape2)
library(dplyr)
df.melt <- melt(df, id="gender")
bar <- group_by(df.melt, variable, gender)%.%summarise(mean=mean(value))
Plotting:
library(ggplot2)
ggplot(bar, aes(x=variable, y=mean, fill=factor(gender)))+
geom_bar(position="dodge", stat="identity")
Solved it:
I had to use Mo'Bulletproofer method
Since the class
is added dynamically, you need to use event delegation to register the event handler
$(document).on('click', "a.tabclick", function() {
var liId = $(this).parent("li").attr("id");
alert(liId);
});
You should use this.state.check
instead of check.value
here:
this.setState({check: !this.state.check})
But anyway it is bad practice to do it this way. Much better to move it to separate method and don't write callbacks directly in markup.
A static constructor looks like this
static class Foo
{
static Foo()
{
// Static initialization code here
}
}
It is executed only once when the type is first used. All classes can have static constructors, not just static classes.
If you have several heroku apps, you must type heroku restart --app app_name
or heroku restart -a app_name
This will work as long as the image you want to rotate is already in your Properties resources folder.
In Partial Class:
Bitmap bmp2;
OnLoad:
bmp2 = new Bitmap(Tycoon.Properties.Resources.save2);
pictureBox6.SizeMode = PictureBoxSizeMode.StretchImage;
pictureBox6.Image = bmp2;
Button or Onclick
private void pictureBox6_Click(object sender, EventArgs e)
{
if (bmp2 != null)
{
bmp2.RotateFlip(RotateFlipType.Rotate90FlipNone);
pictureBox6.Image = bmp2;
}
}
Yet another approach is ISNULL().
UPDATE [DATABASE].[dbo].[TABLE_NAME]
SET
[ABC] = ISNULL(@ABC, [ABC]),
[ABCD] = ISNULL(@ABCD, [ABCD])
The difference between ISNULL and COALESCE is the return type. COALESCE can also take more than 2 arguments, and use the first that is not null. I.e.
select COALESCE(null, null, 1, 'two') --returns 1
select COALESCE(null, null, null, 'two') --returns 'two'
RFC6690 - Constrained RESTful Environments (CoRE) Link Format Does not explicitly state what Date format should be however in section 2. Link Format it points to RFC 3986. This implies that recommendation for date type in RFC 3986 should be used.
Basically RFC 3339 Date and Time on the Internet is the document to look at that says:
date and time format for use in Internet protocols that is a profile of the ISO 8601 standard for representation of dates and times using the Gregorian calendar.
what this boils down to : YYYY-MM-ddTHH:mm:ss.ss±hh:mm
(e.g 1937-01-01T12:00:27.87+00:20)
Is the safest bet.
C# equivalent of your code is
class Imagedata : PDFStreamEngine
{
// C# uses "base" keyword whenever Java uses "super"
// so instead of super(...) in Java we should call its C# equivalent (base):
public Imagedata()
: base(ResourceLoader.loadProperties("org/apache/pdfbox/resources/PDFTextStripper.properties", true))
{ }
// Java methods are virtual by default, when C# methods aren't.
// So we should be sure that processOperator method in base class
// (that is PDFStreamEngine)
// declared as "virtual"
protected override void processOperator(PDFOperator operations, List arguments)
{
base.processOperator(operations, arguments);
}
}
Please do not depend on casting as a solution, even though others are suggesting this as a valid option to prevent an error, it might cause another one.
Be aware: If you expect a specific form of array to be returned, this might fail you. More checks are required for that.
E.g. casting a boolean to an array
(array)bool
, will NOT result in an empty array, but an array with one element containing the boolean value as an int:[0=>0]
or[0=>1]
.
I wrote a quick test to present this problem. (Here is a backup Test in case the first test url fails.)
Included are tests for: null
, false
, true
, a class
, an array
and undefined
.
Always test your input before using it in foreach. Suggestions:
$array = is_array($var) or is_object($var) ? $var : [] ;
try{}catch(){}
blocksarray_key_exists
on a specific key, or test the depth of an array (when it is one !).You don't have to bind parameters if you use query builder or eloquent ORM. However, if you use DB::raw()
, ensure that you binding the parameters.
Try the following:
$array = array(1,2,3); $query = DB::table('offers'); $query->select('id', 'business_id', 'address_id', 'title', 'details', 'value', 'total_available', 'start_date', 'end_date', 'terms', 'type', 'coupon_code', 'is_barcode_available', 'is_exclusive', 'userinformations_id', 'is_used'); $query->leftJoin('user_offer_collection', function ($join) use ($array) { $join->on('user_offer_collection.offers_id', '=', 'offers.id') ->whereIn('user_offer_collection.user_id', $array); }); $query->get();
Try to check this free an open source alternative https://www.nuget.org/packages/AIM It is free to use and open source and uses the exact same way that System.Net.Mail is using To send email to implicit ssl ports you can use following code
public static void SendMail()
{
var mailMessage = new MimeMailMessage();
mailMessage.Subject = "test mail";
mailMessage.Body = "hi dude!";
mailMessage.Sender = new MimeMailAddress("[email protected]", "your name");
mailMessage.To.Add(new MimeMailAddress("[email protected]", "your friendd's name"));
// You can add CC and BCC list using the same way
mailMessage.Attachments.Add(new MimeAttachment("your file address"));
//Mail Sender (Smtp Client)
var emailer = new SmtpSocketClient();
emailer.Host = "your mail server address";
emailer.Port = 465;
emailer.SslType = SslMode.Ssl;
emailer.User = "mail sever user name";
emailer.Password = "mail sever password" ;
emailer.AuthenticationMode = AuthenticationType.Base64;
// The authentication types depends on your server, it can be plain, base 64 or none.
//if you do not need user name and password means you are using default credentials
// In this case, your authentication type is none
emailer.MailMessage = mailMessage;
emailer.OnMailSent += new SendCompletedEventHandler(OnMailSent);
emailer.SendMessageAsync();
}
// A simple call back function:
private void OnMailSent(object sender, AsyncCompletedEventArgs asynccompletedeventargs)
{
if (e.UserState!=null)
Console.Out.WriteLine(e.UserState.ToString());
if (e.Error != null)
{
MessageBox.Show(e.Error.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
else if (!e.Cancelled)
{
MessageBox.Show("Send successfull!", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
}
Your code looks fine, but there are a couple of things to be aware of:
Post::find($id);
acts upon the primary key, if you have set your primary key in your model to something other than id
by doing:
protected $primaryKey = 'slug';
then find
will search by that key instead.
Laravel also expects the id
to be an integer, if you are using something other than an integer (such as a string) you need to set the incrementing property on your model to false:
public $incrementing = false;
In /etc/my.cnf
add:
max_allowed_packet=32M
It worked for me. You can verify by going into PHPMyAdmin and opening a SQL command window and executing:
SHOW VARIABLES LIKE 'max_allowed_packet'
Run eventvwr from the command line to see if it has recorded any Application errors.
This might give you an actual error message that is more useful.