f=/home/cox/myapp.apk #or $1 if input from terminal.
#backup env var
backup=$LD_LIBRARY_PATH
LD_LIBRARY_PATH=/vendor/lib:/system/lib
myTemp=/sdcard/temp.apk
adb push $f $myTemp
adb shell pm install -r $myTemp
#restore env var
LD_LIBRARY_PATH=$backup
This works for me. I run this on ubuntu 12.04, on shell terminal.
When you scheduled task, just select "Run whether user is logged on or not" under the "General" tab.
Alternate way is to let the task run as another user.
I am pretty new to all of this, but I found that if the script is started via CScript.exe (console scripting host) there is no window popping up on exec(): so when running:
cscript myscript.vbs //nologo
any .Exec() calls in the myscript.vbs do not open an extra window, meaning that you can use the first variant of your original solution (using exec).
(Note that the two forward slashes in the above code are intentional, see cscript /?)
A solution for me:
$old_ErrorActionPreference = $ErrorActionPreference
$ErrorActionPreference = 'SilentlyContinue'
if((Get-PSSessionConfiguration -Name "MyShellUri" -ErrorAction SilentlyContinue) -eq $null) {
WriteTraceForTrans "The session configuration MyShellUri is already unregistered."
}
else {
#Unregister-PSSessionConfiguration -Name "MyShellUri" -Force -ErrorAction Ignore
}
$ErrorActionPreference = $old_ErrorActionPreference
Or use try-catch
try {
(Get-PSSessionConfiguration -Name "MyShellUri" -ErrorAction SilentlyContinue)
}
catch {
}
Update
From v0.24.0 onwards, you can merge on DataFrame and Series as long as the Series is named.
df.merge(s.rename('new'), left_index=True, right_index=True)
# If series is already named,
# df.merge(s, left_index=True, right_index=True)
Nowadays, you can simply convert the Series to a DataFrame with to_frame(). So (if joining on index):
df.merge(s.to_frame(), left_index=True, right_index=True)
Single quoted php string variable works.
$str = 'http://www.domain.com/data/images\flags/en.gif';
$str = str_replace('\\', '/', $str);
To call the function on click of some html element (control).
$('#controlID').click(myFunction);
You will need to ensure you bind the event when your html element is ready on which you binding the event. You can put the code in document.ready
$(document).ready(function(){
$('#controlID').click(myFunction);
});
You can use anonymous function to bind the event to the html element.
$(document).ready(function(){
$('#controlID').click(function(){
$.messager.show({
title:'My Title',
msg:'The message content',
showType:'fade',
style:{
right:'',
bottom:''
}
});
});
});
If you want to bind click with many elements you can use class selector
$('.someclass').click(myFunction);
Edit based on comments by OP, If you want to call function under some condition
You can use if for conditional execution, for example,
if(a == 3)
myFunction();
Go to "Window -> Preferences -> General -> C/C++ -> Code analysis" and disable "Syntax and Semantics Errors -> Abstract class cannot be instantiated"
in parent window put :
<script>
function ifDoneChildFrame(val)
{
$('#parentPrice').html(val);
}
</script>
and in iframe src file put :
<script>window.parent.ifDoneChildFrame('Your value here');</script>
$("div[id^=" + controlid + "]")
will return all the controls with the same name but you need to ensure that the text should not present in any of the controls
Naive and ugly (but seems to be faster) solution?
Only tried this in php 7.3.11 but an ugly loop seems to execute in about a third of the time. Similar results on an array with a few hundred keys. Micro-optimization, probably not useful in RW, but found it surprising and interesting:
$time = microtime(true);
$i = 100000;
while($i) {
$my_array = ['foo' => 1, 'hello' => 'world'];
$allowed = ['foo', 'bar'];
$filtered = array_filter(
$my_array,
function ($key) use ($allowed) {
return in_array($key, $allowed);
},
ARRAY_FILTER_USE_KEY
);
$i--;
}
print_r($filtered);
echo microtime(true) - $time . ' on array_filter';
// 0.40600109100342 on array_filter
$time2 = microtime(true);
$i2 = 100000;
while($i2) {
$my_array2 = ['foo' => 1, 'hello' => 'world'];
$allowed2 = ['foo', 'bar'];
$filtered2 = [];
foreach ($my_array2 as $k => $v) {
if (in_array($k, $allowed2)) $filtered2[$k] = $v;
}
$i2--;
}
print_r($filtered2);
echo microtime(true) - $time2 . ' on ugly loop';
// 0.15677785873413 on ugly loop
You've got the syntax all wrong:
cursor.execute ("""
UPDATE tblTableName
SET Year=%s, Month=%s, Day=%s, Hour=%s, Minute=%s
WHERE Server=%s
""", (Year, Month, Day, Hour, Minute, ServerID))
For more, read the documentation.
You create the frame with button enable, do some test to see if btn1Cliked is true, and that's all.
Then you have the actionPerformed method that does nothing with your button. So, if you don't have any action related, your button status will never be evaluated again.
Here is a solution that you can execute without relying on the operating system:
STEP 1: Create a stored procedure.
DROP PROCEDURE IF EXISTS kill_user_processes$$
CREATE PROCEDURE `kill_user_processes`(
IN user_to_kill VARCHAR(255)
)
READS SQL DATA
BEGIN
DECLARE name_val VARCHAR(255);
DECLARE no_more_rows BOOLEAN;
DECLARE loop_cntr INT DEFAULT 0;
DECLARE num_rows INT DEFAULT 0;
DECLARE friends_cur CURSOR FOR
SELECT CONCAT('KILL ',id,';') FROM information_schema.processlist WHERE USER=user_to_kill;
DECLARE CONTINUE HANDLER FOR NOT FOUND
SET no_more_rows = TRUE;
OPEN friends_cur;
SELECT FOUND_ROWS() INTO num_rows;
the_loop: LOOP
FETCH friends_cur
INTO name_val;
IF no_more_rows THEN
CLOSE friends_cur;
LEAVE the_loop;
END IF;
SET @s = name_val;
PREPARE stmt FROM @s;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
SELECT name_val;
SET loop_cntr = loop_cntr + 1;
END LOOP the_loop;
SELECT num_rows, loop_cntr;
END $$
DELIMITER ;
STEP 2: Call the stored procedure giving it the name of a database user whose processes you want to kill. You could rewrite the stored procedure to filter on some other criteria if you like.
CALL kill_user_processes('devdba');
I meet this error when integrate modal bootstrap in angular.
This is my solution to solve this issue.
I share for whom concern.
First step you need install jquery
and bootstrap
by npm
command.
Second you need add declare var $ : any;
in component
And use can use $('#myModal').modal('hide');
on onSave() method
Demo https://stackblitz.com/edit/angular-model-bootstrap-close?file=src/app/app.component.ts
Is solved this using RouteValueDictionary (works fine as htmlAttributes as it's based on IDictionary) and an extension method:
public static RouteValueDictionary AddIf(this RouteValueDictionary dict, bool condition, string name, object value)
{
if (condition) dict.Add(name, value);
return dict;
}
Usage:
@Html.TextBoxFor(m => m.GovId, new RouteValueDictionary(new { @class = "form-control" })
.AddIf(Model.IsEntityFieldsLocked, "disabled", "disabled"))
Credit goes to https://stackoverflow.com/a/3481969/40939
$host
is a variable of the Core module.
$host
This variable is equal to line Host in the header of request or name of the server processing the request if the Host header is not available.
This variable may have a different value from $http_host in such cases: 1) when the Host input header is absent or has an empty value, $host equals to the value of server_name directive; 2)when the value of Host contains port number, $host doesn't include that port number. $host's value is always lowercase since 0.8.17.
$http_host
is also a variable of the same module but you won't find it with that name because it is defined generically as $http_HEADER
(ref).
$http_HEADER
The value of the HTTP request header HEADER when converted to lowercase and with 'dashes' converted to 'underscores', e.g. $http_user_agent, $http_referer...;
Summarizing:
$http_host
equals always the HTTP_HOST
request header.$host
equals $http_host
, lowercase and without the port number (if present), except when HTTP_HOST
is absent or is an empty value. In that case, $host
equals the value of the server_name
directive of the server which processed the request.See Effective C++ Introduction
try
{
int temp=Convert.ToInt32(TextBox1.Text);
}
catch(Exception h)
{
MessageBox.Show("Please provide number only");
}
d <- 5
for(i in 1:10) {
nam <- paste("A", i, sep = "")
assign(nam, rnorm(3)+d)
}
As shaishab roy says, in the cheat sheet you can find the answer.
But in his answer, the given response was :
{path: '/home/...', name: 'Home', component: HomeComponent} {path: '/', redirectTo: ['Home']}, {path: '/user/...', name: 'User', component: UserComponent}, {path: '/404', name: 'NotFound', component: NotFoundComponent}, {path: '/*path', redirectTo: ['NotFound']}
For some reasons, it doesn't works on my side, so I tried instead :
{path: '/**', redirectTo: ['NotFound']}
and it works. Be careful and don't forget that you need to put it at the end, or else you will often have the 404 error page ;).
The other answers so far have a lot of technical information. I will try to answer, as requested, in simple terms.
Serialization is what you do to an instance of an object if you want to dump it to a raw buffer, save it to disk, transport it in a binary stream (e.g., sending an object over a network socket), or otherwise create a serialized binary representation of an object. (For more info on serialization see Java Serialization on Wikipedia).
If you have no intention of serializing your class, you can add the annotation just above your class @SuppressWarnings("serial")
.
If you are going to serialize, then you have a host of things to worry about all centered around the proper use of UUID. Basically, the UUID is a way to "version" an object you would serialize so that whatever process is de-serializing knows that it's de-serializing properly. I would look at Ensure proper version control for serialized objects for more information.
As Marc says, you run it exactly like you would from the command line. See Creating SQL Server Agent Jobs on MSDN.
Within the range 0 = c < 128, yes the '
is the only difference for CPython 2.6.
>>> set(unichr(c).encode('unicode_escape') for c in range(128)) - set(chr(c).encode('string_escape') for c in range(128))
set(["'"])
Outside of this range the two types are not exchangeable.
>>> '\x80'.encode('string_escape')
'\\x80'
>>> '\x80'.encode('unicode_escape')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
UnicodeDecodeError: 'ascii' codec can’t decode byte 0x80 in position 0: ordinal not in range(128)
>>> u'1'.encode('unicode_escape')
'1'
>>> u'1'.encode('string_escape')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: escape_encode() argument 1 must be str, not unicode
On Python 3.x, the string_escape
encoding no longer exists, since str
can only store Unicode.
If the entire program should stop use sys.exit() otherwise just use an empty return.
What exactly are the rules for requesting retransmission of lost data?
The receiver does not request the retransmission. The sender waits for an ACK for the byte-range sent to the client and when not received, resends the packets, after a particular interval. This is ARQ (Automatic Repeat reQuest). There are several ways in which this is implemented.
Stop-and-wait ARQ
Go-Back-N ARQ
Selective Repeat ARQ
are detailed in the RFC 3366.
At what time frequency are the retransmission requests performed?
The retransmissions-times and the number of attempts isn't enforced by the standard. It is implemented differently by different operating systems, but the methodology is fixed. (One of the ways to fingerprint OSs perhaps?)
The timeouts are measured in terms of the RTT (Round Trip Time) times. But this isn't needed very often due to Fast-retransmit which kicks in when 3 Duplicate ACKs are received.
Is there an upper bound on the number?
Yes there is. After a certain number of retries, the host is considered to be "down" and the sender gives up and tears down the TCP connection.
Is there functionality for the client to indicate to the server to forget about the whole TCP segment for which part went missing when the IP packet went missing?
The whole point is reliable communication. If you wanted the client to forget about some part, you wouldn't be using TCP in the first place. (UDP perhaps?)
Download the Java mail jars.
Extract the downloaded file.
Copy the ".jar" file and paste it into ProjectName\WebContent\WEB-INF\lib
folder
Right click on the Project and go to Properties
Select Java Build Path and then select Libraries
Add JARs...
Select the .jar file from ProjectName\WebContent\WEB-INF\lib
and click OK
that's all
Of course, if you want to make sure it's in there otherwise fail then this works:
thisTag = _tags[key];
NOTE: This will fail if the key,value pair does not exists but sometimes that is exactly what you want. This way you can catch it and do something about the error. I would only do this if I am certain that the key,value pair is or should be in the dictionary and if not I want it to know about it via the throw.
This has been an old question but solution is very simple to that. If you are ever unsure about how to write criterias, joins etc in hibernate then best way is using native queries. This doesn't slow the performance and very useful. Eq. below
@Query(nativeQuery = true, value = "your sql query")
returnTypeOfMethod methodName(arg1, arg2);
This is how I usually generate random numbers. Then I use "NUM_1" as the variable for the port number I use. Here is a short example script.
#!/bin/bash
clear
echo 'Choose how many digits you want for port# (1-5)'
read PORT
NUM_1="$(tr -dc '0-9' </dev/urandom | head -c $PORT)"
echo "$NUM_1"
if [ "$PORT" -gt "5" ]
then
clear
echo -e "\x1b[31m Choose a number between 1 and 5! \x1b[0m"
sleep 3
clear
exit 0
fi
Add width:100px, margin:50%.
Now the left side of the button is set to the center.
Finally add half of the width of the button in our case 50px.
The middle of the button is in the center.
<input type='submit' style='width:100px;margin:0 50%;position:relative;left:-50px;'>
Windows: Mostly C and C++, some C#
If you only want to log the query, then add 'logger' and 'profileSQL' to the jdbc url:
&logger=com.mysql.jdbc.log.Slf4JLogger&profileSQL=true
Then you will get the SQL statement below:
2016-01-14 10:09:43 INFO MySQL - FETCH created: Thu Jan 14 10:09:43 CST 2016 duration: 1 connection: 19130945 statement: 999 resultset: 0
2016-01-14 10:09:43 INFO MySQL - QUERY created: Thu Jan 14 10:09:43 CST 2016 duration: 1 connection: 19130945 statement: 999 resultset: 0 message: SET sql_mode='NO_ENGINE_SUBSTITUTION,STRICT_TRANS_TABLES'
2016-01-14 10:09:43 INFO MySQL - FETCH created: Thu Jan 14 10:09:43 CST 2016 duration: 1 connection: 19130945 statement: 999 resultset: 0
2016-01-14 10:09:43 INFO MySQL - QUERY created: Thu Jan 14 10:09:43 CST 2016 duration: 2 connection: 19130945 statement: 13 resultset: 17 message: select 1
2016-01-14 10:09:43 INFO MySQL - FETCH created: Thu Jan 14 10:09:43 CST 2016 duration: 0 connection: 19130945 statement: 13 resultset: 17
2016-01-14 10:09:43 INFO MySQL - QUERY created: Thu Jan 14 10:09:43 CST 2016 duration: 1 connection: 19130945 statement: 15 resultset: 18 message: select @@session.tx_read_only
2016-01-14 10:09:43 INFO MySQL - FETCH created: Thu Jan 14 10:09:43 CST 2016 duration: 0 connection: 19130945 statement: 15 resultset: 18
2016-01-14 10:09:43 INFO MySQL - QUERY created: Thu Jan 14 10:09:43 CST 2016 duration: 2 connection: 19130945 statement: 14 resultset: 0 message: update sequence set seq=seq+incr where name='demo' and seq=4602
2016-01-14 10:09:43 INFO MySQL - FETCH created: Thu Jan 14 10:09:43 CST 2016 duration: 0 connection: 19130945 statement: 14 resultset: 0
The default logger is:
com.mysql.jdbc.log.StandardLogger
Mysql jdbc property list: https://dev.mysql.com/doc/connector-j/en/connector-j-reference-configuration-properties.html
Also, CasperJS provides a nice high-level interface for navigation in PhantomJS, including clicking on links and filling out forms.
Updated to add July 28, 2015 article comparing PhantomJS and CasperJS.
(Thanks to commenter Mr. M!)
This solution will also work for the following URLs, without breaking anchor links to different pages.
http://www.example.com/dir/index.html
http://www.example.com/dir/index.html#anchor
./index.html
./index.html#anchor
etc.
var $root = $('html, body');
$('a').on('click', function(event){
var hash = this.hash;
// Is the anchor on the same page?
if (hash && this.href.slice(0, -hash.length-1) == location.href.slice(0, -location.hash.length-1)) {
$root.animate({
scrollTop: $(hash).offset().top
}, 'normal', function() {
location.hash = hash;
});
return false;
}
});
I haven't tested this in all browsers, yet.
Why not using Cakes Response Class? You can set the status code of the response simply by this:
$this->response->statusCode(200);
Then just render a file with the error message, which suits best with JSON.
Global variables are not extern
nor static
by default on C and C++.
When you declare a variable as static
, you are restricting it to the current source file. If you declare it as extern
, you are saying that the variable exists, but are defined somewhere else, and if you don't have it defined elsewhere (without the extern
keyword) you will get a link error (symbol not found).
Your code will break when you have more source files including that header, on link time you will have multiple references to varGlobal
. If you declare it as static
, then it will work with multiple sources (I mean, it will compile and link), but each source will have its own varGlobal
.
What you can do in C++, that you can't in C, is to declare the variable as const
on the header, like this:
const int varGlobal = 7;
And include in multiple sources, without breaking things at link time. The idea is to replace the old C style #define
for constants.
If you need a global variable visible on multiple sources and not const
, declare it as extern
on the header, and then define it, this time without the extern keyword, on a source file:
Header included by multiple files:
extern int varGlobal;
In one of your source files:
int varGlobal = 7;
public static void BubbleSort(int[] array){
boolean swapped ;
do {
swapped = false;
for (int i = 0; i < array.length - 1; i++) {
if (array[i] > array[i + 1]) {
int temp = array[i];
array[i] = array[i + 1];
array[i + 1] = temp;
swapped = true;
}
}
}while (swapped);
}
Seems like you expected the query to return running totals, but it must have given you the same values for both partitions of AccountID
.
To obtain running totals with SUM() OVER ()
, you need to add an ORDER BY
sub-clause after PARTITION BY …
, like this:
SUM(Quantity) OVER (PARTITION BY AccountID ORDER BY ID)
But remember, not all database systems support ORDER BY
in the OVER
clause of a window aggregate function. (For instance, SQL Server didn't support it until the latest version, SQL Server 2012.)
For me, something different worked, that I found in on this answer from a similar question. Probably won't help OP, but maybe someone like me that had a similar problem.
You should indeed use rvm, but as no one explained to you how to do this without rvm, here you go:
sudo gem install tzinfo builder memcache-client rack rack-test rack-mount \
abstract erubis activesupport mime-types mail text-hyphen text-format \
thor i18n rake bundler arel railties rails --prerelease --force
This can be set up on your tsconfig.json file, as it is a TS feature.
You can do like this:
"compilerOptions": {
"baseUrl": "src", // This must be specified if "paths" is.
...
"paths": {
"@app/*": ["app/*"],
"@config/*": ["app/_config/*"],
"@environment/*": ["environments/*"],
"@shared/*": ["app/_shared/*"],
"@helpers/*": ["helpers/*"]
},
...
Have in mind that the path where you want to refer to, it takes your baseUrl as the base of the route you are pointing to and it's mandatory as described on the doc.
The character '@' is not mandatory.
After you set it up on that way, you can easily use it like this:
import { Yo } from '@config/index';
the only thing you might notice is that the intellisense does not work in the current latest version, so I would suggest to follow an index convention for importing/exporting files.
https://www.typescriptlang.org/docs/handbook/module-resolution.html#path-mapping
Technically, the char*
is not an array, but a pointer to a char
.
Similarly, char**
is a pointer to a char*
. Making it a pointer to a pointer to a char
.
C and C++ both define arrays behind-the-scenes as pointer types, so yes, this structure, in all likelihood, is array of arrays of char
s, or an array of strings.
None of the above solutions did exactly what I wanted, which was to add some information to the first part of the error message i.e. I wanted my users to see my custom message first.
This worked for me:
exception_raised = False
try:
do_something_that_might_raise_an_exception()
except ValueError as e:
message = str(e)
exception_raised = True
if exception_raised:
message_to_prepend = "Custom text"
raise ValueError(message_to_prepend + message)
I'm adding this answer as a use case and complete example for the runtime-check described in another answer.
This is the approach I've been taking for conveying to the end-user whether the program was compiled as 64-bit or 32-bit (or other, for that matter):
version.h
#ifndef MY_VERSION
#define MY_VERSION
#include <string>
const std::string version = "0.09";
const std::string arch = (std::to_string(sizeof(void*) * 8) + "-bit");
#endif
test.cc
#include <iostream>
#include "version.h"
int main()
{
std::cerr << "My App v" << version << " [" << arch << "]" << std::endl;
}
Compile and Test
g++ -g test.cc
./a.out
My App v0.09 [64-bit]
It's a convention so the *nix shell knows what kind of interpreter to run.
For example, older flavors of ATT defaulted to sh (the Bourne shell), while older versions of BSD defaulted to csh (the C shell).
Even today (where most systems run bash, the "Bourne Again Shell"), scripts can be in bash, python, perl, ruby, PHP, etc, etc. For example, you might see #!/bin/perl
or #!/bin/perl5
.
PS:
The exclamation mark (!
) is affectionately called "bang". The shell comment symbol (#
) is sometimes called "hash".
PPS:
Remember - under *nix, associating a suffix with a file type is merely a convention, not a "rule". An executable can be a binary program, any one of a million script types and other things as well. Hence the need for #!/bin/bash
.
I too needed a rounded ImageView, I used the below code, you can modify it accordingly:
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Bitmap.Config;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.PorterDuff.Mode;
import android.graphics.PorterDuffXfermode;
import android.graphics.Rect;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.util.AttributeSet;
import android.widget.ImageView;
public class RoundedImageView extends ImageView {
public RoundedImageView(Context context) {
super(context);
}
public RoundedImageView(Context context, AttributeSet attrs) {
super(context, attrs);
}
public RoundedImageView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
@Override
protected void onDraw(Canvas canvas) {
Drawable drawable = getDrawable();
if (drawable == null) {
return;
}
if (getWidth() == 0 || getHeight() == 0) {
return;
}
Bitmap b = ((BitmapDrawable) drawable).getBitmap();
Bitmap bitmap = b.copy(Bitmap.Config.ARGB_8888, true);
int w = getWidth();
@SuppressWarnings("unused")
int h = getHeight();
Bitmap roundBitmap = getCroppedBitmap(bitmap, w);
canvas.drawBitmap(roundBitmap, 0, 0, null);
}
public static Bitmap getCroppedBitmap(Bitmap bmp, int radius) {
Bitmap sbmp;
if (bmp.getWidth() != radius || bmp.getHeight() != radius) {
float smallest = Math.min(bmp.getWidth(), bmp.getHeight());
float factor = smallest / radius;
sbmp = Bitmap.createScaledBitmap(bmp,
(int) (bmp.getWidth() / factor),
(int) (bmp.getHeight() / factor), false);
} else {
sbmp = bmp;
}
Bitmap output = Bitmap.createBitmap(radius, radius, Config.ARGB_8888);
Canvas canvas = new Canvas(output);
final String color = "#BAB399";
final Paint paint = new Paint();
final Rect rect = new Rect(0, 0, radius, radius);
paint.setAntiAlias(true);
paint.setFilterBitmap(true);
paint.setDither(true);
canvas.drawARGB(0, 0, 0, 0);
paint.setColor(Color.parseColor(color));
canvas.drawCircle(radius / 2 + 0.7f, radius / 2 + 0.7f,
radius / 2 + 0.1f, paint);
paint.setXfermode(new PorterDuffXfermode(Mode.SRC_IN));
canvas.drawBitmap(sbmp, rect, rect, paint);
return output;
}
}
In my case, it appears that this message can be issued by Intellisense in Visual Studio 2013. The screenshot below shows the error at the bottom of VisualStudio 2013 after the first load of a customer project.
I started googling what causes this error, and decided to try deleteing the user.vxproj files as mentioned above. I found however that the project built with no issues, then after exiting and re-loading the project, I no longer received the error. So I'm assuming in my case, it was some corruption due to moving the project from the customers directory tree structure to my local development disk tree structure. The key here is that in my case, the problem was transient. I did NOTHING and the problem appeared to resolve itself. (Not generally a desirable thing as I didn't fix anything so it might come back).
Directly, you can't, and that's a good thing. The browser's alert is there for a reason. This thread should answer your question:
Prevent Back button from showing POST confirmation alert
Two key workarounds suggested were the PRG pattern, and an AJAX submit followed by a scripting relocation.
Note that if your method allows for a GET and not a POST submission method, then that would both solve the problem and better fit with convention. Those solutions are provided on the assumption you want/need to POST data.
for those who want some official document to confirm the behavior
Variables in make can come from the environment in which make is run. Every environment variable that make sees when it starts up is transformed into a make variable with the same name and value. However, an explicit assignment in the makefile, or with a command argument, overrides the environment. (If the ‘-e’ flag is specified, then values from the environment override assignments in the makefile.
https://www.gnu.org/software/make/manual/html_node/Environment.html
I would check datatypes.
current_date has "date" datatype, 10 is a number, and Table.date - you need to look at your table.
I think you just need 'git show -c $ref'. Trying this on the git repository on a8e4a59 shows a combined diff (plus/minus chars in one of 2 columns). As the git-show manual mentions, it pretty much delegates to 'git diff-tree' so those options look useful.
./manage.py migrate
This solved my issue
urllib2.urlopen does an HTTP GET (or POST if you supply a data argument), not an HTTP HEAD (if it did the latter, you couldn't do readlines or other accesses to the page body, of course).
Try this
String[] arr = list.toArray(new String[list.size()]);
See this blog article that describes the difference. Basically doing:
Task.Run(A)
Is the same as doing:
Task.Factory.StartNew(A, CancellationToken.None, TaskCreationOptions.DenyChildAttach, TaskScheduler.Default);
Fix the indentation of the print
statement
import random
my_randoms=[]
for i in range (10):
my_randoms.append(random.randrange(1,101,1))
print (my_randoms)
Well, basically what I found is that you can declare the array, but when you set it vba shows you an error.
So I put an special sub to declare global variables and arrays, something like:
Global example(10) As Variant
Sub set_values()
example(1) = 1
example(2) = 1
example(3) = 1
example(4) = 1
example(5) = 1
example(6) = 1
example(7) = 1
example(8) = 1
example(9) = 1
example(10) = 1
End Sub
And whenever I want to use the array, I call the sub first, just in case
call set_values
Msgbox example(5)
Perhaps is not the most correct way, but I hope it works for you
In theory like so:
# BOLD
$ echo -e "\033[1mThis is a BOLD line\033[0m"
This is a BOLD line
# Using tput
tput bold
echo "This" #BOLD
tput sgr0 #Reset text attributes to normal without clear.
echo "This" #NORMAL
# UNDERLINE
$ echo -e "\033[4mThis is a underlined line.\033[0m"
This is a underlined line.
But in practice it may be interpreted as "high intensity" color instead.
(source: http://unstableme.blogspot.com/2008/01/ansi-escape-sequences-for-writing-text.html)
Use this
select * from (
SELECT ARIDNR,LIEFNR,row_number() over
(partition by ARIDNR order by ARIDNR) as RowNum) a
where a.RowNum >1
Use the best recursion function for getting all posts of users.
<?php
set_time_limit(0);
function getPost($url,$i)
{
static $posts=array();
$json=file_get_contents($url);
$data = json_decode($json);
$ins_links=array();
$page=$data->pagination;
$pagearray=json_decode(json_encode($page),true);
$pagecount=count($pagearray);
foreach( $data->data as $user_data )
{
$posts[$i++]=$user_data->link;
}
if($pagecount>0)
return getPost($page->next_url,$i);
else
return $posts;
}
$posts=getPost("https://api.instagram.com/v1/users/CLIENT-ACCOUNT-NUMBER/media/recent?client_id=CLIENT-ID&count=33",0);
print_r($posts);
?>
The .NET framework uses banker's rounding in Math.Round
by default. You should use this overload:
Math.Round(0.5d, MidpointRounding.AwayFromZero) //1
Math.Round(0.4d, MidpointRounding.AwayFromZero) //0
Boost Preprocessor actually has this as of Boost 1.49, as BOOST_PP_VARIADIC_SIZE(...)
. It works up to size 64.
Under the hood, it's basically the same as Kornel Kisielewicz's answer.
If you've opened a table and you want to clear an existing value to NULL, click on the value, and press Ctrl
+0
.
One idea would be to winsorize the data in a two-pass procedure:
run a first pass, learn what the bounds are, e.g. cut of at given percentile, or N standard deviation above the mean, or ...
in a second pass, set the values beyond the given bound to the value of that bound
I should stress that this is an old-fashioned method which ought to be dominated by more modern robust techniques but you still come across it a lot.
When you return something from a then()
callback, it's a bit magic. If you return a value, the next then()
is called with that value. However, if you return something promise-like, the next then()
waits on it, and is only called when that promise settles (succeeds/fails).
Source: https://web.dev/promises/#queuing-asynchronous-actions
The linux kernel graphical operations are in /include/linux/fb.h as struct fb_ops. Eventually this is what add-ons like X11, Wayland, or DRM appear to reference. As these operations are only for video cards, not vector or raster hardcopy or tty oriented terminal devices, their usefulness as a GUI is limited; it's just not entirely true you need those add-ons to get graphical output if you don't mind using some assembler to bypass syscall as necessary.
I think this is the syntax you are looking for:
if [ -z != $errorstatus ]
then
commands
else
commands
fi
As @Quartz mentioned, you can do something like
stage('Tests') {
parallel(
'Unit Tests': {
container('node') {
sh("npm test --cat=unit")
}
},
'API Tests': {
container('node') {
sh("npm test --cat=acceptance")
}
}
)
}
Try this
button.addTarget(self, action:#selector(handleRegister()), for: .touchUpInside).
Just add parenthesis with name of method.
Also you can refer link : Value of type 'CustomButton' has no member 'touchDown'
ctrl != super on windows and linux machines.
If the F12 version of "Goto Definition" produces results of several files, the "ctrl + shift + click" version might not work well. I found that bug when viewing golang project with GoSublime package.
To be able to inspect any element do the following. This should work even if it's hard to duplicate the hover state:
Run the following javascript in the console. This will break into the debugger in 5 seconds.
setTimeout(function(){debugger;}, 5000)
Go show your element (by hovering or however) and wait until Chrome breaks into the Debugger.
Elements
tab in the Chrome Inspector, and you can look for your element there. Find Element
icon (looks like a magnifying glass) and Chrome will let you go and inspect and find your element on the page by right clicking on it, then choosing Inspect Element
Note that this approach is a slight variation to this other great answer on this page.
The PDB file is typically used to store debug information. This warning is caused probably because the file vc80.pdb
is not found when linking the target object file. Read the MSDN entry on LNK4099 here.
Alternatively, you can turn off debug information generation from the Project Properties > Linker > Debugging > Generate Debug Info field.
More actual solution:
<a id="someId">Link</a>
const a = document.querySelector('#someId');
a.href = 'url';
Or you can use for the HttpClient in the Windows.Web.Http
namespace:
var filter = new HttpBaseProtocolFilter();
#if DEBUG
filter.IgnorableServerCertificateErrors.Add(ChainValidationResult.Expired);
filter.IgnorableServerCertificateErrors.Add(ChainValidationResult.Untrusted);
filter.IgnorableServerCertificateErrors.Add(ChainValidationResult.InvalidName);
#endif
using (var httpClient = new HttpClient(filter)) {
...
}
A simplest fix would be:
x = input("Give starting number: ")
y = input("Give ending number: ")
x = int(x) # parse string into an integer
y = int(y) # parse string into an integer
for i in range(x,y):
print(i)
input
returns you a string (raw_input
in Python 2). int
tries to parse it into an integer. This code will throw an exception if the string doesn't contain a valid integer string, so you'd probably want to refine it a bit using try
/except
statements.
Convert a string to a DateTime, you could try
DateTime timeValue = Convert.ToDateTime("01:00 PM");
Console.WriteLine(timeValue.ToString("HH:mm"));
Below are code snippets to create and delete a cookie. The cookie is set for 1 day.
// 1 Day = 24 Hrs = 24*60*60 = 86400.
By using max-age:
document.cookie = "cookieName=cookieValue; max-age=86400; path=/;";
document.cookie = "cookieName=; max-age=- (any digit); path=/;";
By using expires:
var expires = (new Date(Date.now()+ 86400*1000)).toUTCString();
document.cookie = "cookieName=cookieValue; expires=" + expires + 86400) + ";path=/;"
var app = angular.module('plunkr', [])
app.controller('UploadController', function($scope, fileReader) {
$scope.imageSrc = "";
$scope.$on("fileProgress", function(e, progress) {
$scope.progress = progress.loaded / progress.total;
});
});
app.directive("ngFileSelect", function(fileReader, $timeout) {
return {
scope: {
ngModel: '='
},
link: function($scope, el) {
function getFile(file) {
fileReader.readAsDataUrl(file, $scope)
.then(function(result) {
$timeout(function() {
$scope.ngModel = result;
});
});
}
el.bind("change", function(e) {
var file = (e.srcElement || e.target).files[0];
getFile(file);
});
}
};
});
app.factory("fileReader", function($q, $log) {
var onLoad = function(reader, deferred, scope) {
return function() {
scope.$apply(function() {
deferred.resolve(reader.result);
});
};
};
var onError = function(reader, deferred, scope) {
return function() {
scope.$apply(function() {
deferred.reject(reader.result);
});
};
};
var onProgress = function(reader, scope) {
return function(event) {
scope.$broadcast("fileProgress", {
total: event.total,
loaded: event.loaded
});
};
};
var getReader = function(deferred, scope) {
var reader = new FileReader();
reader.onload = onLoad(reader, deferred, scope);
reader.onerror = onError(reader, deferred, scope);
reader.onprogress = onProgress(reader, scope);
return reader;
};
var readAsDataURL = function(file, scope) {
var deferred = $q.defer();
var reader = getReader(deferred, scope);
reader.readAsDataURL(file);
return deferred.promise;
};
return {
readAsDataUrl: readAsDataURL
};
});
*************** CSS ****************
img{width:200px; height:200px;}
************** HTML ****************
<div ng-app="app">
<div ng-controller="UploadController ">
<form>
<input type="file" ng-file-select="onFileSelect($files)" ng-model="imageSrc">
<input type="file" ng-file-select="onFileSelect($files)" ng-model="imageSrc2">
<!-- <input type="file" ng-file-select="onFileSelect($files)" multiple> -->
</form>
<img ng-src="{{imageSrc}}" />
<img ng-src="{{imageSrc2}}" />
</div>
</div>
Just because no-one else has said the magic words yet: it's the null coalescing operator. It's defined in section 7.12 of the C# 3.0 language specification.
It's very handy, particularly because of the way it works when it's used multiple times in an expression. An expression of the form:
a ?? b ?? c ?? d
will give the result of expression a
if it's non-null, otherwise try b
, otherwise try c
, otherwise try d
. It short-circuits at every point.
Also, if the type of d
is non-nullable, the type of the whole expression is non-nullable too.
You need to make a class library and not a Console Application. The console application is translated into an .exe
whereas the class library will then be compiled into a dll
which you can reference in your windows project.
Use the adb tool that comes with the SDK.
adb push myDirectory /sdcard/targetDir
If you only specify /sdcard/
(with the trailing slash) as destination, then the CONTENTS of myDirectory will end up in the root of /sdcard.
The smarter/easier thing to do here is to just change your code so that instead of opening the file assuming that it exists in the current working directory (I assume you are doing something like new File("blah.txt")
, just build the path to the file yourself.
Let the user pass in the base directory, read it from a config file, fall back to user.dir
if the other properties can't be found, etc. But it's a whole lot easier to improve the logic in your program than it is to change how environment variables work.
According to MSDN
result is the number of lines affected, and since your query is select
no lines are affected (i.e. inserted, deleted or updated) anyhow.
If you want to return a single row of the query, use ExecuteScalar()
instead of ExecuteNonQuery()
:
int result = (int) (command.ExecuteScalar());
However, if you expect many rows to be returned, ExecuteReader()
is the only option:
using (SqlDataReader reader = command.ExecuteReader()) {
while (reader.Read()) {
int result = reader.GetInt32(0);
...
}
}
Java has a feature called "checked exceptions". That means that there are certain kinds of exceptions, namely those that subclass Exception but not RuntimeException, such that if a method may throw them, it must list them in its throws declaration, say: void readData() throws IOException. IOException is one of those.
Thus, when you are calling a method that lists IOException in its throws declaration, you must either list it in your own throws declaration or catch it.
The rationale for the presence of checked exceptions is that for some kinds of exceptions, you must not ignore the fact that they may happen, because their happening is quite a regular situation, not a program error. So, the compiler helps you not to forget about the possibility of such an exception being raised and requires you to handle it in some way.
However, not all checked exception classes in Java standard library fit under this rationale, but that's a totally different topic.
If the data in your database is POSTED from HTML form TextArea controls, different browsers use different New Line characters:
Firefox separates lines with CHR(10) only
Internet Explorer separates lines with CHR(13) + CHR(10)
Apple (pre-OSX) separates lines with CHR(13) only
So you may need something like:
set col_name = replace(replace(col_name, CHR(13), ''), CHR(10), '')
You can use google's chart api to generate charts.
They're examples provided by the Android team, if you've already loaded Samples, you can import Home screen replacement sample by following these steps.
File > New > Other >Android > Android Sample Project > Android x.x > Home > Finish
But if you do not have samples loaded, then download it using the below steps
Windows > Android SDK Manager > chooses "Sample for SDK" for SDK you need it > Install package > Accept License > Install
If you compiled from source, then adding extension=php_openssl.dll
to the php.ini file may not work.
To troubleshoot this, open a command prompt and type php -i
. Scroll up to the first line, it will tell you the most recent error regarding your php.ini file.
To solve the issue, find the php_openssl.dll
file, for me it was in the very same directory of the compilation output:
C:\php-sdk\bin\phpdev\vc14\x64\php-7.0.13-src\x64\Release_TS
So just add the directory where the extension is, to the php.ini
:
extension_dir = "C:\php-sdk\bin\phpdev\vc14\x64\php-7.0.13-src\x64\Release_TS"
Hopefully the error will be gone
import re
s = '''
text1
text2
http://url.com/bla1/blah1/
text3
text4
http://url.com/bla2/blah2/
text5
text6
http://url.com/bla3/blah3/'''
g = re.findall(r'(text\d+)',s)
print ('list',g)
for i in g:
print (i)
Out
list ['text1', 'text2', 'text3', 'text4', 'text5', 'text6']
text1
text2
text3
text4
text5
text6 ?
You can develop your own thing in a second. For instance:
class Program
{
static void Main(string[] args)
{
var a = new object();
var b = new object();
Console.WriteLine("", a.GetId(), b.GetId());
}
}
public static class MyExtensions
{
//this dictionary should use weak key references
static Dictionary<object, int> d = new Dictionary<object,int>();
static int gid = 0;
public static int GetId(this object o)
{
if (d.ContainsKey(o)) return d[o];
return d[o] = gid++;
}
}
You can choose what you will like to have as unique ID on your own, for instance, System.Guid.NewGuid() or simply integer for fastest access.
Surprisingly this question doesn't have a definitive documented answer. Perhaps another data point would provide value to others looking for an answer. On my systems running CentOS (6.8,7.3) and Java 8 (build 1.8.0_60-b27, 64-Bit Server):
default memory is 1/4 of physical memory, not limited by 1GB.
Also, -XX:+PrintFlagsFinal
prints to STDERR so command to determine current default memory presented by others above should be tweaked to the following:
java -XX:+PrintFlagsFinal 2>&1 | grep MaxHeapSize
The following is returned on system with 64GB of physical RAM:
uintx MaxHeapSize := 16873684992 {product}
Just hit the same problem... For some reason, the freezepanes command just caused crosshairs to appear in the centre of the screen. It turns oout I had switched ScreenUpdating off! Solved with the following code:
Application.ScreenUpdating = True
Cells(2, 1).Select
ActiveWindow.FreezePanes = True
Now it works fine.
Percent encoding. Replace the hash with %23
.
I would say remove them and define a default: branch.
http://api.football-data.org/index is free and useful. The API is in active development, stable and recently the first versioned release called alpha was put online. Check the blog section to follow updates and changes.
Another method that I use is to create a symbolic link (in Linux, don't know about Win) using the ln command in htdocs or www i.e. ln projectname/public project
The site is thus accessible via localhost/project
Rookie, if you want to write a file to server by socket, how about using fileoutputstream instead of dataoutputstream? dataoutputstream is more fit for protocol-level read-write. it is not very reasonable for your code in bytes reading and writing. loop to read and write is necessary in java io. and also, you use a buffer way. flush is necessary. here is a code sample: http://www.rgagnon.com/javadetails/java-0542.html
For >= 2nd row values insert into table-
$file = fopen($filename, "r");
//$sql_data = "SELECT * FROM prod_list_1 ";
$count = 0; // add this line
while (($emapData = fgetcsv($file, 10000, ",")) !== FALSE)
{
//print_r($emapData);
//exit();
$count++; // add this line
if($count>1){ // add this line
$sql = "INSERT into prod_list_1(p_bench,p_name,p_price,p_reason) values ('$emapData[0]','$emapData[1]','$emapData[2]','$emapData[3]')";
mysql_query($sql);
} // add this line
}
The <span>
tag will need to be set to display:block
as it is an inline element and will ignore width.
so:
<style type="text/css"> span { width: 50px; display: block; } </style>
and then:
<li><span> </span>something</li>
<li><span>AND</span>something else</li>
What's even easier is to just use the BackgroundWorker control...
As of Ubuntu 12.04 (Precise Pangolin) (and perhaps a release or two before) simply installing apache2
and mod-perl
via Synaptic and placing your CGI scripts in /usr/lib/cgi-bin is really all you need to do.
Here is my answer from a different question.
First you need to reference the Adobe Reader ActiveX Control
Adobe Acrobat Browser Control Type Library 1.0
%programfiles&\Common Files\Adobe\Acrobat\ActiveX\AcroPDF.dll
Then you just drag it into your Windows Form from the Toolbox.
And use some code like this to initialize the ActiveX Control.
private void InitializeAdobe(string filePath)
{
try
{
this.axAcroPDF1.LoadFile(filePath);
this.axAcroPDF1.src = filePath;
this.axAcroPDF1.setShowToolbar(false);
this.axAcroPDF1.setView("FitH");
this.axAcroPDF1.setLayoutMode("SinglePage");
this.axAcroPDF1.Show();
}
catch (Exception ex)
{
throw;
}
}
Make sure when your Form closes that you dispose of the ActiveX Control
this.axAcroPDF1.Dispose();
this.axAcroPDF1 = null;
otherwise Acrobat might be left lying around.
(This question came up high on a search engine result, but I ended up using a different approach. Adding an answer to this old question in case other people with similar questions read this)
You can solve this with Json.Net and make an extension method to handle the items you want to loop:
public static Tuple<string, int, int> ToTuple(this JToken token)
{
var type = token["attributes"]["OBJECT_TYPE"].ToString();
var x = token["position"]["x"].Value<int>();
var y = token["position"]["y"].Value<int>();
return new Tuple<string, int, int>(type, x, y);
}
And then access the data like this: (scenario: writing to console):
var tuples = JObject.Parse(myJsonString)["objects"].Select(item => item.ToTuple()).ToList();
tuples.ForEach(t => Console.WriteLine("{0}: ({1},{2})", t.Item1, t.Item2, t.Item3));
As can be seen from previous posts, one can argue that if class functionality needs to be circumvented then something is wrong in the class architecture. That might be true, but one cannot always restructure or refactor the class structure on a large mature project. The various levels of change management might be one problem, but to keep existing functionality operating the same after refactoring is not always a trivial task, especially if time constraints apply. On a mature project it can be quite an undertaking to keep various regression tests from passing after a code restructure; there are often obscure "oddities" that show up. We had a similar problem in some cases inherited functionality should not execute (or should perform something else). The approach we followed below, was to put the base code that need to be excluded in a separate virtual function. This function can then be overridden in the derived class and the functionality excluded or altered. In this example "Text 2" can be prevented from output in the derived class.
public class Base
{
public virtual void Foo()
{
Console.WriteLine("Hello from Base");
}
}
public class Derived : Base
{
public override void Foo()
{
base.Foo();
Console.WriteLine("Text 1");
WriteText2Func();
Console.WriteLine("Text 3");
}
protected virtual void WriteText2Func()
{
Console.WriteLine("Text 2");
}
}
public class Special : Derived
{
public override void WriteText2Func()
{
//WriteText2Func will write nothing when
//method Foo is called from class Special.
//Also it can be modified to do something else.
}
}
The other answers here rely on the user making an initial click (on the image). This is fine for the specifics of the OP detail but not necessarily the question title.
There is an answer here explaining how to do it by firing a click event on the button ( or any element ).
Code snippet for implementing matching parenthesis using java.util.Stack
data structure -
//map for storing matching parenthesis pairs
private static final Map<Character, Character> matchingParenMap = new HashMap<>();
//set for storing opening parenthesis
private static final Set<Character> openingParenSet = new HashSet<>();
static {
matchingParenMap.put(')','(');
matchingParenMap.put(']','[');
matchingParenMap.put('}','{');
openingParenSet.addAll(matchingParenMap.values());
}
//check if parenthesis match
public static boolean hasMatchingParen(String input) {
try {
//stack to store opening parenthesis
Stack<Character> parenStack = new Stack<>();
for(int i=0; i< input.length(); i++) {
char ch = input.charAt(i);
//if an opening parenthesis then push to the stack
if(openingParenSet.contains(ch)) {
parenStack.push(ch);
}
//for closing parenthesis
if(matchingParenMap.containsKey(ch)) {
Character lastParen = parenStack.pop();
if(lastParen != matchingParenMap.get(ch)) {
return false;
}
}
}
//returns true if the stack is empty else false
return parenStack.isEmpty();
}
catch(StackOverflowException s) {}
catch(StackUnderflowException s1) {}
return false;
}
I have explained the code snippet and the algorithm used on blog http://hetalrachh.home.blog/2019/12/25/stack-data-structure/
const input = document.getElementById('input')_x000D_
_x000D_
input.addEventListener('change', (event) => {_x000D_
const target = event.target_x000D_
if (target.files && target.files[0]) {_x000D_
_x000D_
/*Maximum allowed size in bytes_x000D_
5MB Example_x000D_
Change first operand(multiplier) for your needs*/_x000D_
const maxAllowedSize = 5 * 1024 * 1024;_x000D_
if (target.files[0].size > maxAllowedSize) {_x000D_
// Here you can ask your users to load correct file_x000D_
target.value = ''_x000D_
}_x000D_
}_x000D_
})
_x000D_
<input type="file" id="input" />
_x000D_
In my case, I created a new project and when I ran it the first time, it gave me the following error:
An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below.
So my solution was to go to the Package Manager Console inside the Visual Studio and run:Update-Package
Problem solved!!
Remove the z-index value.
I would also recommend this approach.
HTML:
<header class="main-header" role="banner">
<img src="mybannerimage.gif" alt="Banner Image"/>
</header>
CSS:
.main-header {
text-align: center;
}
This will center your image with out stretching it out. You can adjust the padding as needed to give it some space around your image. Since this is at the top of your page you don't need to force it there with position absolute unless you want your other elements to go underneath it. In that case you'd probably want position:fixed; anyway.
Roger's answer was very helpful.
I had a little trouble using it, though, and kept getting the red "Windows can't verify the publisher of this driver software" error dialog. The key was to install the test root certificate with
certutil -addstore Root Demo_CA.cer
which Roger's answer didn't quite cover.
Here is a batch file that worked for me (with my .inf file, not included). It shows how to do it all from start to finish, with no GUI tools at all (except for a few password prompts).
REM Demo of signing a printer driver with a self-signed test certificate.
REM Run as administrator (else devcon won't be able to try installing the driver)
REM Use a single 'x' as the password for all certificates for simplicity.
PATH %PATH%;"c:\Program Files\Microsoft SDKs\Windows\v7.1\Bin";"c:\Program Files\Microsoft SDKs\Windows\v7.0\Bin";c:\WinDDK\7600.16385.1\bin\selfsign;c:\WinDDK\7600.16385.1\Tools\devcon\amd64
makecert -r -pe -n "CN=Demo_CA" -ss CA -sr CurrentUser ^
-a sha256 -cy authority -sky signature ^
-sv Demo_CA.pvk Demo_CA.cer
makecert -pe -n "CN=Demo_SPC" -a sha256 -cy end ^
-sky signature ^
-ic Demo_CA.cer -iv Demo_CA.pvk ^
-sv Demo_SPC.pvk Demo_SPC.cer
pvk2pfx -pvk Demo_SPC.pvk -spc Demo_SPC.cer ^
-pfx Demo_SPC.pfx ^
-po x
inf2cat /drv:driver /os:XP_X86,Vista_X64,Vista_X86,7_X64,7_X86 /v
signtool sign /d "description" /du "www.yoyodyne.com" ^
/f Demo_SPC.pfx ^
/p x ^
/v driver\demoprinter.cat
certutil -addstore Root Demo_CA.cer
rem Needs administrator. If this command works, the driver is properly signed.
devcon install driver\demoprinter.inf LPTENUM\Yoyodyne_IndustriesDemoPrinter_F84F
rem Now uninstall the test driver and certificate.
devcon remove driver\demoprinter.inf LPTENUM\Yoyodyne_IndustriesDemoPrinter_F84F
certutil -delstore Root Demo_CA
Very easy method to get the Last digit:
int myInt = 1821;
int lastDigit = myInt - ((myInt/10)*10); // 1821 - 1820 = 1
I believe you want to use CHARINDEX
. You can read about it here.
Yes.
It is a good practice since an element can be a part of different groups, and you may want specific elements to be a part of more than one group. The element can hold an infinite number of classes in HTML5, while in HTML4 you are limited by a specific length.
The following example will show you the use of multiple classes.
The first class makes the text color
red.
The second class makes the background-color
blue.
See how the DOM Element with multiple classes will behave, it will wear both CSS statements at the same time.
Result: multiple CSS statements in different classes will stack up.
You can read more about CSS Specificity.
.class1 {
color:red;
}
.class2 {
background-color:blue;
}
<div class="class1">text 1</div>
<div class="class2">text 2</div>
<div class="class1 class2">text 3</div>
If you want to convert an Instant
to a Date
:
Date myDate = Date.from(instant);
And then you can use SimpleDateFormat
for the formatting part of your question:
SimpleDateFormat formatter = new SimpleDateFormat("dd MM yyyy HH:mm:ss");
String formattedDate = formatter.format(myDate);
As of right now, I do not know of any. It appears the code academy folks have set their sites on Ruby on Rails. They do not rule Java out of the picture however.
If the column is a timestamp you can do the following:
if(fromDate!=null){
criteria.add(Restrictions.sqlRestriction("TRUNC(COLUMN) >= TO_DATE('" + dataFrom + "','dd/mm/yyyy')"));
}
if(toDate!=null){
criteria.add(Restrictions.sqlRestriction("TRUNC(COLUMN) <= TO_DATE('" + dataTo + "','dd/mm/yyyy')"));
}
resultDB = criteria.list();
The plus sign is the historic encoding for a space character in URL parameters, as documented in the help for the urlencode()
function.
That same page contains the answer you need - use rawurlencode()
instead to get RFC 3986 compatible encoding.
Element, Pseudo Element: d = 1 – (0,0,0,1)
Class, Pseudo class, Attribute: c = 1 – (0,0,1,0)
Id: b = 1 – (0,1,0,0)
Inline Style: a = 1 – (1,0,0,0)
Inline css ( html style attribute ) overrides css rules in style tag and css file
A more specific selector takes precedence over a less specific one.
Rules that appear later in the code override earlier rules if both have the same specificity.
In addition to all the concerns expressed about why you give a rat's ass what the ID value is (all are correct that you shouldn't), let me add this to the mix:
If you've deleted all the records from the table, compacting the database will reset the seed value back to its original value.
For a table where there are still records, and you've inserted a value into the Autonumber field that is lower than the highest value, you have to use @Remou's method to reset the seed value. This also applies if you want to reset to the Max+1 in a table where records have been deleted, e.g., 300 records, last ID of 300, delete 201-300, compact won't reset the counter (you have to use @Remou's method -- this was not the case in earlier versions of Jet, and, indeed, in early versions of Jet 4, the first Jet version that allowed manipulating the seed value programatically).
I have tried all suggestions and found my own simple solution.
The problem is that codes written in external environment like C
need compiler. Look for its own VS environment, i.e. VS 2008.
Currently my machine runs VS 2012 and faces Unable to find vcvarsall.bat
.
I studied codes that i want to install to find the VS version. It was VS 2008. i have add to system variable VS90COMNTOOLS
as variable name and gave the value of VS120COMNTOOLS
.
You can find my step by step solution below:
Now open a new session and pip install your-package
It turns out that, out of the four possible permutations of including or excluding trailing or leading forward slashes on the BaseAddress
and the relative URI passed to the GetAsync
method -- or whichever other method of HttpClient
-- only one permutation works. You must place a slash at the end of the BaseAddress
, and you must not place a slash at the beginning of your relative URI, as in the following example.
using (var handler = new HttpClientHandler())
using (var client = new HttpClient(handler))
{
client.BaseAddress = new Uri("http://something.com/api/");
var response = await client.GetAsync("resource/7");
}
Even though I answered my own question, I figured I'd contribute the solution here since, again, this unfriendly behavior is undocumented. My colleague and I spent most of the day trying to fix a problem that was ultimately caused by this oddity of HttpClient
.
Or, if you're using PrototypeJS
<script type="text/javascript>
Event.observe( $('thelink'), 'click', function(event) {
//do stuff
Event.stop(event);
}
</script>
<a href="#" id="thelink">This is the link</a>
For me, the problem was in XML migrations. I deleted all tables and sequences and it works on next bootRun
You can select just the part of the string you want to check:
if [ "${HOST:0:4}" = user ]
For your follow-up question, you could use an OR:
if [[ "$HOST" == user1 || "$HOST" == node* ]]
use:
std::vector <Acard> playerHand;
everywhere qualify it by std::
or do:
using std::vector;
in your cpp file.
You have to do this because vector
is defined in the std
namespace and you do not tell your program to find it in std
namespace, you need to tell that.
All the 3 first ways are identical. You have make sure that if t
is a matrix you add .
before using multiplication or the power.
for matrix:
t= [1 2 3;2 3 4;3 4 5];
tp=t.*t;
x=exp(-(t.^2));
y=exp(-(t.*t));
z=exp(-(tp));
gives the results:
x =
0.3679 0.0183 0.0001
0.0183 0.0001 0.0000
0.0001 0.0000 0.0000
y =
0.3679 0.0183 0.0001
0.0183 0.0001 0.0000
0.0001 0.0000 0.0000
z=
0.3679 0.0183 0.0001
0.0183 0.0001 0.0000
0.0001 0.0000 0.0000
And using a scalar:
p=3;
pp=p^2;
x=exp(-(p^2));
y=exp(-(p*p));
z=exp(-pp);
gives the results:
x =
1.2341e-004
y =
1.2341e-004
z =
1.2341e-004
JavaScript does require semicolons, it's just that the interpreter will insert them for you on line breaks where possible*.
Unfortunately, the code
var a = new B(args)(stuff)()
does not result in a syntax error, so no ;
will be inserted. (An example which can run is
var answer = new Function("x", "return x")(function(){return 42;})();
To avoid surprises like this, train yourself to always end a statement with ;
.
If you are using the new** Gradle build system then getPackageName
will oddly return application Id, not package name. So MasterGaurav's answer is correct but he doesn't need to start off with ++
If by application id, you're referring to package name...
See more about the differences here.
** not so new at this point
++ I realize that his answer made perfect sense in 2011
Apple simply recommends declaring an isX
getter for stylistic purposes. It doesn't matter whether you customize the getter name or not, as long as you use the dot notation or message notation with the correct name. If you're going to use the dot notation it makes no difference, you still access it by the property name:
@property (nonatomic, assign) BOOL working;
[self setWorking:YES]; // Or self.working = YES;
BOOL working = [self working]; // Or = self.working;
Or
@property (nonatomic, assign, getter=isWorking) BOOL working;
[self setWorking:YES]; // Or self.working = YES;, same as above
BOOL working = [self isWorking]; // Or = self.working;, also same as above
Just append a div
with that class to body
, then remove it when you're done:
// Show the backdrop
$('<div class="modal-backdrop"></div>').appendTo(document.body);
// Remove it (later)
$(".modal-backdrop").remove();
Live Example:
$("input").click(function() {_x000D_
var bd = $('<div class="modal-backdrop"></div>');_x000D_
bd.appendTo(document.body);_x000D_
setTimeout(function() {_x000D_
bd.remove();_x000D_
}, 2000);_x000D_
});
_x000D_
<link href="//netdna.bootstrapcdn.com/twitter-bootstrap/2.3.2/css/bootstrap-combined.min.css" rel="stylesheet" type="text/css" />_x000D_
<script src="//code.jquery.com/jquery.min.js"></script>_x000D_
<script src="//netdna.bootstrapcdn.com/twitter-bootstrap/2.3.2/js/bootstrap.min.js"></script>_x000D_
<p>Click the button to get the backdrop for two seconds.</p>_x000D_
<input type="button" value="Click Me">
_x000D_
It may be curable by increasing the stack size - but a better solution would be to work out how to avoid recursing so much. A recursive solution can always be converted to an iterative solution - which will make your code scale to larger inputs much more cleanly. Otherwise you'll really be guessing at how much stack to provide, which may not even be obvious from the input.
Are you absolutely sure it's failing due to the size of the input rather than a bug in the code, by the way? Just how deep is this recursion?
EDIT: Okay, having seen the update, I would personally try to rewrite it to avoid using recursion. Generally having a Stack<T>
of "things still do to" is a good starting point to remove recursion.
I believe you can also do:
$sortDirection = 'desc';
$user->with(['comments' => function ($query) use ($sortDirection) {
$query->orderBy('column', $sortDirection);
}]);
That allows you to run arbitrary logic on each related comment record. You could have stuff in there like:
$query->where('timestamp', '<', $someTime)->orderBy('timestamp', $sortDirection);
From the VIM Documentation
To clear the last used search pattern:
:let @/ = ""
This will not set the pattern to an empty string, because that would match everywhere. The pattern is really cleared, like when starting Vim.
For anyone who is searching for a solution about posting to Instagram using AWS lambda and puppeteer (chrome-aws-lambda). Noted that this solution allow you to post 1 photo for each post only. If you are not using lambda, just replace chrome-aws-lambda
with puppeteer
.
For the first launch of lambda, it is normal that will not work because instagram detects “Suspicious login attempt”. Just goto instagram page using your PC and approve it, everything should be fine.
Here's my code, feel free to optimize it:
// instagram.js
const chromium = require('chrome-aws-lambda');
const username = process.env.IG_USERNAME;
const password = process.env.IG_PASSWORD;
module.exports.post = async function(fileToUpload, caption){
const browser = await chromium.puppeteer.launch({
args: [...chromium.args, '--window-size=520,700'],
defaultViewport: chromium.defaultViewport,
executablePath: await chromium.executablePath,
headless: false,
ignoreHTTPSErrors: true,
});
const page = await browser.newPage();
await page.setUserAgent('Mozilla/5.0 (iPhone; CPU iPhone OS 10_3_2 like Mac OS X) AppleWebKit/603.2.4 (KHTML, like Gecko) FxiOS/7.5b3349 Mobile/14F89 Safari/603.2.4');
await page.goto('https://www.instagram.com/', {waitUntil: 'networkidle2'});
const [buttonLogIn] = await page.$x("//button[contains(., 'Log In')]");
if (buttonLogIn) {
await buttonLogIn.click();
}
await page.waitFor('input[name="username"]');
await page.type('input[name="username"]', username)
await page.type('input[name="password"]', password)
await page.click('form button[type="submit"]');
await page.waitFor(3000);
const [buttonSaveInfo] = await page.$x("//button[contains(., 'Not Now')]");
if (buttonSaveInfo) {
await buttonSaveInfo.click();
}
await page.waitFor(3000);
const [buttonNotificationNotNow] = await page.$x("//button[contains(., 'Not Now')]");
const [buttonNotificationCancel] = await page.$x("//button[contains(., 'Cancel')]");
if (buttonNotificationNotNow) {
await buttonNotificationNotNow.click();
} else if (buttonNotificationCancel) {
await buttonNotificationCancel.click();
}
await page.waitFor('form[enctype="multipart/form-data"]');
const inputUploadHandle = await page.$('form[enctype="multipart/form-data"] input[type=file]');
await page.waitFor(5000);
const [buttonPopUpNotNow] = await page.$x("//button[contains(., 'Not Now')]");
const [buttonPopUpCancel] = await page.$x("//button[contains(., 'Cancel')]");
if (buttonPopUpNotNow) {
await buttonPopUpNotNow.click();
} else if (buttonPopUpCancel) {
await buttonPopUpCancel.click();
}
await page.click('[data-testid="new-post-button"]')
await inputUploadHandle.uploadFile(fileToUpload);
await page.waitFor(3000);
const [buttonNext] = await page.$x("//button[contains(., 'Next')]");
await buttonNext.click();
await page.waitFor(3000);
await page.type('textarea', caption);
const [buttonShare] = await page.$x("//button[contains(., 'Share')]");
await buttonShare.click();
await page.waitFor(3000);
return true;
};
// handler.js
await instagram.post('/tmp/image.png', '#text');
it must be local file path, if it is url, download it to /tmp folder first.
Use the 'string' key of the hashmap, to access its value which is your tab class.
Tab mytab = hash.get("your_string_key_used_to_insert");
You can specify a custom class to the top element of the dialog via the option dialogClass
$("#success").dialog({
...
dialogClass:"myClass",
...
});
Then you can target this class in CSS via .myClass.ui-dialog
.
Okay, from your question, you just simply want to read a particular column. So, while iterating over a row and then on its cells, your can simply check the index of the column.
Iterator<Row> rowIterator = mySheet.iterator(); // Traversing over each row of XLSX file
while (rowIterator.hasNext()) {
Row row = rowIterator.next(); // For each row, iterate through each columns
Iterator<Cell> cellIterator = row.cellIterator();
while (cellIterator.hasNext()) {
Cell cell = cellIterator.next();
println "column index"+cell.getColumnIndex()//You will have your columns fixed in Excel file
if(cell.getColumnIndex()==3)//for example of c
{
print "done"
}
}
}
I am using POI 3.12-- 'org.apache.poi:poi:3.12' Hope it helps. Cheers!
Another alternative, which is also quite popular is the Java Service Wrapper. This is also quite popular around the OSS community.
Regarding the upvoted answer, I liked it except that if the resulting "listfiles" array is used in an array formula {CSE}, the list values come out all in a horizontal row. To make them come out in a vertical column, I simply made the array two dimensional as follows:
ReDim vaArray(1 To oFiles.Count, 0)
i = 1
For Each oFile In oFiles
vaArray(i, 0) = oFile.Name
i = i + 1
Next
If your task is not to invent the line-by-line reading function, but just to read the file line-by-line, you may use a typical code snippet involving the getline()
function (see the manual page here):
#define _GNU_SOURCE
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
FILE * fp;
char * line = NULL;
size_t len = 0;
ssize_t read;
fp = fopen("/etc/motd", "r");
if (fp == NULL)
exit(EXIT_FAILURE);
while ((read = getline(&line, &len, fp)) != -1) {
printf("Retrieved line of length %zu:\n", read);
printf("%s", line);
}
fclose(fp);
if (line)
free(line);
exit(EXIT_SUCCESS);
}
Just to clarify: from within your app, you can simply refer to the emulator as 'localhost' or 127.0.0.1.
Web traffic is routed through your development machine, so the emulator's external IP is whatever IP has been assigned to that machine by your provider. The development machine can always be reached from your device at 10.0.2.2.
Since you were asking only about the emulator's IP, what is it you're trying to do?
The bootstrap v4 starter template css uses:
body {
padding-top: 5rem;
}
You can't kill a goroutine from outside. You can signal a goroutine to stop using a channel, but there's no handle on goroutines to do any sort of meta management. Goroutines are intended to cooperatively solve problems, so killing one that is misbehaving would almost never be an adequate response. If you want isolation for robustness, you probably want a process.
Can you try using document.location.replace()
it is used to clear the last entry in the history and replace it with the address of a new url. replace()
removes the URL of the current document from the document history, meaning that it is not possible to use the "back" button to navigate back to the original document.
<script type="text/javascript">
function Navigate(){
window.location.replace('your link');
return false;
}
</script>
HTML:
<button onclick="Navigate()">Replace document</button>
This is a combination of the above, because I had to read several posts to understand.
Content-Type
to application/json
Accept
to application/json
{ "Obj1" : { "key1" : "val1" } }
Hope this helps!
Other answers have shown you how to use JUnit to set up test classes. JUnit is not the only Java test framework. Concentrating on the technical details of using a framework however detracts from the most important concepts that should be guiding your actions, so I will talk about those.
Testing (of all kinds of all kinds of things) compares the actual behaviour of something (The System Under Test, SUT) with its expected behaviour.
Automated testing can be done using a computer program. Because that comparison is being done by an inflexible and unintelligent computer program, the expected behaviour must be precisely and unambiguously known.
What a program or part of a program (a class or method) is expected to do is its specification. Testing software therefore requires that you have a specification for the SUT. This might be an explicit description, or an implicit specification in your head of what is expected.
Automated unit testing therefore requires a precise and unambiguous specification of the class or method you are testing.
But you needed that specification when you set out to write that code. So part of what testing is about actually begins before you write even one line of the SUT. The testing technique of Test Driven Development (TDD) takes that idea to an extreme, and has you create the unit testing code before you write the code to be tested.
Unit testing frameworks test your SUT using assertions. An assertion is a logical expression (an expression with a boolean
result type; a predicate) that must be true
if the SUT is behaving correctly. The specification must therefore be expressed (or re-expressed) as assertions.
A useful technique for expressing a specification as assertions is programming by contract. These specifications are in terms of postconditions. A postcondition is an assertion about the publicly visible state of the SUT after return from a method or a constructor. Some methods have postconditions
that are invariants, which are predicates that are true before and after execution of the method. A class can also be said to have invariants, which are postconditions of every constructor and method of the class, and hence should always be true. Postconditions (And invariants) are expressed only in terms of publicity visible state: public
and protected
fields, the values returned by returned by public
and protected
methods (such as getters), and the publicly visible state of objects passed (by reference) to methods.
Many beginners post questions here asking how they can test some code, presenting the code but without stating the specification for that code. As this discussion shows, it is impossible for anyone to give a good answer to such a question, because at best potential answereres must guess the specification, and might do so incorrectly. The asker of the question evidently does not understand the importance of a specification, and is thus a novice who needs to understand the fundamentals I've described here before trying to write some test code.
It's also worth noting that you can use *
and **
when calling functions as well. This is a shortcut that allows you to pass multiple arguments to a function directly using either a list/tuple or a dictionary. For example, if you have the following function:
def foo(x,y,z):
print("x=" + str(x))
print("y=" + str(y))
print("z=" + str(z))
You can do things like:
>>> mylist = [1,2,3]
>>> foo(*mylist)
x=1
y=2
z=3
>>> mydict = {'x':1,'y':2,'z':3}
>>> foo(**mydict)
x=1
y=2
z=3
>>> mytuple = (1, 2, 3)
>>> foo(*mytuple)
x=1
y=2
z=3
Note: The keys in mydict
have to be named exactly like the parameters of function foo
. Otherwise it will throw a TypeError
:
>>> mydict = {'x':1,'y':2,'z':3,'badnews':9}
>>> foo(**mydict)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: foo() got an unexpected keyword argument 'badnews'
What worked for me was
git reset HEAD app/views/data/landingpage.js.erb
git restore app/views/data/landingpage.js.erb
where the file I wanted to restore was app/views/data/landingpage.js.erb
In the following example you have an PHP array, then firstly create a JavaScript array by a PHP array:
<script type="javascript">
day = new Array(<?php echo implode(',', $day); ?>);
week = new Array(<?php echo implode(',',$week); ?>);
month = new Array(<?php echo implode(',',$month); ?>);
<!-- Then pass it to the JavaScript function: -->
drawChart(<?php echo count($day); ?>, day, week, month);
</script>
You should add namespace if you are not using it:
System.Windows.Forms.MessageBox.Show("Some text", "Some title",
System.Windows.Forms.MessageBoxButtons.OK,
System.Windows.Forms.MessageBoxIcon.Error);
Alternatively, you can add at the begining of your file:
using System.Windows.Forms
and then use (as stated in previous answers):
MessageBox.Show("Some text", "Some title",
MessageBoxButtons.OK, MessageBoxIcon.Error);
Visual Studio 2013: Yes to both adding to the watch windows during debugging and dragging variables or typing them in without "user::". But before any of that would work I also needed to go to Tools > Options, then Debugging > General and had to scroll right down to the bottom of the right hand pane to be able to tick "Use Managed Compatibility Mode". Then I had to stop and restart debugging. Finally the above advice worked. Many thanks to the above and to this article: Visual Studio 2015 Debugging: Can't expand local variables?
Button button = new Button();
button.Click += (s,e) => { your code; };
//button.Click += new EventHandler(button_Click);
container.Controls.Add(button);
//protected void button_Click (object sender, EventArgs e) { }
std::string::iterator end_pos = std::remove(str.begin(), str.end(), ' ');
str.erase(end_pos, str.end());
In codeigniter you can't pass parameters in the url as you are doing in core php.So remove the "?" and "product_id" and simply pass the id.If you want more security you can encrypt the id and pass it.
There is no need to remove any .iml
files. Follow this:
File
->
Open...
and choose your newly created build.gradle
Open Existing Project
Delete Existing Project and Import
If you also want to keep "?" and just remove everything after that particular character, you can do:
var str = "/Controller/Action?id=11112&value=4444",
stripped = str.substring(0, str.indexOf('?') + '?'.length);
// output: /Controller/Action?
This is my version of a bash script. It takes database name as a parameter and converts all tables to another charset and collation (given by another parameters or default value defined in the script).
#!/bin/bash
# mycollate.sh <database> [<charset> <collation>]
# changes MySQL/MariaDB charset and collation for one database - all tables and
# all columns in all tables
DB="$1"
CHARSET="$2"
COLL="$3"
[ -n "$DB" ] || exit 1
[ -n "$CHARSET" ] || CHARSET="utf8mb4"
[ -n "$COLL" ] || COLL="utf8mb4_general_ci"
echo $DB
echo "ALTER DATABASE $DB CHARACTER SET $CHARSET COLLATE $COLL;" | mysql
echo "USE $DB; SHOW TABLES;" | mysql -s | (
while read TABLE; do
echo $DB.$TABLE
echo "ALTER TABLE $TABLE CONVERT TO CHARACTER SET $CHARSET COLLATE $COLL;" | mysql $DB
done
)
You can just iterate over the elements in the array and call array[i].trim()
on each element
Step 1: fetch list of commits:
git log
You'll get list like in this example:
[Comp:Folder User$ git log
commit 54b11d42e12dc6e9f070a8b5095a4492216d5320
Author: author <[email protected]>
Date: Fri Jul 8 23:42:22 2016 +0300
This is last commit message
commit fd6cb176297acca4dbc69d15d6b7f78a2463482f
Author: author <[email protected]>
Date: Fri Jun 24 20:20:24 2016 +0300
This is previous commit message
commit ab0de062136da650ffc27cfb57febac8efb84b8d
Author: author <[email protected]>
Date: Thu Jun 23 00:41:55 2016 +0300
This is previous previous commit message
...
Step 2: copy needed commit hash and paste it for checkout:
git checkout fd6cb176297acca4dbc69d15d6b7f78a2463482f
That's all.
Using properties is to me more intuitive and fits better into most code.
Comparing
o.x = 5
ox = o.x
vs.
o.setX(5)
ox = o.getX()
is to me quite obvious which is easier to read. Also properties allows for private variables much easier.
Since @Doua Beri is experiencing connection close even when there are 1 Hz SENDs, it may be instead be due to size limits on messages.
This passage from Spring's WebSockets may be useful, with my emphasis ...
Although in theory a WebSocket message can be almost unlimited in size, in practice WebSocket servers impose limits — for example, 8K on Tomcat and 64K on Jetty. For this reason STOMP clients such as stomp.js split larger STOMP messages at 16K boundaries and send them as multiple WebSocket messages thus requiring the server to buffer and re-assemble.
You can use justify-content: space-between
in .test
like so:
.test {_x000D_
display: flex;_x000D_
justify-content: space-between;_x000D_
width: 20rem;_x000D_
border: .1rem red solid;_x000D_
}
_x000D_
<div class="test">_x000D_
<button>test</button>_x000D_
<button>test</button>_x000D_
</div>
_x000D_
For those who want to use Bootstrap 4 can use justify-content-between
:
div {_x000D_
width: 20rem;_x000D_
border: .1rem red solid;_x000D_
}
_x000D_
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" rel="stylesheet" />_x000D_
<div class="d-flex justify-content-between">_x000D_
<button>test</button>_x000D_
<button>test</button>_x000D_
</div>
_x000D_
Use -d
(full list of file tests)
if (-d "cgi-bin") {
# directory called cgi-bin exists
}
elsif (-e "cgi-bin") {
# cgi-bin exists but is not a directory
}
else {
# nothing called cgi-bin exists
}
As a note, -e
doesn't distinguish between files and directories. To check if something exists and is a plain file, use -f
.
While rolling stone's answer is good, straightforward and functional, I think there are two things it does not solve.
Introduce the content types framework, which exposes some objects that allow us to create a "generic foreign key" on the PhoneNumber model. Then, we can define the reverse relationship on Dude and Business
from django.contrib.contenttypes.fields import GenericForeignKey, GenericRelation
from django.contrib.contenttypes.models import ContentType
from django.db import models
class PhoneNumber(models.Model):
number = models.CharField()
content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE)
object_id = models.PositiveIntegerField()
owner = GenericForeignKey()
class Dude(models.Model):
numbers = GenericRelation(PhoneNumber)
class Business(models.Model):
numbers = GenericRelation(PhoneNumber)
See the docs for details, and perhaps check out this article for a quick tutorial.
Also, here is an article that argues against the use of Generic FKs.
instead of files use pipes and if u wana use C and not C++ u can use popen like this
#include<stdlib.h>
#include<stdio.h>
FILE *fp= popen("date +F","r");
and use *fp as a normal file pointer with fgets and all
if u wana use c++ strings, fork a child, invoke the command and then pipe it to the parent.
#include <stdlib.h>
#include <iostream>
#include <string>
using namespace std;
string currentday;
int dependPipe[2];
pipe(dependPipe);// make the pipe
if(fork()){//parent
dup2(dependPipe[0],0);//convert parent's std input to pipe's output
close(dependPipe[1]);
getline(cin,currentday);
} else {//child
dup2(dependPipe[1],1);//convert child's std output to pipe's input
close(dependPipe[0]);
system("date +%F");
}
// make a similar 1 for date +T but really i recommend u stick with stuff in time.h GL
Just concatenate a string to the end of the value:
Fields!<your field>.Value & " " 'test'
and this should work!
You can do it with Linq, as mamoo showed, but the oldies are good too:
var filteredDataTable = dt.Select(@"EmpId > 2
AND (EmpName <> 'abc' OR EmpName <> 'xyz')
AND EmpName like '%il%'" );
All the examples are great, but I figure I'd add one more to show how working in a "tidy" format simplifies things. Right now the data frame is in "wide" format meaning the variables "a" through "d" are represented in columns. To get to a "tidy" (or long) format, you can use gather()
from the tidyr
package which shifts the variables in columns "a" through "d" into rows. Then you use the group_by()
and summarize()
functions to get the mean of each group. If you want to present the data in a wide format, just tack on an additional call to the spread()
function.
library(tidyverse)
# Create reproducible df
set.seed(101)
df <- tibble(a = sample(1:5, 10, replace=T),
b = sample(1:5, 10, replace=T),
c = sample(1:5, 10, replace=T),
d = sample(1:5, 10, replace=T),
grp = sample(1:3, 10, replace=T))
# Convert to tidy format using gather
df %>%
gather(key = variable, value = value, a:d) %>%
group_by(grp, variable) %>%
summarize(mean = mean(value)) %>%
spread(variable, mean)
#> Source: local data frame [3 x 5]
#> Groups: grp [3]
#>
#> grp a b c d
#> * <int> <dbl> <dbl> <dbl> <dbl>
#> 1 1 3.000000 3.5 3.250000 3.250000
#> 2 2 1.666667 4.0 4.666667 2.666667
#> 3 3 3.333333 3.0 2.333333 2.333333
If you are using jQuery then by using plugin formInteract, you just need to do this:
// Just keep the HTML as it is.
<input name="searchTxt" type="text" maxlength="512" id="searchTxt" class="searchField"/>
At bottom of the page just include this plugin file and write this code:
// Initialize one time at the bottom of the page.
var search= $("#searchTxt).formInteract();
search.getAjax("http://www.myurl.com/search/", function(rsp){
// Now do whatever you want to with your response
});
Or if using a parameterized URL then use this:
$.get("http://www.myurl.com/search/"+search.get().searchTxt, {}, function(rsp){
// Now do work with your response;
})
Here is the link to project https://bitbucket.org/ranjeet1985/forminteract
You can use this plugin for many purposes like getting the value of a form, putting values into a form, validation of forms and many more. You can see some example of code in the index.html file of the project.
Of course I am the author of this project and all are welcome to make it better.
There are multiple tools, mentioned by many great answers, I'm going to pick one.
I downloaded latest version (5.1.7) from [AngusJ]: Resource Hacker. All the needed information can be found on that page (command line options, scripts, ...). In the following walkthrough I'm going to operate on 2 executables (lab rats) which (for obvious reasons) I've copied in my cwd:
Before going further, I want to mention that ResourceHacker has a funny terminal output, and the the following copy / paste fragments might generate a bit of confusion.
This is more like a preliminary step, to get acquainted with the environment, to show there's no funky business going on, ...
e:\Work\Dev\StackOverflow\q000284258> sopr.bat *** Set shorter prompt to better fit when pasted in StackOverflow (or other) pages *** [prompt]> dir Volume in drive E is Work Volume Serial Number is 3655-6FED Directory of e:\Work\Dev\StackOverflow\q000284258 2019-01-28 20:09 <DIR> . 2019-01-28 20:09 <DIR> .. 2016-11-03 09:17 5,413,376 cmake.exe 2019-01-03 02:06 5,479,424 ResourceHacker.exe 2019-01-28 20:30 496 ResourceHacker.ini 3 File(s) 10,893,296 bytes 2 Dir(s) 103,723,261,952 bytes free [prompt]> set PATH=%PATH%;c:\Install\x64\CMake\CMake\3.6.3\bin [prompt]> .\cmake --help >nul 2>&1 [prompt]> echo %errorlevel% 0 [prompt]> .\ResourceHacker.exe -help [prompt]> ================================== Resource Hacker Command Line Help: ================================== -help : displays these abbreviated help instructions. -help commandline : displays help for single commandline instructions -help script : displays help for script file instructions. [prompt]> echo %errorlevel% 0
As seen, the executables are OK, they run fine, and here's how their Details (that we care about) look like:
Resource files are text files that contain resources. A resource (simplified) has:
For more details check [MS.Docs]: About Resource Files. There are many tools (mentioned in existing answers) that facilitate resource file editing like:
But, since it's about Resource Hacker, and:
I'm going to use it for this step (-action extract
)
Next, In order for a resource to be embedded into an .exe (.dll, ...) it must be compiled to a binary form, which fits into the PE format. Again, there are lots of tools who can achieve this, but as you probably guessed I'm going to stick to Resource Hacker (-action compile
).
[prompt]> :: Extract the resources into a file [prompt]> .\ResourceHacker.exe -open .\ResourceHacker.exe -save .\sample.rc -action extract -mask VersionInfo,, -log con [prompt]> [28 Jan 2019, 20:58:03] Current Directory: e:\Work\Dev\StackOverflow\q000284258 Commandline: .\ResourceHacker.exe -open .\ResourceHacker.exe -save .\sample.rc -action extract -mask VersionInfo,, -log con Open : e:\Work\Dev\StackOverflow\q000284258\ResourceHacker.exe Save : e:\Work\Dev\StackOverflow\q000284258\sample.rc Success! [prompt]> :: Modify the resource file and set our own values [prompt]> [prompt]> :: Compile the resource file [prompt]> .\ResourceHacker.exe -open .\sample.rc -save .\sample.res -action compile -log con [prompt]> [28 Jan 2019, 20:59:51] Current Directory: e:\Work\Dev\StackOverflow\q000284258 Commandline: .\ResourceHacker.exe -open .\sample.rc -save .\sample.res -action compile -log con Open : e:\Work\Dev\StackOverflow\q000284258\sample.rc Save : e:\Work\Dev\StackOverflow\q000284258\sample.res Compiling: e:\Work\Dev\StackOverflow\q000284258\sample.rc Success! [prompt]> dir /b cmake.exe ResourceHacker.exe ResourceHacker.ini sample.rc sample.res
In your case saving and editing the resource file won't be necessary, as the file will already be present, I just did it for demonstrating purposes. Below it's the resource file after being modified (and thus before being compiled).
sample.rc:
1 VERSIONINFO
FILEVERSION 3,1,4,1592
PRODUCTVERSION 2,7,1,8
FILEOS 0x4
FILETYPE 0x1
{
BLOCK "StringFileInfo"
{
BLOCK "040904E4"
{
VALUE "CompanyName", "Cristi Fati\0"
VALUE "FileDescription", "20190128 - SO q000284258 demo\0"
VALUE "FileVersion", "3.1.4.1592\0"
VALUE "ProductName", "Colonel Panic\0"
VALUE "InternalName", "100\0"
VALUE "LegalCopyright", "(c) Cristi Fati 1999-2999\0"
VALUE "OriginalFilename", "ResHack\0"
VALUE "ProductVersion", "2.7.1.8\0"
}
}
BLOCK "VarFileInfo"
{
VALUE "Translation", 0x0409 0x04E4
}
}
This will also be performed by Resource Hacker (-action addoverwrite
). Since the .exes are already copied I'm going to edit their resources in place.
[prompt]> .\ResourceHacker.exe -open .\cmake.exe -save .\cmake.exe -res .\sample.res -action addoverwrite -mask VersionInfo,, -log con [prompt]> [28 Jan 2019, 21:17:19] Current Directory: e:\Work\Dev\StackOverflow\q000284258 Commandline: .\ResourceHacker.exe -open .\cmake.exe -save .\cmake.exe -res .\sample.res -action addoverwrite -mask VersionInfo,, -log con Open : e:\Work\Dev\StackOverflow\q000284258\cmake.exe Save : e:\Work\Dev\StackOverflow\q000284258\cmake.exe Resource: e:\Work\Dev\StackOverflow\q000284258\sample.res Added: VERSIONINFO,1,1033 Success! [prompt]> copy ResourceHacker.exe ResourceHackerTemp.exe 1 file(s) copied. [prompt]> .\ResourceHackerTemp.exe -open .\ResourceHacker.exe -save .\ResourceHacker.exe -res .\sample.res -action addoverwrite -mask VersionInfo,, -log con [prompt]> [28 Jan 2019, 21:19:29] Current Directory: e:\Work\Dev\StackOverflow\q000284258 Commandline: .\ResourceHackerTemp.exe -open .\ResourceHacker.exe -save .\ResourceHacker.exe -res .\sample.res -action addoverwrite -mask VersionInfo,, -log con Open : e:\Work\Dev\StackOverflow\q000284258\ResourceHacker.exe Save : e:\Work\Dev\StackOverflow\q000284258\ResourceHacker.exe Resource: e:\Work\Dev\StackOverflow\q000284258\sample.res Modified: VERSIONINFO,1,1033 Success! [prompt]> del /f /q ResourceHackerTemp.* [prompt]> dir Volume in drive E is Work Volume Serial Number is 3655-6FED Directory of e:\Work\Dev\StackOverflow\q000284258 2019-01-28 21:20 <DIR> . 2019-01-28 21:20 <DIR> .. 2016-11-03 09:17 5,414,400 cmake.exe 2019-01-03 02:06 5,479,424 ResourceHacker.exe 2019-01-28 21:17 551 ResourceHacker.ini 2019-01-28 20:05 1,156 sample.rc 2019-01-28 20:59 792 sample.res 5 File(s) 10,896,323 bytes 2 Dir(s) 103,723,253,760 bytes free
As seen, I had to d a little trick (gainarie) as I can't (at least I don't think I can) modify the .exe while in use.
This is an optional phase, to make sure that:
[prompt]> .\cmake --help >nul 2>&1 [prompt]> echo %errorlevel% 0 [prompt]> .\ResourceHacker.exe -help [prompt]> ================================== Resource Hacker Command Line Help: ================================== -help : displays these abbreviated help instructions. -help commandline : displays help for single commandline instructions -help script : displays help for script file instructions. [prompt]> echo %errorlevel% 0
And their Details:
As it was mentioned by the others you can substitute Lambda function instead of function pointer. I am using this method in my C++ interface to F77 ODE solver RKSUITE.
//C interface to Fortran subroutine UT
extern "C" void UT(void(*)(double*,double*,double*),double*,double*,double*,
double*,double*,double*,int*);
// C++ wrapper which calls extern "C" void UT routine
static void rk_ut(void(*)(double*,double*,double*),double*,double*,double*,
double*,double*,double*,int*);
// Call of rk_ut with lambda passed instead of function pointer to derivative
// routine
mathlib::RungeKuttaSolver::rk_ut([](double* T,double* Y,double* YP)->void{YP[0]=Y[1]; YP[1]= -Y[0];}, TWANT,T,Y,YP,YMAX,WORK,UFLAG);
Similar to previous answers I used the following:
Array.prototype.getIemtByParam = function(paramPair) {
var key = Object.keys(paramPair)[0];
return this.find(function(item){return ((item[key] == paramPair[key]) ? true: false)});
}
usage:
myArray.getIemtByParam(
{name: 'Sasha'}
);
This may help... use the following code and browse the folder you want to set as the working folder
setwd(choose.dir())
Now there is an official way to add "PlantUML integration" plugin to your JetBrains product.
Installation steps please refer: https://stackoverflow.com/a/53387418/5320704
When you need to connect to github with a normal request (git pull origin master
), setting the Host as *
in ~/.ssh/config
worked for me, any other Host (say, "github" or "gb") wasn't working.
Host *
User git
Hostname github.com
PreferredAuthentications publickey
IdentityFile ~/.ssh/id_rsa_xxx
You must run your mysql by xampp-controle.exe in folder XAMPP. After that login:
mysql -u root
PHP runs on the server before the page is sent to the user, JavaScript is run on the user's computer once it is received, so the PHP script has already executed.
If you want to pass a JavaScript value to a PHP script, you'd have to do an XMLHttpRequest to send the data back to the server.
Here's a previous question that you can follow for more information: Ajax Tutorial
Now if you just need to pass a form value to the server, you can also just do a normal form post, that does the same thing, but the whole page has to be refreshed.
<?php
if(isset($_POST))
{
print_r($_POST);
}
?>
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
<input type="text" name="data" value="1" />
<input type="submit" value="Submit" />
</form>
Clicking submit will submit the page, and print out the submitted data.
If the language you use accepts {}
, you can use [0-9]{4,6}
.
If not, you'll have to use [0-9][0-9][0-9][0-9][0-9]?[0-9]?
.
The DOMContentLoaded
event will fire as soon as the DOM hierarchy has been fully constructed, the load
event will do it when all the images and sub-frames have finished loading.
DOMContentLoaded
will work on most modern browsers, but not on IE including IE9 and above. There are some workarounds to mimic this event on older versions of IE, like the used on the jQuery library, they attach the IE specific onreadystatechange
event.
I just want to share my new finding: https://laragon.org/docs/index.html
I just used it for 1 hour and it looks promising.
How to add another PHP version to Laragon
How to add phpMyAdmin to Laragon
I'm not affiliated in any way with Laragon. Just found it on Google looking for "XAMPP Windows alteratives"
All I had to do was add:
line-height: 0px;
in my
<tr ...>
The source code for the Android mobile application open-gpstracker which you appreciated is available here.
You can checkout the code using SVN client application or via Git:
Debugging the source code will surely help you.
I think that you can do something like this:
let routeData = this.$router.resolve({name: 'routeName', query: {data: "someData"}});
window.open(routeData.href, '_blank');
It worked for me.
Dim f as Range
Set f=ActiveSheet.Cells.Find(...)
If Not f Is Nothing then
msgbox "Row=" & f.Row & vbcrlf & "Column=" & f.Column
Else
msgbox "value not found!"
End If
This is the simplest code to draw a rotated and scaled image:
function drawImage(ctx, image, x, y, w, h, degrees){
ctx.save();
ctx.translate(x+w/2, y+h/2);
ctx.rotate(degrees*Math.PI/180.0);
ctx.translate(-x-w/2, -y-h/2);
ctx.drawImage(image, x, y, w, h);
ctx.restore();
}
Use tow function to solve it ,Very simple and useful:
HTML:
<input class="int-number" type="text" />
<input class="decimal-number" type="text" />
JQuery:
//Integer Number
$(document).on("input", ".int-number", function (e) {
this.value = this.value.replace(/[^0-9]/g, '');
});
//Decimal Number
$(document).on("input", ".decimal-number", function (e) {
this.value = this.value.replace(/[^0-9.]/g, '').replace(/(\..*)\./g, '$1');
});
or in a better way we can have like this
Let's say your primary key is an Integer and object you save is "ticket", then you can get it like this. When you save the object, id is always returned
//unboxing will occur here so that id here will be value type not the reference type. Now you can check id for 0 in case of save failure. like below:
int id = (Integer) session.save(ticket);
if(id==0)
your session.save call was not success.
else '
your call to session.save was successful.
After doing the git rm --cached
command, try adding myfile
to the .gitignore
file (create one if it does not exist). This should tell git to ignore myfile
.
The .gitignore
file is versioned, so you'll need to commit it and push it to the remote repository.
Replace
f = open(D\\python\\HW\\2_1 - Copy.cp,"r");
by
f = open("D:\\python\\HW\\2_1 - Copy.cp", "r")
What tutorial are you using?
Check out this snippet:
Private Sub openDialog()
Dim fd As Office.FileDialog
Set fd = Application.FileDialog(msoFileDialogFilePicker)
With fd
.AllowMultiSelect = False
' Set the title of the dialog box.
.Title = "Please select the file."
' Clear out the current filters, and add our own.
.Filters.Clear
.Filters.Add "Excel 2003", "*.xls"
.Filters.Add "All Files", "*.*"
' Show the dialog box. If the .Show method returns True, the
' user picked at least one file. If the .Show method returns
' False, the user clicked Cancel.
If .Show = True Then
txtFileName = .SelectedItems(1) 'replace txtFileName with your textbox
End If
End With
End Sub
I think this is what you are asking for.
I had originally asked myself the question "Do I need a PDB file deployed to my customer's machine?", and after reading this post, decided to exclude the file.
Everything worked fine, until today, when I was trying to figure out why a message box containing an Exception.StackTrace
was missing the file and line number information - necessary for troubleshooting the exception. I re-read this post and found the key nugget of information: that although the PDB is not necessary for the app to run, it is necessary for the file and line numbers to be present in the StackTrace
string. I included the PDB file in the executable folder and now all is fine.
Why not?
#header {
text-align: center;
}
#header ul {
display: inline;
}
The Android Studio website has recently (I think) provided some advice what kind of messages to expect from different log levels that may be useful along with Kurtis' answer:
This works, but all the children of the element with this class will also become transparent, without any way of preventing that.
.css-class-name {
opacity:0.8;
}
Example of not very good, but simple decision (not only for Jackson, also for Spring RestTemplate, etc.):
Set<MyClass> res = new HashSet<>();
objectMapper.readValue(json, res.getClass());
I am facing small trouble in returning a value from callback function in Node.js
This is not a "small trouble", it is actually impossible to "return" a value in the traditional sense from an asynchronous function.
Since you cannot "return the value" you must call the function that will need the value once you have it. @display_name already answered your question, but I just wanted to point out that the return in doCall is not returning the value in the traditional way. You could write doCall as follow:
function doCall(urlToCall, callback) {
urllib.request(urlToCall, { wd: 'nodejs' }, function (err, data, response) {
var statusCode = response.statusCode;
finalData = getResponseJson(statusCode, data.toString());
// call the function that needs the value
callback(finalData);
// we are done
return;
});
}
Line callback(finalData);
is what calls the function that needs the value that you got from the async function. But be aware that the return statement is used to indicate that the function ends here, but it does not mean that the value is returned to the caller (the caller already moved on.)
You can use typeof(N)
to get the actual object type, but what you want to do is check the tag, not the type of the DOM element.
In that case, use the elem.tagName
or elem.nodeName
property.
if you want to get really creative, you can use a dictionary of tagnames and anonymous closures instead if a switch or if/else.
Firstly, I highly recommend you do your CSS styling in an external CSS file, rather than doing it inline. It's much easier to maintain and can be more reusable using classes.
Working off Alex's answer (& Garret's clearfix) of "adding an element at the end with clear: both", you can do it like so:
<div id='outerdiv' style='border: 1px solid black; background-color: black;'>
<div style='width: 300px; border: red 1px dashed; float: left;'>
<p>xxxxxxxxxxxxxxxxxxxxxxxxxxxxx</p>
</div>
<div style='width: 300px; border: red 1px dashed; float: right;'>
<p>zzzzzzzzzzzzzzzzzzzzzzzzzzzzz</p>
</div>
<div style='clear:both;'></div>
</div>
This works (but as you can see inline CSS isn't so pretty).
You can use .exists (return boolean) in jpaRepository.
if(commercialRuleMsisdnRepo.exists(commercialRuleMsisdn.getRuleId())!=true){
jsRespon.setStatusDescription("SUCCESS ADD TO DB");
}else{
jsRespon.setStatusCode("ID already exists is database");
}
Given that you're only converting to int
s to then perform a comparison, I'd just switch the table definition around to using varchar
also:
Create table #myTempTable
(
num varchar(12)
)
insert into #myTempTable (num) values (1),(2),(3),(4),(5)
and remove all of the attempted CONVERT
s from the rest of the query.
SELECT a.name, a.value AS value, COUNT(*) AS pocet
FROM
(SELECT item.name, value.value
FROM mdl_feedback AS feedback
INNER JOIN mdl_feedback_item AS item
ON feedback.id = item.feedback
INNER JOIN mdl_feedback_value AS value
ON item.id = value.item
WHERE item.typ = 'multichoicerated' AND item.feedback IN (43)
) AS a
INNER JOIN #myTempTable
on a.value = #myTempTable.num
GROUP BY a.name, a.value ORDER BY a.name
I've been using this code to instantiate my custom segue subclass and run it programmatically. It seems to work. Anything wrong with this? I'm puzzled, reading all the other answers saying it cannot be done.
UIViewController *toViewController = [self.storyboard instantiateViewControllerWithIdentifier:@"OtherViewControllerId"];
MyCustomSegue *segue = [[MyCustomSegue alloc] initWithIdentifier:@"" source:self destination:toViewController];
[self prepareForSegue:segue sender:sender];
[segue perform];