To diagnose this issue, place the line of code causing the TargetInvocationException inside the try block.
To troubleshoot this type of error, get the inner exception. It could be due to a number of different issues.
try
{
// code causing TargetInvocationException
}
catch (Exception e)
{
if (e.InnerException != null)
{
string err = e.InnerException.Message;
}
}
clear pictureBox in c# winform Application Simple way to clear pictureBox in c# winform Application
First use this Namespace:
using System.Drawing;
Add this anywhere on your form:
listBox.DrawMode = DrawMode.OwnerDrawFixed;
listBox.DrawItem += listBox_DrawItem;
Here is the Event Handler:
private void listBox_DrawItem(object sender, DrawItemEventArgs e)
{
e.DrawBackground();
Graphics g = e.Graphics;
g.FillRectangle(new SolidBrush(Color.White), e.Bounds);
ListBox lb = (ListBox)sender;
g.DrawString(lb.Items[e.Index].ToString(), e.Font, new SolidBrush(Color.Black), new PointF(e.Bounds.X, e.Bounds.Y));
e.DrawFocusRectangle();
}
Important benefit of the dynamic resources
if application startup takes extremely long time, you must use dynamic resources, because static resources are always loaded when the window or app is created, while dynamic resources are loaded when they’re first used.
However, you won’t see any benefit unless your resource is extremely large and complex.
Since some codes gave a wrong result for Edge and Opera, I suggest to try this code:
$popularBrowsers = ["Opera","OPR/", "Edg", "Chrome", "Safari", "Firefox", "MSIE", "Trident"];
$userAgent = $_SERVER['HTTP_USER_AGENT'];
$userBrowser = 'Other less popular browsers';
foreach ($popularBrowsers as $browser) {
if (strpos($userAgent, $browser) !== false) {
$userBrowser = $browser;
break;
}
}
switch ($userBrowser) {
case 'OPR/':
$userBrowser = 'Opera';
break;
case 'MSIE':
$userBrowser = 'Internet Explorer';
break;
case 'Trident':
$userBrowser = 'Internet Explorer';
break;
case 'Edg':
$userBrowser = 'Microsoft Edge';
break;
}
echo "Your browser: " . $userBrowser;
For information about agent strings for different browsers and some similarities in them, please refer to: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/User-Agent
Some of the solutions described here did not work for me. Others did, however they produced warnings on runtime and javadoc was still not linked. After some experimenting, I managed to solve this. The steps are:
Install the Google Play Services as recommended on Android Developers.
Set up your project as recommended on Android Developers.
If you followed 1. and 2., you should see two projects in your workspace: your project and google-play-services_lib project. Copy the docs
folder which contains the javadoc from <android-sdk>/extras/google/google_play_services/
to libs
folder of your project.
Copy google-play-services.jar
from <android-sdk>/extras/google/google_play_services/libproject/google-play-services_lib/libs
to 'libs' folder of your project.
In google-play-services_lib
project, edit libs/google-play-services.jar.properties . The <path>
in doc=<path>
should point to the subfolder reference
of the folder docs
, which you created in step 3.
In Eclipse, do Project > Clean. Done, javadoc is now linked.
if you have a the input password in a variable and you want to match exactly 123456 then anchors will help you:
/^123456$/
in perl the test for matching the password would be something like
print "MATCH_OK" if ($input_pass=~/^123456$/);
EDIT:
bart kiers is right tho, why don't you use a strcmp() for this? every language has it in its own way
as a second thought, you may want to consider a safer authentication mechanism :)
Just a sidenote to Overlord Zurg's answer.
I've added the dummy reference this way, and it worked in Debug mode:
public class DummyClass
{
private static void Dummy()
{
var dummy = typeof(AbcDll.AnyClass);
}
}
But in Release mode, the dependent dll still did not get copied.
This worked however:
public class DummyClass
{
private static void Dummy()
{
Action<Type> noop = _ => {};
var dummy = typeof(AbcDll.AnyClass);
noop(dummy);
}
}
This infomation actually costed me hours to figure out, so I thought I share it.
Here is a simple programe to capture a image from using laptop default camera.I hope that this will be very easy method for all.
import cv2
# 1.creating a video object
video = cv2.VideoCapture(0)
# 2. Variable
a = 0
# 3. While loop
while True:
a = a + 1
# 4.Create a frame object
check, frame = video.read()
# Converting to grayscale
#gray = cv2.cvtColor(frame,cv2.COLOR_BGR2GRAY)
# 5.show the frame!
cv2.imshow("Capturing",frame)
# 6.for playing
key = cv2.waitKey(1)
if key == ord('q'):
break
# 7. image saving
showPic = cv2.imwrite("filename.jpg",frame)
print(showPic)
# 8. shutdown the camera
video.release()
cv2.destroyAllWindows
You can see my github code here
In Chrome, go to options (Customize and Control, the 3 dots/bars at top right) ---> More Tools ---> save page as
save page as
filename : any_name.html
save as type : webpage complete.
Then you will get any_name.html
and any_name folder
.
Create a BroadcastReceiver
and register it to receive ACTION_BOOT_COMPLETED. You also need RECEIVE_BOOT_COMPLETED permission.
Read: Listening For and Broadcasting Global Messages, and Setting Alarms
Union
will remove duplicates. Union All
does not.
RegEx is -
^(?:(?=.*\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[@#$%^&+=]).*)[^\s]{8,}$
In the old days, when we could assume that most computers used ASCII, we would just do
int i = c[0] - '0';
But in these days of Unicode, it's not a good idea. It was never a good idea if your code had to run on a non-ASCII computer.
Edit: Although it looks hackish, evidently it is guaranteed by the standard to work. Thanks @Earwicker.
When you use docker run
to start a container, it actually creates a new container based on the image you have specified.
Besides the other useful answers here, note that you can restart an existing container after it exited and your changes are still there.
docker start f357e2faab77 # restart it in the background
docker attach f357e2faab77 # reattach the terminal & stdin
This will give you the time in seconds + microseconds
#include <sys/time.h>
struct timeval tv;
gettimeofday(&tv,NULL);
tv.tv_sec // seconds
tv.tv_usec // microseconds
Still using empty strings you can use:
document.getElementById("name").value = '';
document.getElementById("review").value = '';
You should use webpack here to make your life easier. Add below rule in your config:
const srcPath = path.join(__dirname, '..', 'publicfolder')
const rules = []
const includePaths = [
srcPath
]
// handle images
rules.push({
test: /\.(png|gif|jpe?g|svg|ico)$/,
include: includePaths,
use: [{
loader: 'file-loader',
options: {
name: 'images/[name]-[hash].[ext]'
}
}
After this, you can simply import the images into your react components:
import myImage from 'publicfolder/images/Image1.png'
Use myImage like below:
<div><img src={myImage}/></div>
or if the image is imported into local state of component
<div><img src={this.state.myImage}/></div>
Specific font
Setting a specific font in Swift is done like this:
let myFont = UIFont(name: "Helvetica", size: 17)
If you don't know the name, you can get a list of the available font names like this:
print(UIFont.familyNames())
Or an even more detailed list like this:
for familyName in UIFont.familyNames() {
print(UIFont.fontNamesForFamilyName(familyName))
}
But the system font changes from version to version of iOS. So it would be better to get the system font dynamically.
System font
let myFont = UIFont.systemFontOfSize(17)
But we have the size hard-coded in. What if the user's eyes are bad and they want to make the font larger? Of course, you could make a setting in your app for the user to change the font size, but this would be annoying if the user had to do this separately for every single app on their phone. It would be easier to just make one change in the general settings...
Dynamic font
let myFont = UIFont.preferredFont(forTextStyle: .body)
Ah, now we have the system font at the user's chosen size for the Text Style we are working with. This is the recommended way of setting the font. See Supporting Dynamic Type for more info on this.
WARNING: DO NOT USE IN A PRODUCTION SYSTEM
/# df
...
/dev/xvda1 51467016 39384516 9886300 80% /
...
Ok, let's first try system prune
#/ docker system prune --volumes
...
/# df
...
/dev/xvda1 51467016 38613596 10657220 79% /
...
Not so great, seems like it cleaned up a few megabytes. Let's go crazy now:
/# sudo su
/# service docker stop
/# cd /var/lib/docker
/var/lib/docker# rm -rf *
/# service docker start
/var/lib/docker# df
...
/dev/xvda1 51467016 8086924 41183892 17% /
...
Nice! Just remember that this is NOT recommended in anything but a throw-away server. At this point Docker's internal database won't be able to find any of these overlays and it may cause unintended consequences.
Step 1: Right-click on references tab to add reference.
Step 2: Click on Assemblies tab
Step 3: Search for 'System.Configuration'
Step 4: Click OK.
Then it will work.
string value = System.Configuration.ConfigurationManager.AppSettings["keyname"];
You can even nest document ready functions inside included html files. Here's an example using jquery:
File: test_main.html
<!DOCTYPE html>
<html lang="en">
<head>
<script src="jquery-1.10.2.min.js"></script>
</head>
<body>
<div id="main-container">
<h1>test_main.html</h1>
</div>
<script>
$(document).ready( function()
{
console.log( 'test_main.html READY' );
$("#main-container").load("test_embed.html");
} );
</script>
</body>
</html>
File: test_embed.html
<h1>test_embed.html</h1>
<script>
$(document).ready( function()
{
console.log( 'test_embed.html READY' );
} );
</script>
Console output:
test_main.html READY test_main.html:15
test_embed.html READY (program):4
Browser shows:
test_embed.html
$?
is used to find the return value of the last executed command.
Try the following in the shell:
ls somefile
echo $?
If somefile
exists (regardless whether it is a file or directory), you will get the return value thrown by the ls
command, which should be 0
(default "success" return value). If it doesn't exist, you should get a number other then 0. The exact number depends on the program.
For many programs you can find the numbers and their meaning in the corresponding man page. These will usually be described as "exit status" and may have their own section.
The 2nd file needs to know about the existance of your variable. To do this you declare the variable again but use the keyword extern
in front of it. This tells the compiler that the variable is available but declared somewhere else, thus prevent instanciating it (again, which would cause clashes when linking). While you can put the extern
declaration in the C file itself it's common style to have an accompanying header (i.e. .h
) file for each .c
file that provides functions or variables to others which hold the extern
declaration. This way you avoid copying the extern
declaration, especially if it's used in multiple other files. The same applies for functions, though you don't need the keyword extern
for them.
That way you would have at least three files: the source file that declares the variable, it's acompanying header that does the extern
declaration and the second source file that #include
s the header to gain access to the exported variable (or any other symbol exported in the header). Of course you need all source files (or the appropriate object files) when trying to link something like that, as the linker needs to resolve the symbol which is only possible if it actually exists in the files linked.
This will work:
{{ oD.OrderDate.replace('/Date(','').replace(')/','') | date:"MM/dd/yyyy" }}
NOTE: once you replace these then remaining date/millis will be converted to given foramt.
you need to decode the bytes
of you want a string:
b = b'1234'
print(b.decode('utf-8')) # '1234'
Avoid using
RETURN
statement when you are using
BEGIN TRY
...
END TRY
BEGIN CATCH
...
END CATCH
and
BEGIN, COMMIT & ROLLBACK
statements in SQL stored procedures
ArrayList<String[]> action = new ArrayList<String[]>();
Don't need String[2]
;
I used:
git reset --hard
I lost some changes, but this is ok.
As Vinay Kumar pointed out that it will not update global installed Angular CLI. To update it globally just use following commands:
npm uninstall -g @angular/cli
npm cache clean
npm install -g @angular/cli@latest
Note if you want to update existing project you have to modify existing project, you should change package.json inside your project.
There are no breaking changes in Angular itself but they are in RxJS, so don't forget to use rxjs-compat library to work with legacy code.
npm install --save rxjs-compat
I wrote a good article about installation/updating Angular CLI http://bmnteam.com/angular-cli-installation/
In additon to other answers - very often, you do not have to iterate using the index but you can simply use a for-each expression:
my_list = ['a', 'b', 'c']
for item in my_list:
print item
This worked just fine for me:
http://jelled.com/instagram/access-token
FYI, I used it in combination with the jQuery Instagram plugin which you'll find here; http://potomak.github.com/jquery-instagram
You can use the below query to identify the values. But please keep in mind that this will not give you the results from encrypted stored procedure.
SELECT DISTINCT OBJECT_NAME(comments.id) OBJECT_NAME
,objects.type_desc
FROM syscomments comments
,sys.objects objects
WHERE comments.id = objects.object_id
AND TEXT LIKE '%CreatedDate%'
ORDER BY 1
Download Json.NET from here http://james.newtonking.com/projects/json-net.aspx
name deserializedName = JsonConvert.DeserializeObject<name>(jsonData);
I think this is the minimal code to implement it:
i=0,a={valueOf:()=>++i}_x000D_
_x000D_
if (a == 1 && a == 2 && a == 3) {_x000D_
console.log('Mind === Blown');_x000D_
}
_x000D_
Creating a dummy object with a custom valueOf
that increments a global variable i
on each call. 23 characters!
I had a file named mysql.py in the folder. That's why it gave an error because it tried to call it in the import process.
import mysql.connector
I solved the problem by changing the file name.
After changing app.php, make sure you run:
php artisan config:clear
This is needed to clear the cache of config settings. If you notice that your timestamps are still wrong after changing the timezone in your app.php file, then running the above command should refresh everything, and your new timezone should be effective.
For elements with dynamic width it's possible to use transform: translateX(-100%);
to counter the horizontal percentage value. This leads to two possible solutions:
Transition from:
transform: translateX(0);
to
transform: translateX(calc(100vw - 100%));
#viewportPendulum {_x000D_
position: fixed;_x000D_
left: 0;_x000D_
top: 0;_x000D_
animation: 2s ease-in-out infinite alternate swingViewport;_x000D_
/* just for styling purposes */_x000D_
background: #c70039;_x000D_
padding: 1rem;_x000D_
color: #fff;_x000D_
font-family: sans-serif;_x000D_
}_x000D_
_x000D_
@keyframes swingViewport {_x000D_
from {_x000D_
transform: translateX(0);_x000D_
}_x000D_
to {_x000D_
transform: translateX(calc(100vw - 100%));_x000D_
}_x000D_
}
_x000D_
<div id="viewportPendulum">Viewport</div>
_x000D_
Transition from:
transform: translateX(0);
left: 0;
to
left: 100%;
transform: translateX(-100%);
#parentPendulum {_x000D_
position: relative;_x000D_
display: inline-block;_x000D_
animation: 2s ease-in-out infinite alternate swingParent;_x000D_
/* just for styling purposes */_x000D_
background: #c70039;_x000D_
padding: 1rem;_x000D_
color: #fff;_x000D_
font-family: sans-serif;_x000D_
}_x000D_
_x000D_
@keyframes swingParent {_x000D_
from {_x000D_
transform: translateX(0);_x000D_
left: 0;_x000D_
}_x000D_
to {_x000D_
left: 100%;_x000D_
transform: translateX(-100%);_x000D_
}_x000D_
}_x000D_
_x000D_
.wrapper {_x000D_
padding: 2rem 0;_x000D_
margin: 2rem 15%;_x000D_
background: #eee;_x000D_
}
_x000D_
<div class="wrapper">_x000D_
<div id="parentPendulum">Parent</div>_x000D_
</div>
_x000D_
Note: This approach can easily be extended to work for vertical positioning. Visit example here.
Linked lists are preferable over arrays when:
you need constant-time insertions/deletions from the list (such as in real-time computing where time predictability is absolutely critical)
you don't know how many items will be in the list. With arrays, you may need to re-declare and copy memory if the array grows too big
you don't need random access to any elements
you want to be able to insert items in the middle of the list (such as a priority queue)
Arrays are preferable when:
you need indexed/random access to elements
you know the number of elements in the array ahead of time so that you can allocate the correct amount of memory for the array
you need speed when iterating through all the elements in sequence. You can use pointer math on the array to access each element, whereas you need to lookup the node based on the pointer for each element in linked list, which may result in page faults which may result in performance hits.
memory is a concern. Filled arrays take up less memory than linked lists. Each element in the array is just the data. Each linked list node requires the data as well as one (or more) pointers to the other elements in the linked list.
Array Lists (like those in .Net) give you the benefits of arrays, but dynamically allocate resources for you so that you don't need to worry too much about list size and you can delete items at any index without any effort or re-shuffling elements around. Performance-wise, arraylists are slower than raw arrays.
Simply just do something like this:
li {
cursor: pointer;
}
I apply it on your code to see how it works:
li {_x000D_
cursor: pointer;_x000D_
}
_x000D_
<ul>_x000D_
<li>foo</li>_x000D_
<li>goo</li>_x000D_
</ul>
_x000D_
Note: Also DO not forget you can have any hand cursor with customised cursor, you can create fav hand icon like this one for example:
div {_x000D_
display: block;_x000D_
width: 400px;_x000D_
height: 400px;_x000D_
background: red;_x000D_
cursor: url(http://findicons.com/files/icons/1840/free_style/128/hand.png) 4 12, auto;_x000D_
}
_x000D_
<div>_x000D_
</div>
_x000D_
Basically both suggested solutions work fine in most cases. My main negative experience with ngOnChange() is the lack of type safety.
In one of my projects I did some renaming, following which some of the magic strings remained unchanged, and the bug of course took some time to surface.
Setters do not have that issue: your IDE or compiler will let you know of any mismatch.
Are you sure you aren't pushing over SSH? Maybe check the email associated with your SSH key in bitbucket if you have one.
https://github.com/jakubgorny47/baku-code/tree/master/c_vector
Here's my implementation. It's basicaly a struct containing pointer to the data, size (in elements), overall allocated space and a size of the type that's being stored in vector to allow use of void pointer.
Razor View Server Side variable can be read to Client Side JavaScript using @ While and JavaScript client side variable can read to Razor View using @:
In your terminal run: docker exec -it container_name /bin/bash
Then: mysql
Specify negative value to spread value. This works for me:
box-shadow: 0 2px 3px -1px rgba(0, 0, 0, 0.1);
Your app is attempting to parse the undefined JSON web token. Such malfunction may occur due to the wrong usage of the local storage. Try to clear your local storage.
Example for Google Chrome:
In this state:
The thread is reading and processing rows for a SELECT statement, and sending data to the client.
Because operations occurring during this this state tend to perform large amounts of disk access (reads).
That's why it takes more time to complete and so is the longest-running state over the lifetime of a given query.
Below solution is a shorthand for @Andy Wilkinson's solution, except that it doesn't have to use a separate class or on a @Bean
annotated method.
application.yml:
input:
name: raja
age: 12
somedata:
abcd: 1
bcbd: 2
cdbd: 3
SomeComponent.java:
@Component
@EnableConfigurationProperties
@ConfigurationProperties(prefix = "input")
class SomeComponent {
@Value("${input.name}")
private String name;
@Value("${input.age}")
private Integer age;
private HashMap<String, Integer> somedata;
public HashMap<String, Integer> getSomedata() {
return somedata;
}
public void setSomedata(HashMap<String, Integer> somedata) {
this.somedata = somedata;
}
}
We can club both @Value
annotation and @ConfigurationProperties
, no issues. But getters and setters are important and @EnableConfigurationProperties
is must to have the @ConfigurationProperties
to work.
I tried this idea from groovy solution provided by @Szymon Stepniak, thought it will be useful for someone.
You must add your keyListener to every component that you need. Only the component with the focus will send these events. For instance, if you have only one TextBox in your JFrame, that TextBox has the focus. So you must add a KeyListener to this component as well.
The process is the same:
myComponent.addKeyListener(new KeyListener ...);
Note: Some components aren't focusable like JLabel.
For setting them to focusable you need to:
myComponent.setFocusable(true);
Made it into a function. You can now call splitCsv <Filename> [chunkSize]
splitCsv() {
HEADER=$(head -1 $1)
if [ -n "$2" ]; then
CHUNK=$2
else
CHUNK=1000
fi
tail -n +2 $1 | split -l $CHUNK - $1_split_
for i in $1_split_*; do
sed -i -e "1i$HEADER" "$i"
done
}
Found on: http://edmondscommerce.github.io/linux/linux-split-file-eg-csv-and-keep-header-row.html
I didn't create my virtualenv using sudo. So Sebastian's answer didn't apply to me. My project is called utils
. I checked utils
directory and saw this:
-rw-r--r-- 1 macuser staff 983 6 Jan 15:17 README.md
drwxr-xr-x 6 root staff 204 6 Jan 14:36 utils.egg-info
-rw-r--r-- 1 macuser staff 31 6 Jan 15:09 requirements.txt
As you can see, utils.egg-info
is owned by root
not macuser
. That is why it was giving me permission denied
error. I also had to remove /Users/macuser/.virtualenvs/armoury/lib/python2.7/site-packages/utils.egg-link
as it was created by root
as well. I did pip install -e .
again after removing those, and it worked.
TL;DR
Long Version
Jenkins Pipeline testing becomes more and more of a pain. Unlike the classic declarative job configuration approach where the user was limited to what the UI exposed the new Jenkins Pipeline is a full fledged programming language for the build process where you mix the declarative part with your own code. As good developers we want to have some unit tests for this kind of code as well.
There are three steps you should follow when developing Jenkins Pipelines. The step 1. should cover 80% of the uses cases.
Examples
The pipelineUnit GitHub repo contains some Spock examples on how to use Jenkins Pipeline Unit testing framework
You could call:
getContentPane().setBackground(Color.black);
Or add a JPanel to the JFrame your using. Then add your components to the JPanel. This will allow you to call
setBackground(Color.black);
on the JPanel to set the background color.
You can get Android Studio not to complain by going to the "Edit Configurations" menu (tap "Shift" three times, type "Edit Configurations"), then change Launch Options > Launch to "Nothing".
I'll probably add a generic activity containing instructions, just to avoid any confusion.
It's an inlined image (png), encoded in base64. It can make a page faster: the browser doesn't have to query the server for the image data separately, saving a round trip.
(It can also make it slower if abused: these resources are not cached, so the bytes are included in each page load.)
I would also suggest LinqPad as a convenient way to tackle with Linq for both advanced and beginners.
Example:
My env: macOS & anaconda3
This works for me:
matplotlib.use('macosx')
or interactive mode:
matplotlib.use('TkAgg')
Consider using more_itertools.unzip:
>>> from more_itertools import unzip
>>> original = [('a', 1), ('b', 2), ('c', 3), ('d', 4)]
>>> [list(x) for x in unzip(original)]
[['a', 'b', 'c', 'd'], [1, 2, 3, 4]]
You can use assertThrows()
, which allows you to test multiple exceptions within the same test. With support for lambdas in Java 8, this is the canonical way to test for exceptions in JUnit.
Per the JUnit docs:
import static org.junit.jupiter.api.Assertions.assertThrows;
@Test
void exceptionTesting() {
MyException thrown = assertThrows(
MyException.class,
() -> myObject.doThing(),
"Expected doThing() to throw, but it didn't"
);
assertTrue(thrown.getMessage().contains("Stuff"));
}
In your controller, render the new
action from your create action if validation fails, with an instance variable, @car
populated from the user input (i.e., the params
hash). Then, in your view, add a logic check (either an if block around the form
or a ternary on the helpers, your choice) that automatically sets the value of the form fields to the params
values passed in to @car if car exists. That way, the form will be blank on first visit and in theory only be populated on re-render in the case of error. In any case, they will not be populated unless @car
is set.
var canvas = document.createElement("canvas");
document.body.appendChild(canvas);
var ctx = canvas.getContext("2d");
ctx.beginPath();
ctx.moveTo(100,100);
ctx.arcTo(0,100,0,0,30);
ctx.arcTo(0,0,100,0,30);
ctx.arcTo(100,0,100,100,30);
ctx.arcTo(100,100,0,100,30);
ctx.fill();
Here's Herb Sutter's take
Guideline: Don’t pass a smart pointer as a function parameter unless you want to use or manipulate the smart pointer itself, such as to share or transfer ownership.
Guideline: Express that a function will store and share ownership of a heap object using a by-value shared_ptr parameter.
Guideline: Use a non-const shared_ptr& parameter only to modify the shared_ptr. Use a const shared_ptr& as a parameter only if you’re not sure whether or not you’ll take a copy and share ownership; otherwise use widget* instead (or if not nullable, a widget&).
\s
matches any white-space character\S
matches any non-white-space character[^ ]
matches anything but a space character.Pick whichever is most appropriate.
If your base class is called Base
, and your function is called FooBar()
you can call it directly using Base::FooBar()
void Base::FooBar()
{
printf("in Base\n");
}
void ChildOfBase::FooBar()
{
Base::FooBar();
}
For PostgreSQL:
GROUP BY to_char(timestampfield, 'yyyy-mm-dd')
or using cast:
GROUP BY timestampfield::date
if you want speed, use the second option and add an index:
CREATE INDEX tablename_timestampfield_date_idx ON tablename(date(timestampfield));
Save the array in a local variable and use the array's length
field to find its length. Subtract one to account for it being 0-based:
String[] bits = one.split("-");
String lastOne = bits[bits.length-1];
Caveat emptor: if the original string is composed of only the separator, for example "-"
or "---"
, bits.length
will be 0 and this will throw an ArrayIndexOutOfBoundsException. Example: https://onlinegdb.com/r1M-TJkZ8
Just a small hack. Update the URL in the file "hudson.model.UpdateCenter.xml" from https to http
<?xml version='1.1' encoding='UTF-8'?>
<sites>
<site>
<id>default</id>
<url>http://updates.jenkins.io/update-center.json</url>
</site>
</sites>
Copy the project into your workspace, create new Android Application Project with the same name from eclipse file->new->project and voila.
you can use the following Bootstrap class with
<tr class="w-25">
</tr>
for more details check the following page https://getbootstrap.com/docs/4.1/utilities/sizing/
This functionality is available from C# 4.0 - it was introduced in Visual Studio 2010. And you can use it in project for .NET 3.5. So there is no need to upgrade old projects in .NET 3.5 to .NET 4.0.
You have to just use Visual Studio 2010, but remember that it should compile to default language version (set it in project Properties->Buid->Advanced...)
This MSDN page has more information about optional parameters in VS 2010.
With Spring 4, if your Controller is annotated with @RestController
instead of @Controller
, you don't need the @ResponseBody
annotation.
The code would be
@RestController
public class FooController {
@RequestMapping(value="/controller", method=GET)
public String foo() {
return "Response!";
}
}
You can find the Javadoc for @RestController
here
You need the following code below. At a glance, this may look like any old code that I made up. However, what I did was look at the source code for http://grepcode.com/file/repo1.maven.org/maven2/mysql/mysql-connector-java/5.1.31/com/mysql/jdbc/PreparedStatement.java. Then after that, I carefully looked through the code of setString(int parameterIndex, String x) to find the characters which it escapes and customised this to my own class so that it can be used for the purposes that you need. After all, if this is the list of characters that Oracle escapes, then knowing this is really comforting security-wise. Maybe Oracle need a nudge to add a method similar to this one for the next major Java release.
public class SQLInjectionEscaper {
public static String escapeString(String x, boolean escapeDoubleQuotes) {
StringBuilder sBuilder = new StringBuilder(x.length() * 11/10);
int stringLength = x.length();
for (int i = 0; i < stringLength; ++i) {
char c = x.charAt(i);
switch (c) {
case 0: /* Must be escaped for 'mysql' */
sBuilder.append('\\');
sBuilder.append('0');
break;
case '\n': /* Must be escaped for logs */
sBuilder.append('\\');
sBuilder.append('n');
break;
case '\r':
sBuilder.append('\\');
sBuilder.append('r');
break;
case '\\':
sBuilder.append('\\');
sBuilder.append('\\');
break;
case '\'':
sBuilder.append('\\');
sBuilder.append('\'');
break;
case '"': /* Better safe than sorry */
if (escapeDoubleQuotes) {
sBuilder.append('\\');
}
sBuilder.append('"');
break;
case '\032': /* This gives problems on Win32 */
sBuilder.append('\\');
sBuilder.append('Z');
break;
case '\u00a5':
case '\u20a9':
// escape characters interpreted as backslash by mysql
// fall through
default:
sBuilder.append(c);
}
}
return sBuilder.toString();
}
}
For listing only directories:
ls -l | grep ^d
For listing only files:
ls -l | grep -v ^d
Or also you can do as:
ls -ld */
This one is:
def binsearch(t, key, low = 0, high = len(t) - 1):
# bisecting the range
while low < high:
mid = (low + high)//2
if t[mid] < key:
low = mid + 1
else:
high = mid
# at this point 'low' should point at the place
# where the value of 'key' is possibly stored.
return low if t[low] == key else -1
This could also be the case if you have created a systemd
service that has:
[Service]
Restart=always
ExecStart=/usr/bin/docker container start -a my_container
ExecStop=/usr/bin/docker container stop -t 2 my_container
I had this error on a MVC Project. And after a long research i found out that the .cs file containing some of the classes i referenced in the main project had a Build Actions set to "Content" ...
After changing it "Content"->"Compile" the error disappeared.
You are likely to use in the code a variable named model
.
Python 3: use functools.reduce
:
>>> from functools import reduce
>>> reduce(lambda x, y: x*y, [1,2,3,4,5,6])
720
Python 2: use reduce
:
>>> reduce(lambda x, y: x*y, [1,2,3,4,5,6])
720
For compatible with 2 and 3 use pip install six
, then:
>>> from six.moves import reduce
>>> reduce(lambda x, y: x*y, [1,2,3,4,5,6])
720
If you want every cell in the grid to have the same background color, you can just do this:
dataGridView1.DefaultCellStyle.BackColor = Color.Green;
Google guides me here but it didn't fix mine, this is a very general question and there are various causes, so I post my problem and solution here for reference in case anyone might read this later.
Another possible cause of 500 error is syntax error in header(...)
function, like this one:
header($_SERVER['SERVER_PROTOCOL'] . '200 OK');
Be aware there should be space between server protocol and status code, so it should be:
header($_SERVER['SERVER_PROTOCOL'] . ' 200 OK');
So I suggest check your http header call if you have it in your code.
You can use ndiff in the difflib module to do this. It has all the information necessary to convert one string into another string.
A simple example:
import difflib
cases=[('afrykanerskojezyczny', 'afrykanerskojezycznym'),
('afrykanerskojezyczni', 'nieafrykanerskojezyczni'),
('afrykanerskojezycznym', 'afrykanerskojezyczny'),
('nieafrykanerskojezyczni', 'afrykanerskojezyczni'),
('nieafrynerskojezyczni', 'afrykanerskojzyczni'),
('abcdefg','xac')]
for a,b in cases:
print('{} => {}'.format(a,b))
for i,s in enumerate(difflib.ndiff(a, b)):
if s[0]==' ': continue
elif s[0]=='-':
print(u'Delete "{}" from position {}'.format(s[-1],i))
elif s[0]=='+':
print(u'Add "{}" to position {}'.format(s[-1],i))
print()
prints:
afrykanerskojezyczny => afrykanerskojezycznym
Add "m" to position 20
afrykanerskojezyczni => nieafrykanerskojezyczni
Add "n" to position 0
Add "i" to position 1
Add "e" to position 2
afrykanerskojezycznym => afrykanerskojezyczny
Delete "m" from position 20
nieafrykanerskojezyczni => afrykanerskojezyczni
Delete "n" from position 0
Delete "i" from position 1
Delete "e" from position 2
nieafrynerskojezyczni => afrykanerskojzyczni
Delete "n" from position 0
Delete "i" from position 1
Delete "e" from position 2
Add "k" to position 7
Add "a" to position 8
Delete "e" from position 16
abcdefg => xac
Add "x" to position 0
Delete "b" from position 2
Delete "d" from position 4
Delete "e" from position 5
Delete "f" from position 6
Delete "g" from position 7
You should ensure the HTTP server headers are correct.
In particular, the header:
Content-Type: text/html; charset=utf-8
should be present.
The meta tag is ignored by browsers if the HTTP header is present.
Also ensure that your file is actually encoded as UTF-8 before serving it, check/try the following:
&#uuu;
.Note: If you use an unicode character for which your system can't find a glyph (no font with that character), your browser should display a question mark or some block like symbol. But if you see multiple roman characters like you do, this denotes an encoding problem.
You can't have duplicate keys in a Map
. You can rather create a Map<Key, List<Value>>
, or if you can, use Guava's Multimap
.
Multimap<Integer, String> multimap = ArrayListMultimap.create();
multimap.put(1, "rohit");
multimap.put(1, "jain");
System.out.println(multimap.get(1)); // Prints - [rohit, jain]
And then you can get the java.util.Map
using the Multimap#asMap()
method.
The function below works perfectly for me:
// Note this *is* JQuery, see below for JS solution instead
function replaceText(selector, text, newText, flags) {
var matcher = new RegExp(text, flags);
$(selector).each(function () {
var $this = $(this);
if (!$this.children().length)
$this.text($this.text().replace(matcher, newText));
});
}
Here's a usage example:
function replaceAllText() {
replaceText('*', 'hello', 'hi', 'g');
}
$(document).ready(replaceAllText);
$('html').ajaxStop(replaceAllText);
You can also use do a direct replacement like so:
document.body.innerHTML = document.body.innerHTML.replace('hello', 'hi');
But be careful with it since it may affect the tags, css and scripts as well.
EDIT: As for a pure JavaScript solution use this method instead:
function replaceText(selector, text, newText, flags) {
var matcher = new RegExp(text, flags);
var elems = document.querySelectorAll(selector), i;
for (i = 0; i < elems.length; i++)
if (!elems[i].childNodes.length)
elems[i].innerHTML = elems[i].innerHTML.replace(matcher, newText);
}
Couple of things you can do, without executing the actual report just run the sproc from within the data tab of reporting services. Does it still take time? Another option is to use SQL Profiler and determine what is coming in and out of the database system.
Another thing you can do to test it, so to recreate a simple report without any parameters. Run the report and see if it makes a difference. It could be that your RS report is corrupted or badly formed that may cause the rendering to be really slow.
SIMPLEST SOLUTION OUT THERE FOR THIS PROBLEM:
I have had this Problem for two months now. My key hashes have been pyling up to 9. Today i finally found the simple solution:
STEP 1:
Install the facebook sdk you downloaded from the facebook developer page on your phone. Don´t install the normal facebook app. Make sure you can log into facebook. Then log out.
STEP 2:
Export your app with your final release key as an apk, like you would when uploading it to the playstore.
STEP 3:
Put the Apk file on your phone via usb cable or usb stick.
STEP 4:
Install your app, using a file manager: Example
STEP 5:
Launch your app and try to log in with facebook. A dialog will open and tell you: "the key YOURHASHKEY has not been found in the facebook developer console"
STEP 6:
Write down the key.
STEP 7:
Put it into your facebook developer console and save. Now you are done. Anyone that downloads your app, published with earlier used keystore can log into facebook.
Enjoy
It's probably like that because of efficiency and because if you have multiple programs writing to a single TTY, this way you don't get characters on a line interlaced. So if program A and B are outputting, you'll usually get:
program A output
program B output
program B output
program A output
program B output
This stinks, but it's better than
proprogrgraam m AB ououtputputt
prproogrgram amB A ououtputtput
program B output
Note that it isn't even guaranteed to flush on a newline, so you should flush explicitly if flushing matters to you.
HTML
<input type="checkbox" id="checkme"/><input type="submit" name="sendNewSms" class="inputButton" id="sendNewSms" value=" Send " />
JS
var checker = document.getElementById('checkme');
var sendbtn = document.getElementById('sendNewSms');
checker.onchange = function() {
sendbtn.disabled = !!this.checked;
};
Set -XX:PermSize=64m -XX:MaxPermSize=128m
. Later on you may also try increasing MaxPermSize
. Hope it'll work. The same works for me. Setting only MaxPermSize
didn't worked for me.
You might implement your class model by composition, having the book object have a map of chapter objects contained within it (map chapter number to chapter object). Your search function could be given a list of books into which to search by asking each book to search its chapters. The book object would then iterate over each chapter, invoking the chapter.search() function to look for the desired key and return some kind of index into the chapter. The book's search() would then return some data type which could combine a reference to the book and some way to reference the data that it found for the search. The reference to the book could be used to get the name of the book object that is associated with the collection of chapter search hits.
No, you need to wrap your TextBlock in a Border. Example:
<Border BorderThickness="1" BorderBrush="Black">
<TextBlock ... />
</Border>
Of course, you can set these properties (BorderThickness
, BorderBrush
) through styles as well:
<Style x:Key="notCalledBorder" TargetType="{x:Type Border}">
<Setter Property="BorderThickness" Value="1" />
<Setter Property="BorderBrush" Value="Black" />
</Style>
<Border Style="{StaticResource notCalledBorder}">
<TextBlock ... />
</Border>
This PL*SQL will write to DBMS_OUTPUT a script that will drop each constraint that does not have delete cascade and recreate it with delete cascade.
NOTE: running the output of this script is AT YOUR OWN RISK. Best to read over the resulting script and edit it before executing it.
DECLARE
CURSOR consCols (theCons VARCHAR2, theOwner VARCHAR2) IS
select * from user_cons_columns
where constraint_name = theCons and owner = theOwner
order by position;
firstCol BOOLEAN := TRUE;
begin
-- For each constraint
FOR cons IN (select * from user_constraints
where delete_rule = 'NO ACTION'
and constraint_name not like '%MODIFIED_BY_FK' -- these constraints we do not want delete cascade
and constraint_name not like '%CREATED_BY_FK'
order by table_name)
LOOP
-- Drop the constraint
DBMS_OUTPUT.PUT_LINE('ALTER TABLE ' || cons.OWNER || '.' || cons.TABLE_NAME || ' DROP CONSTRAINT ' || cons.CONSTRAINT_NAME || ';');
-- Re-create the constraint
DBMS_OUTPUT.PUT('ALTER TABLE ' || cons.OWNER || '.' || cons.TABLE_NAME || ' ADD CONSTRAINT ' || cons.CONSTRAINT_NAME
|| ' FOREIGN KEY (');
firstCol := TRUE;
-- For each referencing column
FOR consCol IN consCols(cons.CONSTRAINT_NAME, cons.OWNER)
LOOP
IF(firstCol) THEN
firstCol := FALSE;
ELSE
DBMS_OUTPUT.PUT(',');
END IF;
DBMS_OUTPUT.PUT(consCol.COLUMN_NAME);
END LOOP;
DBMS_OUTPUT.PUT(') REFERENCES ');
firstCol := TRUE;
-- For each referenced column
FOR consCol IN consCols(cons.R_CONSTRAINT_NAME, cons.R_OWNER)
LOOP
IF(firstCol) THEN
DBMS_OUTPUT.PUT(consCol.OWNER);
DBMS_OUTPUT.PUT('.');
DBMS_OUTPUT.PUT(consCol.TABLE_NAME); -- This seems a bit of a kluge.
DBMS_OUTPUT.PUT(' (');
firstCol := FALSE;
ELSE
DBMS_OUTPUT.PUT(',');
END IF;
DBMS_OUTPUT.PUT(consCol.COLUMN_NAME);
END LOOP;
DBMS_OUTPUT.PUT_LINE(') ON DELETE CASCADE ENABLE VALIDATE;');
END LOOP;
end;
If you have to get an attribute that is not the ID. I would use CollectionUtils.
Dog someDog = new Dog();
Dog dog = CollectionUtils(dogList, new Predicate() {
@Override
public boolean evaluate(Object o)
{
Dog d = (Dog)o;
return someDog.getName().equals(d.getName());
}
});
From the documentation get_or_create:
# get_or_create() a person with similar first names.
p, created = Person.objects.get_or_create(
first_name='John',
last_name='Lennon',
defaults={'birthday': date(1940, 10, 9)},
)
# get_or_create() didn't have to create an object.
>>> created
False
Explanation:
Fields to be evaluated for similarity, have to be mentioned outside defaults
. Rest of the fields have to be included in defaults
. In case CREATE event occurs, all the fields are taken into consideration.
It looks like you need to be returning into a tuple, instead of a single variable, do like this:
customer.source,created = Source.objects.get_or_create(name="Website")
I am using Server version: 5.7.11-log MySQL Community Server (GPL)
Now we will solve this in a simple way.
I have created a table named "datetable"
mysql> describe datetable;
+---------+---------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+---------+---------+------+-----+---------+-------+
| colid | int(11) | NO | PRI | NULL | |
| coldate | date | YES | | NULL | |
+---------+---------+------+-----+---------+-------+
2 rows in set (0.00 sec)
now, wee will see the inserted records within.
mysql> select * from datetable;
+-------+------------+
| colid | coldate |
+-------+------------+
| 101 | 2015-01-01 |
| 102 | 2015-05-01 |
| 103 | 2016-01-01 |
+-------+------------+
3 rows in set (0.00 sec)
and here our query to fetch records within two dates rather than those dates.
mysql> select * from datetable where coldate > '2015-01-01' and coldate < '2016-01-01';
+-------+------------+
| colid | coldate |
+-------+------------+
| 102 | 2015-05-01 |
+-------+------------+
1 row in set (0.00 sec)
hope this would help many ones.
you can directly send mail from php mail() function if you specified the smtp server and smtp port in php.ini, first ask the SMTP server credential to your ISP.
SMTP = smtp.wlink.com.np //put your ISP's smtp server
smtp_port = 25 // your ISP's smtp port.
then just restart the apache server and it will start working. ENjoy ...
We can merge two collection by using mongoDB sub query. Here is example, Commentss--
`db.commentss.insert([
{ uid:12345, pid:444, comment:"blah" },
{ uid:12345, pid:888, comment:"asdf" },
{ uid:99999, pid:444, comment:"qwer" }])`
Userss--
db.userss.insert([
{ uid:12345, name:"john" },
{ uid:99999, name:"mia" }])
MongoDB sub query for JOIN--
`db.commentss.find().forEach(
function (newComments) {
newComments.userss = db.userss.find( { "uid": newComments.uid } ).toArray();
db.newCommentUsers.insert(newComments);
}
);`
Get result from newly generated Collection--
db.newCommentUsers.find().pretty()
Result--
`{
"_id" : ObjectId("5511236e29709afa03f226ef"),
"uid" : 12345,
"pid" : 444,
"comment" : "blah",
"userss" : [
{
"_id" : ObjectId("5511238129709afa03f226f2"),
"uid" : 12345,
"name" : "john"
}
]
}
{
"_id" : ObjectId("5511236e29709afa03f226f0"),
"uid" : 12345,
"pid" : 888,
"comment" : "asdf",
"userss" : [
{
"_id" : ObjectId("5511238129709afa03f226f2"),
"uid" : 12345,
"name" : "john"
}
]
}
{
"_id" : ObjectId("5511236e29709afa03f226f1"),
"uid" : 99999,
"pid" : 444,
"comment" : "qwer",
"userss" : [
{
"_id" : ObjectId("5511238129709afa03f226f3"),
"uid" : 99999,
"name" : "mia"
}
]
}`
Hope so this will help.
ok, after 5 years have passed....
if discount.try :nonzero?
...
end
It's important to note that try
is defined in the ActiveSupport gem, so it is not available in plain ruby.
For me this was the solution.
The problem was that the SVN server was behind a reverse-proxy (pound). And the reverse proxy had to be told to allow OPTIONS
.
Just like any other text file, .js
files have specific encodings they are saved in. This message means you are saving the .js
file with a non-UTF8 encoding (probably ASCII), and so your non-ASCII characters never even make it to the disk.
That is, the problem is not at the level of HTML or <meta charset>
or Content-Type
headers, but instead a very basic issue of how your text file is saved to disk.
To fix this, you'll need to change the encoding that Dreamweaver saves files in. It looks like this page outlines how to do so; choose UTF8 without saving a Byte Order Mark (BOM). This Super User answer (to a somewhat-related question) even includes screenshots.
In the POM, you can set the compiler properties, e.g. for 1.8:
<project>
...
<properties>
<maven.compiler.source>1.8</maven.compiler.source>
<maven.compiler.target>1.8</maven.compiler.target>
</properties>
...
</project>
Use it like this:
$("#searchField").focus(function() {
$(this).val("");
});
It has to work. Otherwise it probably never gets focused.
You should probably set the property dt.Columns["columnName"].ReadOnly = false;
before.
If you want to change the size of plot the use arg figsize
df.groupby(['NFF', 'ABUSE']).size().unstack()
.plot(kind='bar', stacked=True, figsize=(15, 5))
I would rather create a map
export class item{
name: string;
id: string
}
let caches = new Map<string, item>();
and then you can simply
this.caches[newitem.id] = newitem;
even
this.caches.set(newitem.id, newitem);
array is so 1999. :)
There are pretty good solutions here but they don't help to understand why the problem actually happens.
But it's very simple, you just need to understand how logic OR ||
works. Whole expression will evaluate to true
when either of its sides evaluates to true
.
Now let's look at your case. Assume whole details.Payment[0].Status
is Status
and it's a number for brevity. Then we have Status != 0 || Status != 1 || ...
.
Imagine Status = 1
:
( 1 != 0 || 1 != 1 || ... ) =
( true || false || ... ) =
( true || ... ) = ... = true
Now imagine Status = 0
:
( 0 != 0 || 0 != 1 || ... ) =
( false || true || ... ) =
( true || ... ) = ... = true
As you it doesn't even matter what you have as ...
as logical OR
of first two expressions gives you true
which will be the result of the full expression.
What you actually need is logical AND
&&
that will be true only if both its sides are true
.
Another variation:
UPDATE test
SET field = IF ( {condition}, {new value}, field )
WHERE id = 123
This will update the field
with {new value}
only if {condition}
is met
There is a third-party log4net adapter for the ASP.NET Core logging interface.
Only thing you need to do is pass the ILoggerFactory
to your Startup
class, then call
loggerFactory.AddLog4Net();
and have a config in place. So you don't have to write any boiler-plate code.
When using MVC, try using ViewBag. The best way to take input from textbox and displaying in View.
On Windows Powershell I run this:
git stash apply "stash@{1}"
If your computer, OS and python are 64-bit, then you can use the mmap module to map the contents of the file into memory and access it with indices and slices. Here an example from the documentation:
import mmap
with open("hello.txt", "r+") as f:
# memory-map the file, size 0 means whole file
map = mmap.mmap(f.fileno(), 0)
# read content via standard file methods
print map.readline() # prints "Hello Python!"
# read content via slice notation
print map[:5] # prints "Hello"
# update content using slice notation;
# note that new content must have same size
map[6:] = " world!\n"
# ... and read again using standard file methods
map.seek(0)
print map.readline() # prints "Hello world!"
# close the map
map.close()
If either your computer, OS or python are 32-bit, then mmap-ing large files can reserve large parts of your address space and starve your program of memory.
public async Task<ActionResult> Index()
{
apiTable table = new apiTable();
table.Name = "Asma Nadeem";
table.Roll = "6655";
string str = "";
string str2 = "";
HttpClient client = new HttpClient();
string json = JsonConvert.SerializeObject(table);
StringContent httpContent = new StringContent(json, System.Text.Encoding.UTF8, "application/json");
var response = await client.PostAsync("http://YourSite.com/api/apiTables", httpContent);
str = "" + response.Content + " : " + response.StatusCode;
if (response.IsSuccessStatusCode)
{
str2 = "Data Posted";
}
return View();
}
Please read and strongly consider my advice in the comments of your post. That being said, if you still have a good reason to do this, check out this list of crypto modules for Node. It has modules for dealing with both sha1 and base64.
In my case I received this error when I misspelled the module name of the library (dependency) in build.gradle
file.
So remember to check if the name of the module is correct.
build.gradle
dependencies {
compile project(':module-name-of-the-library')
}
Difference between split and partition is split returns the list without delimiter and will split where ever it gets delimiter in string i.e.
x = 'http://test.com/lalala-134-431'
a,b,c = x.split(-)
print(a)
"http://test.com/lalala"
print(b)
"134"
print(c)
"431"
and partition will divide the string with only first delimiter and will only return 3 values in list
x = 'http://test.com/lalala-134-431'
a,b,c = x.partition('-')
print(a)
"http://test.com/lalala"
print(b)
"-"
print(c)
"134-431"
so as you want last value you can use rpartition it works in same way but it will find delimiter from end of string
x = 'http://test.com/lalala-134-431'
a,b,c = x.partition('-')
print(a)
"http://test.com/lalala-134"
print(b)
"-"
print(c)
"431"
a simpler solution based on this answer:
public static String prettyFormat(String input, int indent) {
try {
Source xmlInput = new StreamSource(new StringReader(input));
StringWriter stringWriter = new StringWriter();
StreamResult xmlOutput = new StreamResult(stringWriter);
TransformerFactory transformerFactory = TransformerFactory.newInstance();
transformerFactory.setAttribute("indent-number", indent);
Transformer transformer = transformerFactory.newTransformer();
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
transformer.transform(xmlInput, xmlOutput);
return xmlOutput.getWriter().toString();
} catch (Exception e) {
throw new RuntimeException(e); // simple exception handling, please review it
}
}
public static String prettyFormat(String input) {
return prettyFormat(input, 2);
}
testcase:
prettyFormat("<root><child>aaa</child><child/></root>");
returns:
<?xml version="1.0" encoding="UTF-8"?>
<root>
<child>aaa</child>
<child/>
</root>
The above solution left blue border around each cell in my case.
This is the solution that worked for me. It is very simple, just add this to your DataGrid
. You can change it from a SolidColorBrush
to any other brush such as linear gradient.
<DataGrid.Resources>
<SolidColorBrush x:Key="{x:Static SystemColors.HighlightBrushKey}"
Color="#FF0000"/>
</DataGrid.Resources>
You can easily restart your MySql service. This kicks the error off.
The port 8005 is used as service port. You can send a shutdown command (a configurable password) to that port. It will not "speak" HTTP, so you cannot use your browser to connect.
The default port for delivering web-content is 8080.
But there may be other applications listen to that port. So your tomcat may not start, if the port is not available.
You asked "How do you know, if tomcat server is installed on your PC?". The answer to that question is: You can't
You can't determine, if it is installed, because it may be only extracted from a ZIP archive or packaged within another application (Like JBoss AS (I think)).
You can list all the available timezones with pytz.all_timezones
:
In [40]: import pytz
In [41]: pytz.all_timezones
Out[42]:
['Africa/Abidjan',
'Africa/Accra',
'Africa/Addis_Ababa',
...]
There is also pytz.common_timezones
:
In [45]: len(pytz.common_timezones)
Out[45]: 403
In [46]: len(pytz.all_timezones)
Out[46]: 563
I think the project you are looking for is: https://github.com/sarxos/webcam-capture (I'm the author)
There is an example working exactly as you've described - after it's run, the window appear where, after you press "Start" button, you can see live image from webcam device and save it to file after you click on "Snapshot" (source code available, please note that FPS counter in the corner can be disabled):
The project is portable (WinXP, Win7, Win8, Linux, Mac, Raspberry Pi) and does not require any additional software to be installed on the PC.
API is really nice and easy to learn. Example how to capture single image and save it to PNG file:
Webcam webcam = Webcam.getDefault();
webcam.open();
ImageIO.write(webcam.getImage(), "PNG", new File("test.png"));
Here is your answer. use
jquery.json-2.2.min.js
and
jquery-1.8.3.min.js
Javascript :
function CallAddToCart(eitemId, equantity) {
var itemId = Number(eitemId);
var quantity = equantity;
var dataValue = "{itemId:'" + itemId+ "', quantity :'"+ quantity "'}" ;
$.ajax({
url: "AddToCart.aspx/AddTo_Cart",
type: "POST",
dataType: "json",
data: dataValue,
contentType: "application/json; charset=utf-8",
success: function (msg) {
alert("Success");
},
error: function () { alert(arguments[2]); }
});
}
and your C# web method should be
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public static string AddTo_Cart(int itemId, string quantity)
{
SpiritsShared.ShoppingCart.AddItem(itemId, quantity);
return "Item Added Successfully";
}
From any of the button click
or any other html control event
you can call to the javascript
method with the parameter which in turn calls to the webmethod
to get the value in json
format.
Although this is not exactly what OP meant as this is not super simple, however, when running scripts from Notepad++ the os.getcwd()
method doesn't work as expected. This is what I would do:
import os
# get real current directory (determined by the file location)
curDir, _ = os.path.split(os.path.abspath(__file__))
print(curDir) # print current directory
Define a function like this:
def dir_up(path,n): # here 'path' is your path, 'n' is number of dirs up you want to go
for _ in range(n):
path = dir_up(path.rpartition("\\")[0], 0) # second argument equal '0' ensures that
# the function iterates proper number of times
return(path)
The use of this function is fairly simple - all you need is your path and number of directories up.
print(dir_up(curDir,3)) # print 3 directories above the current one
The only minus is that it doesn't stop on drive letter, it just will show you empty string.
HTMLUNIT is the package if you're a java developer. http://htmlunit.sourceforge.net/apidocs/index.html
The previous answers are correct but remember to use the name attribute in the input fields (html form) or you won't get anything. Example:
<input type="text" id="username" /> <!-- won't work -->
<input type="text" name="username" /> <!-- will work -->
<input type="text" name="username" id="username" /> <!-- will work too -->
All this code is HTML valid, but using getParameter(java.lang.String) you will need the name attribute been set in all parameters you want to receive.
If you're fetching data using Wordpress, then you can access the number of rows returned using $wpdb->num_rows:
$wpdb->get_results( $wpdb->prepare('select * from mytable where foo = %s', $searchstring));
echo $wpdb->num_rows;
If you want a specific count based on a mysql count query then you do this:
$numrows = $wpdb->get_var($wpdb->prepare('SELECT COUNT(*) FROM mytable where foo = %s', $searchstring );
echo $numrows;
If you're running updates or deletes then the count of rows affected is returned directly from the function call:
$numrowsaffected = $wpdb->query($wpdb->prepare(
'update mytable set val=%s where myid = %d', $valuetoupdate, $myid));
This applies also to $wpdb->update and $wpdb->delete.
Assuming you are using an auto-incrementing primary key, which is the normal way to do things, then you can access the key value of the last row you put into the database with:
$userID = mysqli_insert_id($link);
otherwise, you'll have to know more specifics about the row you are trying to find, such as email address. Without knowing your table structure, we can't be more specific.
Either way, to limit your SELECT
query, use a WHERE
statement like this:
(Generic Example)
$getID = mysqli_fetch_assoc(mysqli_query($link, "SELECT userID FROM users WHERE something = 'unique'"));
$userID = $getID['userID'];
(Specific example) Or a more specific example:
$getID = mysqli_fetch_assoc(mysqli_query($link, "SELECT userID FROM users WHERE userID = 1"));
$userID = $getID['userID'];
You can just check if the jQuery
object exists:
if( typeof jQuery !== 'undefined' ) ... // jQuery loaded
jQuery().jquery
has the version number.
As for the prefix, jQuery
should always work. If you want to use $
you can wrap your code to a function and pass jQuery
to it as the parameter:
(function( $ ) {
$( '.class' ).doSomething(); // works always
})( jQuery )
Better would have been generate url like
app.dev/backend?type=surveys&id=2
and then use
var type=$location.search().type;
var id=$location.search().id;
and inject $location in controller.
You want to add libraries to your project and in doing so you have two options as you yourself identified:
Compile-time libraries are libraries which is needed to compile your application. They are not included when your application is assembled (e.g., into a war-file). Libraries of this kind must be provided by the container running your project.
This is useful in situation when you want to vary API and implementation, or when the library is supplied by the container (which is typically the case with javax.servlet which is required to compile but provided by the application server, e.g., Apache Tomcat).
Run-time libraries are libraries which is needed both for compilation and when running your project. This is probably what you want in most cases. If for instance your project is packaged into a war/ear, then these libraries will be included in the package.
As for the other alernatives you have either global libraries using Library Manager
or jdk libraries. The latter is simply your regular java libraries, while the former is just a way for your to store a set of libraries under a common name. For all your future projects, instead of manually assigning the libraries you can simply select to import them from your Library Manager
.
if you are add jre and jkd path, remove jre install path, keep jdk path is work
I have had this issue before, you need more than the standard 755
or 644
permission to store the $_SESSION
information. You need to be able to write to that file as that is how it remembers.
Just a remind: I tried to work with idea and imported maven, and encountered the same problem, I have tried all the solutions and they didnt work. Finally, I found out it was because of the root access... I opened idea with administrator access and all things work just fine, hope you not as silly as i am...
If you have a compiler that supports C99 you can
#include <stdbool.h>
Otherwise, you can define your own if you'd like. Depending on how you want to use it (and whether you want to be able to compile your code as C++), your implementation could be as simple as:
#define bool int
#define true 1
#define false 0
In my opinion, though, you may as well just use int
and use zero to mean false and nonzero to mean true. That's how it's usually done in C.
setSize
will resize the component to the specified size.
setPreferredSize
sets the preferred size. The component may not actually be this size depending on the size of the container it's in, or if the user re-sized the component manually.
In Android Studio 3.5.3, the Device File Explorer can be found in View -> Tool Windows.
It can also be opened using the vertical tabs on the right-hand side of the main window.
.m2 directory on linux box usually would be $HOME/.m2
you could get the $HOME :
echo $HOME
or simply:
cd <enter>
to go to your home directory.
other information from maven site: http://maven.apache.org/download.html#Installation
No, because that would open up the floodgates for phishing. The only part of the URI you can change is the fragment (everything after the #
). You can do so by setting window.location.hash
.
I know this is an old thread, but I landed here when my row deletes were blocked by foreign key constraints. In my case, my table design permitted "NULL" values in the constrained column. In the rows to be deleted, I changed the constrained column value to "NULL" (which does not violate the Foreign Key Constraint) and then deleted all the rows.
i think it will depend on many things - run EXPLAIN PLAN
on each one to see what your optimizer selects. Otherwise - as @rayman suggests - run them both and time them.
Most answers here either require a clean working directory and multiple interactive steps (bad for scripting), or don't work for all cases, e.g. past merges which already bring some of the outstanding changes into your target branch, or cherry-picks doing the same.
To truly see what would change in the master
branch if you merged develop
into it, right now:
git merge-tree $(git merge-base master develop) master develop
As it's a plumbing command, it does not guess what you mean, you have to be explicit. It also doesn't colorize the output or use your pager, so the full command would be:
git merge-tree $(git merge-base master develop) master develop | colordiff | less -R
— https://git.seveas.net/previewing-a-merge-result.html
(thanks to David Normington for the link)
P.S.:
If you would get merge conflicts, they will show up with the usual conflict markers in the output, e.g.:
$ git merge-tree $(git merge-base a b ) a b
added in both
our 100644 78981922613b2afb6025042ff6bd878ac1994e85 a
their 100644 61780798228d17af2d34fce4cfbdf35556832472 a
@@ -1 +1,5 @@
+<<<<<<< .our
a
+=======
+b
+>>>>>>> .their
User @dreftymac makes a good point: this makes it unsuitable for scripting, because you can't easily catch that from the status code. The conflict markers can be quite different depending on circumstance (deleted vs modified, etc), which makes it hard to grep, too. Beware.
Try this
To Remove Hand Cursor
a.link {
cursor: default;
}
I got the same issue and after a lot of time spent on the search I found the solution
Just change your method especially // DownloadsProvider part
getpath()
to
@SuppressLint("NewApi") public static String getPath(final Context context, final Uri uri) {
final boolean isKitKat = Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT;
// DocumentProvider
if (isKitKat && DocumentsContract.isDocumentUri(context, uri)) {
// ExternalStorageProvider
if (isExternalStorageDocument(uri)) {
final String docId = DocumentsContract.getDocumentId(uri);
final String[] split = docId.split(":");
final String type = split[0];
// This is for checking Main Memory
if ("primary".equalsIgnoreCase(type)) {
if (split.length > 1) {
return Environment.getExternalStorageDirectory() + "/" + split[1];
} else {
return Environment.getExternalStorageDirectory() + "/";
}
// This is for checking SD Card
} else {
return "storage" + "/" + docId.replace(":", "/");
}
}
// DownloadsProvider
else if (isDownloadsDocument(uri)) {
String fileName = getFilePath(context, uri);
if (fileName != null) {
return Environment.getExternalStorageDirectory().toString() + "/Download/" + fileName;
}
String id = DocumentsContract.getDocumentId(uri);
if (id.startsWith("raw:")) {
id = id.replaceFirst("raw:", "");
File file = new File(id);
if (file.exists())
return id;
}
final Uri contentUri = ContentUris.withAppendedId(Uri.parse("content://downloads/public_downloads"), Long.valueOf(id));
return getDataColumn(context, contentUri, null, null);
}
// MediaProvider
else if (isMediaDocument(uri)) {
final String docId = DocumentsContract.getDocumentId(uri);
final String[] split = docId.split(":");
final String type = split[0];
Uri contentUri = null;
if ("image".equals(type)) {
contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
} else if ("video".equals(type)) {
contentUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
} else if ("audio".equals(type)) {
contentUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
}
final String selection = "_id=?";
final String[] selectionArgs = new String[]{
split[1]
};
return getDataColumn(context, contentUri, selection, selectionArgs);
}
}
// MediaStore (and general)
else if ("content".equalsIgnoreCase(uri.getScheme())) {
// Return the remote address
if (isGooglePhotosUri(uri))
return uri.getLastPathSegment();
return getDataColumn(context, uri, null, null);
}
// File
else if ("file".equalsIgnoreCase(uri.getScheme())) {
return uri.getPath();
}
return null;
}
For more solution click on the link here
https://gist.github.com/HBiSoft/15899990b8cd0723c3a894c1636550a8
I hope will do the same for you!
If you are trying to reference an android style, you need to put "android:" in there
android:theme="@android:style/Theme.Black"
If that doesn't solve it, you may need to edit your question with the full manifest file, so we can see more details
Use the "$" on a reg expression to match the end of the string
$string = 'The quick brown fox jumps over the lazy fox';
echo preg_replace('/fox$/', 'dog', $string);
//output
'The quick brown fox jumps over the lazy dog'
It sounds like you need an OR instead:
<button type="submit" [disabled]="!validate || !SAForm.valid">Add</button>
This will disable the button if not validate or if not SAForm.valid.
In mechanical terms a COMMIT makes a transaction. That is, a transaction is all the activity (one or more DML statements) which occurs between two COMMIT statements (or ROLLBACK).
In Oracle a DDL statement is a transaction in its own right simply because an implicit COMMIT is issued before the statement is executed and again afterwards. TRUNCATE is a DDL command so it doesn't need an explicit commit because calling it executes an implicit commit.
From a system design perspective a transaction is a business unit of work. It might consist of a single DML statement or several of them. It doesn't matter: only full transactions require COMMIT. It literally does not make sense to issue a COMMIT unless or until we have completed a whole business unit of work.
This is a key concept. COMMITs don't just release locks. In Oracle they also release latches, such as the Interested Transaction List. This has an impact because of Oracle's read consistency model. Exceptions such as ORA-01555: SNAPSHOT TOO OLD
or ORA-01002: FETCH OUT OF SEQUENCE
occur because of inappropriate commits. Consequently, it is crucial for our transactions to hang onto locks for as long as they need them.
I installed System.Configuration.ConfigurationManager
from Nuget into my .net core 2.2 application.
I then reference using System.Configuration;
Next, I changed
WebConfigurationManager.AppSettings
to ..
ConfigurationManager.AppSettings
So far I believe this is correct. 4.5.0 is typical with .net core 2.2
I have not had any issues with this.
Try this command to solve your problem.
sudo apt install build-essential python3-dev libqt4-dev
This works for me in python3.
You can try to use pandoc
as your converter. Here's a jekyll plugin to implement this. Pandoc will be able to add a figure caption the same as your alt
attribute automatically.
But you have to push the compiled site because github doesn't allow plugins in Github pages for security.
I honestly suggest that you use moment.js. Just download moment.min.js
and then use this snippet to get your date in whatever format you want:
<script>
$(document).ready(function() {
// set an element
$("#date").val( moment().format('MMM D, YYYY') );
// set a variable
var today = moment().format('D MMM, YYYY');
});
</script>
Use following chart for date formats:
If your using Visual Studio just run the application with Crtl + F5 instead of F5. This will leave the console open when it's finished executing.
The simple solution to this would be to find phpmyadmin.conf file and then find below code inside it,
<Directory "c:/wamp/apps/phpmyadmin3.5.1/">
Options Indexes FollowSymLinks MultiViews
AllowOverride all
Order Deny,Allow
Deny from all
Allow from 127.0.0.1
</Directory>
Change "Deny from all" to "Allow from all".
OR
Follow below link to get better understanding on how to do it,
WAMP says Forbidden You don't have permission to access /phpmyadmin/ on this server Windows 7 or 8
Enjoy :)
Pasting the jar files in WebContent\WEB-INF\lib via the file system was the only way it worked for me.
They then appeared under the Deployed Resources and WebContent lib sub-folders.
When I looked, the build path had the jars in the Web App Libraries and everything built and ran fine.
May I remind everybody that the question was:
I'd like to use a single image as both a regular favicon and iPhone/iPad friendly favicon? Is this possible? Would an iPad-friendly 72x72 PNG scale if linked to as a regular browser favicon? Or do I have to use a separate 16x16 or 32x32 image?
The answer is: YES, that is possible! YES, it will be scaled. NO, you do not need a 'regular browser favicon'. Please look at this answer: https://stackoverflow.com/a/48646940/2397550
If you are using Maven, add the below config in your pom.xml:
<build>
<testResources>
<testResource>
<directory>src/main/webapp</directory>
</testResource>
</testResources>
</build>
With this config, you will be able to access xml files in WEB-INF folder. From Maven POM Reference: The testResources element block contains testResource elements. Their definitions are similar to resource elements, but are naturally used during test phases.
If we have a dropdown with a title of "Data Classification":
<select title="Data Classification">
<option value="Top Secret">Top Secret</option>
<option value="Secret">Secret</option>
<option value="Confidential">Confidential</option>
</select>
We can get it into a variable:
var dataClsField = $('select[title="Data Classification"]');
Then put into another variable the value we want the dropdown to have:
var myValue = "Top Secret"; // this would have been "2" in your example
Then we can use the field we put into dataClsField
, do a find for myValue
and make it selected using .prop()
:
dataClsField.find('option[value="'+ myValue +'"]').prop('selected', 'selected');
Or, you could just use .val()
, but your selector of .
can only be used if it matches a class on the dropdown, and you should use quotes on the value inside the parenthesis, or just use the variable we set earlier:
dataClsField.val(myValue);
**The simplest way to drop and recreate a stored proc in T-Sql is **
Use DatabaseName
go
If Object_Id('schema.storedprocname') is not null
begin
drop procedure schema.storedprocname
end
go
create procedure schema.storedprocname
as
begin
end
<div id="OK1" runat="server" style ="display:none" >
<asp:DropDownList ID="DropDownList2" runat="server"></asp:DropDownList>
</div>
vb.net code
Protected Sub DropDownList1_SelectedIndexChanged(sender As Object, e As EventArgs) Handles DropDownList1.SelectedIndexChanged
If DropDownList1.SelectedIndex = 0 Then
OK1.Style.Add("display", "none")
Else
OK1.Style.Add("display", "block")
End If
End Sub
As of 2015, it now just works.
<input type="file">
This will ask user for the upload of any file. On iOS 8.x this can be a camera video, camera photo, or a photo/video from Photo Library.
<input type="file" accept="image/*">
This is as above, but limits the uploads to photos only from camera or library, no videos.
To guarantee the correct order for each array of Keys and Values, use this (the other answers use individual Set
s which offer no guarantee as to order.
Map<String, Object> map = new HashMap<String, Object>();
String[] keys = new String[map.size()];
Object[] values = new Object[map.size()];
int index = 0;
for (Map.Entry<String, Object> mapEntry : map.entrySet()) {
keys[index] = mapEntry.getKey();
values[index] = mapEntry.getValue();
index++;
}
Connect your javascript clientside controller and php serverside controller using sending and receiving opcodes with binded data. So your php code can send as response functional delta for js recepient/listener
see https://github.com/ArtNazarov/LazyJs
Sorry for my bad English
I'm using
Sheet1.Range("E2", "E3000").NumberFormat = "dd/mm/yyyy hh:mm:ss"
to format a column
So I guess
Sheet1.Range("E2", "E3000").NumberFormat = "MMM dd yyyy"
would do the trick for you.
More: NumberFormat function.
Since PostgreSQL 9.4 there's the FILTER
clause, which allows for a very concise query to count the true values:
select count(*) filter (where myCol)
from tbl;
The above query is a bad example in that a simple WHERE clause would suffice, and is for demonstrating the syntax only. Where the FILTER clause shines is that it is easy to combine with other aggregates:
select count(*), -- all
count(myCol), -- non null
count(*) filter (where myCol) -- true
from tbl;
The clause is especially handy for aggregates on a column that uses another column as the predicate, while allowing to fetch differently filtered aggregates in a single query:
select count(*),
sum(otherCol) filter (where myCol)
from tbl;
Add up to Dmitry's answer, if you don't want to handle unique key IDs manually, you can use React.Children.toArray
as proposed in the React documentation
React.Children.toArray
Returns the children opaque data structure as a flat array with keys assigned to each child. Useful if you want to manipulate collections of children in your render methods, especially if you want to reorder or slice this.props.children before passing it down.
Note:
React.Children.toArray()
changes keys to preserve the semantics of nested arrays when flattening lists of children. That is, toArray prefixes each key in the returned array so that each element’s key is scoped to the input array containing it.
<div>
<ul>
{
React.Children.toArray(
this.state.data.map((item, i) => <li>Test</li>)
)
}
</ul>
</div>
In addition to Tom Blodget's response, you may simply add @HtmlBeginForm as the form action, like this:
<form id="form" method="post" action="@Html.BeginForm("action", "controller", FormMethod.Post, new { onsubmit = "this.querySelectorAll('input').forEach(i => i.disabled = false)" })"
A connection timeout is the maximum amount of time that the program is willing to wait to setup a connection to another process. You aren't getting or posting any application data at this point, just establishing the connection, itself.
A socket timeout is the timeout when waiting for individual packets. It's a common misconception that a socket timeout is the timeout to receive the full response. So if you have a socket timeout of 1 second, and a response comprised of 3 IP packets, where each response packet takes 0.9 seconds to arrive, for a total response time of 2.7 seconds, then there will be no timeout.
String text = "text";
text += new String(" ");
A simple way is to make your own log collector methods or even just an existing log collector app from the market.
For my apps I made a report functionality which sends the logs to my email (or even to another place - once you get the log you can do whether you want with it).
Here is a simple example about how to get the log file from a device:
try
Calendar c = Calendar.getInstance(); // this takes current date
c.set(Calendar.DAY_OF_MONTH, 1);
System.out.println(c.getTime()); // this returns java.util.Date
Updated (Since Java 8):
import java.time.LocalDate;
LocalDate todaydate = LocalDate.now();
System.out.println("Months first date in yyyy-mm-dd: " +todaydate.withDayOfMonth(1));
If you need to pass UUID for a primary key for your model or unique field then below code returns the UUID object -
import uuid
uuid.uuid4()
If you need to pass UUID as a parameter for URL you can do like below code -
import uuid
str(uuid.uuid4())
If you want the hex value for a UUID you can do the below one -
import uuid
uuid.uuid4().hex
<ToggleButton
android:id="@+id/togglebutton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textOn="Vibrate on"
android:textOff="Vibrate off"
android:onClick="onToggleClicked"/>
Within the Activity that hosts this layout, the following method handles the click event:
public void onToggleClicked(View view) {
// Is the toggle on?
boolean on = ((ToggleButton) view).isChecked();
if (on) {
// Enable vibrate
} else {
// Disable vibrate
}
}
Looks like the data has the same columns, so you can:
df1 = pd.DataFrame(data1)
df2 = pd.DataFrame(data2)
merged_df = pd.concat([df1, df2])
$(document).ready(function () {
var someObj = {};
$("#checkAll").click(function () {
$('.chk').prop('checked', this.checked);
});
$(".chk").click(function () {
$("#checkAll").prop('checked', ($('.chk:checked').length == $('.chk').length) ? true : false);
});
$("input:checkbox").change(function () {
debugger;
someObj.elementChecked = [];
$("input:checkbox").each(function () {
if ($(this).is(":checked")) {
someObj.elementChecked.push($(this).attr("id"));
}
});
});
$("#button").click(function () {
debugger;
alert(someObj.elementChecked);
});
});
</script>
</head>
<body>
<ul class="chkAry">
<li><input type="checkbox" id="checkAll" />Select All</li>
<li><input class="chk" type="checkbox" id="Delhi">Delhi</li>
<li><input class="chk" type="checkbox" id="Pune">Pune</li>
<li><input class="chk" type="checkbox" id="Goa">Goa</li>
<li><input class="chk" type="checkbox" id="Haryana">Haryana</li>
<li><input class="chk" type="checkbox" id="Mohali">Mohali</li>
</ul>
<input type="button" id="button" value="Get" />
</body>
You can also overcome this problem with
git mergetool
which causes git
to create local copies of the conflicted binary and spawn your default editor on them:
{conflicted}.HEAD
{conflicted}
{conflicted}.REMOTE
Obviously you can't usefully edit binaries files in a text editor. Instead you copy the new {conflicted}.REMOTE
file over {conflicted}
without closing the editor. Then when you do close the editor git
will see that the undecorated working-copy has been changed and your merge conflict is resolved in the usual way.
Ranges from -9,223,372,036,854,775,808 to +9,223,372,036,854,775,807.
It will start from -9,223,372,036,854,775,808
Long.MIN_VALUE.
This might be a very late reply but I hope it helps someone.
Note(If you are using point 2) : While setting alpha to the background, it will blur the whole layout. To avoid this, create a new xml containing drawable and set alpha here to 0.5 (or value of your wish) and use this drawable name (name of file) as the background.
For example, use it as below (say file name is bgndblur.xml):
<bitmap xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:shape="rectangle"
android:src="@drawable/registerscreenbackground"
android:alpha="0.5">
Use the below in your layout :
<....
android:background="@drawable/bgndblur">
Hope this helped.
Using the Promise pattern:
function getImage(url){
return new Promise(function(resolve, reject){
var img = new Image()
img.onload = function(){
resolve(url)
}
img.onerror = function(){
reject(url)
}
img.src = url
})
}
And when calling the function we can handle its response or error quite neatly.
getImage('imgUrl').then(function(successUrl){
//do stufff
}).catch(function(errorUrl){
//do stuff
})
Here's a bat file I wrote to execute all SQL scripts in a folder:
REM ******************************************************************
REM Runs all *.sql scripts sorted by filename in the current folder.
REM To use integrated auth change -U <user> -P <password> to -E
REM ******************************************************************
dir /B /O:n *.sql > RunSqlScripts.tmp
for /F %%A in (RunSqlScripts.tmp) do osql -S (local) -d DEFAULT_DATABASE_NAME -U USERNAME_GOES_HERE -P PASSWORD_GOES_HERE -i %%A
del RunSqlScripts.tmp
say easily http://www.google.com/maps/place/lat,lng
format
sample url:
Here's a new automated tool, JSNice, to try to deobfuscate/deminify it. The tool even tries to guess the variable names, which is unbelievably cool. (It mines Javascript on github for this purpose.)
The usage info:
Usage: brew switch <formula> <version>
Example:
brew switch mysql 5.5.29
You can find the versions installed on your system with info
.
brew info mysql
And to see the available versions to install, you can provide a dud version number, as brew will helpfully respond with the available version numbers:
brew switch mysql 0
Update (15.10.2014):
The brew versions
command has been removed from brew, but, if you do wish to use this command first run brew tap homebrew/boneyard
.
The recommended way to install an old version is to install from the homebrew/versions
repo as follows:
$ brew tap homebrew/versions
$ brew install mysql55
For detailed info on all the ways to install an older version of a formula read this answer.
Try (maybe as root)
lsof -i -P
and grep the output for the port you are looking for.
For example to check for port 80 do
lsof -i -P | grep :80
Since you said "Solutions for other languages are also welcome", here's the version for Python:
>>> import random
>>> random.choice([1,2,3,4,5,6])
3
>>> random.choice([1,2,3,4,5,6])
4
Please try the following code
Uri.fromFile(new File("/sdcard/sample.jpg"))
After struggling with this for a few days, it turns out that you can't do a window.location.reload() after a window.history.go(-2)
, because the code stops running after the window.history.go(-2)
. Also the html spec basically views a history.go(-2)
to the the same as hitting the back button and should retrieve the page as it was instead of as it now may be. There was some talk of setting caching headers in the webserver to turn off caching but I did not want to do this.
The solution for me was to use session storage to set a flag in the browser with sessionStorage.setItem('refresh', 'true');
Then in the "theme" or the next page that needs to be refreshed do:
if (sessionStorage.getItem("refresh") == "true") {
sessionStorage.removeItem("refresh"); window.location.reload()
}
So basically tell it to reload in the sessionStorage then check for that at the top of the page that needs to be reloaded.
Hope this helps someone with this bit of frustration.
When you use git push origin :staleStuff
, it automatically removes origin/staleStuff
, so when you ran git remote prune origin
, you have pruned some branch that was removed by someone else. It's more likely that your co-workers now need to run git prune
to get rid of branches you have removed.
So what exactly git remote prune
does? Main idea: local branches (not tracking branches) are not touched by git remote prune
command and should be removed manually.
Now, a real-world example for better understanding:
You have a remote repository with 2 branches: master
and feature
. Let's assume that you are working on both branches, so as a result you have these references in your local repository (full reference names are given to avoid any confusion):
refs/heads/master
(short name master
)refs/heads/feature
(short name feature
)refs/remotes/origin/master
(short name origin/master
)refs/remotes/origin/feature
(short name origin/feature
)Now, a typical scenario:
feature
, merges it into master
and removes feature
branch from remote repository.git fetch
(or git pull
), no references are removed from your local repository, so you still have all those 4 references.git remote prune origin
.feature
branch no longer exists, so refs/remotes/origin/feature
is a stale branch which should be removed. refs/heads/feature
, because git remote prune
does not remove any refs/heads/*
references.It is possible to identify local branches, associated with remote tracking branches, by branch.<branch_name>.merge
configuration parameter. This parameter is not really required for anything to work (probably except git pull
), so it might be missing.
(updated with example & useful info from comments)
This will print the full path of all files in the given directory, you can also pass other callback functions to recursiveDir.
function printFunc($path){
echo $path."<br>";
}
function recursiveDir($path, $fileFunc, $dirFunc){
$openDir = opendir($path);
while (($file = readdir($openDir)) !== false) {
$fullFilePath = realpath("$path/$file");
if ($file[0] != ".") {
if (is_file($fullFilePath)){
if (is_callable($fileFunc)){
$fileFunc($fullFilePath);
}
} else {
if (is_callable($dirFunc)){
$dirFunc($fullFilePath);
}
recursiveDir($fullFilePath, $fileFunc, $dirFunc);
}
}
}
}
recursiveDir($dirToScan, 'printFunc', 'printFunc');
By using the constraint definition on table creation, you can specify one or multiple constraints that span multiple columns. The syntax, simplified from technet's documentation, is in the form of:
CONSTRAINT constraint_name UNIQUE [ CLUSTERED | NONCLUSTERED ]
(
column [ ASC | DESC ] [ ,...n ]
)
Therefore, the resuting table definition would be:
CREATE TABLE [dbo].[user](
[userID] [int] IDENTITY(1,1) NOT NULL,
[fcode] [int] NULL,
[scode] [int] NULL,
[dcode] [int] NULL,
[name] [nvarchar](50) NULL,
[address] [nvarchar](50) NULL,
CONSTRAINT [PK_user_1] PRIMARY KEY CLUSTERED
(
[userID] ASC
),
CONSTRAINT [UQ_codes] UNIQUE NONCLUSTERED
(
[fcode], [scode], [dcode]
)
) ON [PRIMARY]
Place the following in your jQuery mouseover
event handler:
$(this).css('color', 'red');
To set both color and size at the same time:
$(this).css({ 'color': 'red', 'font-size': '150%' });
You can set any CSS attribute using the .css()
jQuery function.
Couldnt get the TEXT() formula to work
Easiest solution was to copy paste into Notepad and back into Excel with the column set to Text before pasting back
Or you can do the same with a formula like this
=DAY(A2)&"/"&MONTH(A2)&"/"&YEAR(A2)& " "&HOUR(B2)&":"&MINUTE(B2)&":"&SECOND(B2)
Found the simple official way after wading through the walls of text above that would make you think there is none.
Create a complete bundle with:
$ git bundle create <filename> --all
Restore it with:
$ git clone <filename> <folder>
This operation is atomic AFAIK. Check official docs for the gritty details.
Regarding "zip": git bundles are compressed and surprisingly small compared to the .git folder size.
Try this style instead, it modifies the template itself. In there you can change everything you need to transparent:
<Style TargetType="{x:Type TabItem}">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type TabItem}">
<Grid>
<Border Name="Border" Margin="0,0,0,0" Background="Transparent"
BorderBrush="Black" BorderThickness="1,1,1,1" CornerRadius="5">
<ContentPresenter x:Name="ContentSite" VerticalAlignment="Center"
HorizontalAlignment="Center"
ContentSource="Header" Margin="12,2,12,2"
RecognizesAccessKey="True">
<ContentPresenter.LayoutTransform>
<RotateTransform Angle="270" />
</ContentPresenter.LayoutTransform>
</ContentPresenter>
</Border>
</Grid>
<ControlTemplate.Triggers>
<Trigger Property="IsSelected" Value="True">
<Setter Property="Panel.ZIndex" Value="100" />
<Setter TargetName="Border" Property="Background" Value="Red" />
<Setter TargetName="Border" Property="BorderThickness" Value="1,1,1,0" />
</Trigger>
<Trigger Property="IsEnabled" Value="False">
<Setter TargetName="Border" Property="Background" Value="DarkRed" />
<Setter TargetName="Border" Property="BorderBrush" Value="Black" />
<Setter Property="Foreground" Value="DarkGray" />
</Trigger>
</ControlTemplate.Triggers>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
Whenever you create or update
package name
Make sure your package name is exactly the same [Upper case and lower case matters]
Do below step.
1). Check applicationId
in App level gradle
file,
2). Check package_name
in your google-services.json
file,
3). Check package
in your AndroidManifest
file
and for full confirmation make sure that your working package directory name i.e.("com.example.app") is also the same.
EDIT [ Any one who is facing this issue in
productFlavour
scenario, go check out Droid Chris's Solution ]
Use array_values
to reset keys
foreach($input as &$val) {
$val = array_values($val);
}
Well, the first and second both generate something like the third in the end. However, don't use the third when you have a syntax for properties.
Finally, if you have no work to do in the get
or set
, then use the first.
In the end, the first and second are just some form of syntactic sugar, but why code more than what's necessary.
// more code == more bugs
And just to have a little fun, consider this:
public string A { get; private set; }
Now that's a lot more straight forward isn't it? The public
modifier is implied on both the get
and the set
, but it can be overriden. This would of course be the same rule for any modifier used when defining the property itself.
Is there a name to describe this idiom?
There is no name for this usage, it is simply known as "Reference as class member".
I am assuming it is to prevent the possibly large overhead of copying a big complex object?
Yes and also scenarios where you want to associate the lifetime of one object with another object.
Is this generally good practice? Are there any pitfalls to this approach?
Depends on your usage. Using any language feature is like "choosing horses for courses". It is important to note that every (almost all) language feature exists because it is useful in some scenario.
There are a few important points to note when using references as class members:
operator=()
and you will have to provide one yourself. It is cumbersome to determine what action your =
operator shall take in such a case. So basically your class becomes non-assignable. NULL
or made to refer any other object. If you need reseating, then it is not possible with a reference as in case of a pointer.For most practical purposes (unless you are really concerned of high memory usage due to member size) just having a member instance, instead of pointer or reference member should suffice. This saves you a whole lot of worrying about other problems which reference/pointer members bring along though at expense of extra memory usage.
If you must use a pointer, make sure you use a smart pointer instead of a raw pointer. That would make your life much easier with pointers.
Sort the array into ascending order then assign a variable to the (n-1)th term.
Assuming you have two programs that process the two files, process_in.exe and process_out.exe:
for %%f in (*.in) do (
echo %%~nf
process_in "%%~nf.in"
process_out "%%~nf.out"
)
%%~nf is a substitution modifier, that expands %f to a file name only. See other modifiers in https://technet.microsoft.com/en-us/library/bb490909.aspx (midway down the page) or just in the next answer.
try {
} catch (javax.script.ScriptException ex) {
// System.out.println(ex.getMessage());
}