my problem was to copy the whole source files contains .idea directory and my webstorm terminal commands were run on the original directory of the source
I delete the .idea directory and it worked fine
If you want the original URL just use the method as described by jthalborn. If you want to rebuild the url do like David Levesque explained, here is a code snippet for it:
final javax.servlet.http.HttpServletRequest req = (javax.servlet.http.HttpServletRequest) ...;
final int serverPort = req.getServerPort();
if ((serverPort == 80) || (serverPort == 443)) {
// No need to add the server port for standard HTTP and HTTPS ports, the scheme will help determine it.
url = String.format("%s://%s/...", req.getScheme(), req.getServerName(), ...);
} else {
url = String.format("%s://%s:%s...", req.getScheme(), req.getServerName(), serverPort, ...);
}
You still need to consider the case of a reverse-proxy:
Could use constants for the ports but not sure if there is a reliable source for them, default ports:
Most developers will know about port 80 and 443 anyways, so constants are not that helpful.
Also see this similar post.
#This definition gives an array of months between two dates.
import datetime
def MonthsBetweenDates(BeginDate, EndDate):
firstyearmonths = [mn for mn in range(BeginDate.month, 13)]<p>
lastyearmonths = [mn for mn in range(1, EndDate.month+1)]<p>
months = [mn for mn in range(1, 13)]<p>
numberofyearsbetween = EndDate.year - BeginDate.year - 1<p>
return firstyearmonths + months * numberofyearsbetween + lastyearmonths<p>
#example
BD = datetime.datetime.strptime("2000-35", '%Y-%j')
ED = datetime.datetime.strptime("2004-200", '%Y-%j')
MonthsBetweenDates(BD, ED)
What I have done in the past is declare my inner class collections using IList<Class>
, ICollection<Class>
or IEnumerable<Class>
(if static list) depending on whether or not I will have to do any number of the following in a method in my repository: enumerate, sort/order or modify. When I just need to enumerate (and maybe sort) over objects then I create a temp List<Class>
to work with the collection within an IEnumerable method. I think this practice would only be effective if the collection is relatively small, but it may be good practice in general, idk. Please correct me if there is evidence as to why this would not good practice.
Basically, the buttons in Twitter Bootstrap are controlled in CSS by ".btn{}". What you have to do is go to the CSS file and find where it says "btn" and change the color settings. However, it's not as simple as just doing that since you also have to change what color the button changes into when you highlight it, etc. To do THAT, you have to look for other tags in CSS like ".btn:hover{}", etc.
Changing it requires changing of the CSS. Here is a quick link to that file:
https://github.com/twbs/bootstrap/blob/master/dist/css/bootstrap.css
Please also consider to use
git clone --mirror path_to_source_repository
From the documentation:
Set up a mirror of the source repository. This implies --bare. Compared to --bare, --mirror not only maps local branches of the source to local branches of the target, it maps all refs (including remote-tracking branches, notes etc.) and sets up a refspec configuration such that all these refs are overwritten by a git remote update in the target repository.
For my responsive design, my drop-box down-arrow on the right side of the box (vertical accordion), accepted percentage as position. Initially the down-arrow was "position: absolute; right: 13px;". With the 97% positioning it worked like charm as follows:
> background: #ffffff;
> background-image: url(PATH-TO-arrow_down.png); /*fall back - IE */
> background-position: 97% center; /*fall back - IE */
> background-repeat: no-repeat; /*fall back - IE */
> background-image: url(PATH-TO-arrow_down.png) no-repeat 97% center;
> background: url(PATH-TO-arrow_down.png) no-repeat 97% center, -moz-linear-gradient(top, #ffffff 1%, #eaeaea 100%);
> background: url(PATH-TO-arrow_down.png) no-repeat 97% center, -webkit-gradient(linear, left top, left bottom, color-stop(1%,#ffffff), color-stop(100%,#eaeaea));
> background: url(PATH-TO-arrow_down.png) no-repeat 97% center, -webkit-linear-gradient(top, #ffffff 1%,#eaeaea 100%);
> background: url(PATH-TO-arrow_down.png) no-repeat 97% center, -o-linear-gradient(top, #ffffff 1%,#eaeaea 100%);<br />
> filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='#ffffff', endColorstr='#eaeaea',GradientType=0 );
P.S. Sorry, don't know how to handle the filters.
Using sed: It will insert at the end of line. You can also pass in variables as usual of course.
grep -qxF "port=9033" $light.conf
if [ $? -ne 0 ]; then
sed -i "$ a port=9033" $light.conf
else
echo "port=9033 already added"
fi
Using oneliner sed
grep -qxF "port=9033" $lightconf || sed -i "$ a port=9033" $lightconf
Using echo may not work under root, but will work like this. But it will not let you automate things if you are looking to do it since it might ask for password.
I had a problem when I was trying to edit from the root for a particular user. Just adding the $username
before was a fix for me.
grep -qxF "port=9033" light.conf
if [ $? -ne 0 ]; then
sudo -u $user_name echo "port=9033" >> light.conf
else
echo "already there"
fi
Can we see the structure of your table? If I am understanding this, then the assumption made by the query is that a record can be only meta_key - 'lat'
or meta_key = 'long'
not both because each row only has one meta_key
column and can only contain 1 corresponding value, not 2. That would explain why you don't get results when you connect the with an AND
; it's impossible.
#include <vector>
#include <algorithm>
int main()
{
int arr[5] = {4, 1, 3, 2, 6};
int x = -1;
std::vector<int> testVector(arr, arr + sizeof(arr) / sizeof(int) );
std::vector<int>::iterator it = std::find(testVector.begin(), testVector.end(), 3);
if (it != testVector.end())
{
x = it - testVector.begin();
}
return 0;
}
Or you can just build a vector in a normal way, without creating it from an array of ints and then use the same solution as shown in my example.
If I remember correctly (from a couple of years ago), one of the senior developers was talking about a fast way to bzero() on PowerPC (specs said we needed to zero almost all the memory on power up). It might not translate well (if at all) to x86, but it could be worth exploring.
The idea was to load a data cache line, clear that data cache line, and then write the cleared data cache line back to memory.
For what it is worth, I hope it helps.
Try setting the "endOfLine":"auto"
in your .prettierrc file (inside the object)
Or set
"prettier/prettier": ["error", {
..
"endOfLine":"auto"
..
}],
inside the rules object of the eslintrc file.
If you are using windows machine endOfLine can be "crlf" basing on your git config.
Try this, it will do the work:
log_file=$curr_dir/log_file.txt
exec > >(tee -a ${log_file} )
exec 2> >(tee -a ${log_file} >&2)
olliej's rounding method is wrong for negative numbers
Here's an alternative
int myInt = (int)(myDouble + (myDouble>0 ? 0.5 : -0.5))
You could of course use a rounding function from math.h
out: dict_values([{1:a, 2:b}])
in: str(dict.values())[14:-3]
out: 1:a, 2:b
Purely for visual purposes. Does not produce a useful product... Only useful if you want a long dictionary to print in a paragraph type form.
You should add AutoPostBack="true" to DropDownList1
<asp:DropDownList ID="ddmanu" runat="server" AutoPostBack="true"
DataSourceID="Sql_fur_model_manu"
DataTextField="manufacturer" DataValueField="manufacturer"
onselectedindexchanged="ddmanu_SelectedIndexChanged">
</asp:DropDownList>
Nowadays you should use modules. Put your code into the default function of a module and import the function into a script element.
client.js
:
export default function ()
{
alert ("test");
}
index.html
:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>test</title>
</head>
<body>
<script type="module">
import main from './client.js';
main ();
</script>
</body>
</html>
Put this in your Application.java
file
@ComponentScan(basePackages={"com.nervy.dialer"})
@EntityScan(basePackages="domain")
Only the thread unless your process has a single thread.
The permitted situations are a temporary whitelist where the background service behaves the same as before Android O.
Under certain circumstances, a background app is placed on a temporary whitelist for several minutes. While an app is on the whitelist, it can launch services without limitation, and its background services are permitted to run. An app is placed on the whitelist when it handles a task that's visible to the user, such as:
- Handling a high-priority Firebase Cloud Messaging (FCM) message.
- Receiving a broadcast, such as an SMS/MMS message.
- Executing a PendingIntent from a notification.
- Starting a VpnService before the VPN app promotes itself to the foreground.
Source: https://developer.android.com/about/versions/oreo/background.html
So in other words if your background service does not meet the whitelist requirements you have to use the new JobScheduler. It's basically the same as a background service, but it gets called periodically instead of running in the background continuously.
If you're using an IntentService, you can change to a JobIntentService. See @kosev's answer below.
Your can use your tokenizer and pad sequencing for a new piece of text. This is followed by model prediction. This will return the prediction as a numpy array plus the label itself.
For example:
new_complaint = ['Your service is not good']
seq = tokenizer.texts_to_sequences(new_complaint)
padded = pad_sequences(seq, maxlen=maxlen)
pred = model.predict(padded)
print(pred, labels[np.argmax(pred)])
The following query will generate ALTER queries that change the collation for all appropriate columns in all tables to a certain type (utf8_general_ci in my example below).
SELECT concat
(
'ALTER TABLE ',
t1.TABLE_SCHEMA,
'.',
t1.table_name,
' MODIFY ',
t1.column_name,
' ',
t1.data_type,
'(' ,
CHARACTER_MAXIMUM_LENGTH,
')',
' CHARACTER SET utf8 COLLATE utf8_general_ci;'
)
from
information_schema.columns t1
where
t1.TABLE_SCHEMA like 'you_db_name_goes_here' AND
t1.COLLATION_NAME IS NOT NULL AND
t1.COLLATION_NAME NOT IN ('utf8_general_ci');
For discussions above, here is an easy example to sort the primitive arrays in descending order.
import java.util.Arrays;
public class Main {
public static void main(String[] args) {
int[] nums = { 5, 4, 1, 2, 9, 7, 3, 8, 6, 0 };
Arrays.sort(nums);
// reverse the array, just like dumping the array!
// swap(1st, 1st-last) <= 1st: 0, 1st-last: nums.length - 1
// swap(2nd, 2nd-last) <= 2nd: i++, 2nd-last: j--
// swap(3rd, 3rd-last) <= 3rd: i++, 3rd-last: j--
//
for (int i = 0, j = nums.length - 1, tmp; i < j; i++, j--) {
tmp = nums[i];
nums[i] = nums[j];
nums[j] = tmp;
}
// dump the array (for Java 4/5/6/7/8/9)
for (int i = 0; i < nums.length; i++) {
System.out.println("nums[" + i + "] = " + nums[i]);
}
}
}
Output:
nums[0] = 9
nums[1] = 8
nums[2] = 7
nums[3] = 6
nums[4] = 5
nums[5] = 4
nums[6] = 3
nums[7] = 2
nums[8] = 1
nums[9] = 0
I tried to create a mapped network driver via 'net use' with admin privilege but failed, it does not show. And if I add it through UI, it disappeared after reboot, now I made that through powershell. So, I think you can run powershell scripts from a .bat file, and the script is
New-PSDrive -Name "P" -PSProvider "FileSystem" -Root "\\Server01\Public"
add -persist
at the end, you will create a persisted mapped network drive
New-PSDrive -Name "P" -PSProvider "FileSystem" -Root "\\Server01\Scripts" -Persist
for more details, refer New-PSDrive - Microsoft Docs
Since you are in a controller, the action method is given a Request
parameter.
You can access all POST data with $request->request->all();
.
This returns a key-value pair array.
When using GET requests you access data using $request->query->all();
@Html.TextBoxFor(m => m.EntryDate, new{ type = "date" })
or type = "time"
it will display a calendar
it will not work if you give @Html.EditorFor()
I wrote a general method that will add a border on whichever sides you wish in any UIView
. You can define thickness, color, margins and zOrder
for each side.
/*
view: the view to draw border around
thickness: thickness of the border on the given side
color: color of the border on the given side
margin: space between the border's outer edge and the view's frame edge on the given side.
zOrder: defines the order to add the borders to the view. The borders will be added by zOrder from lowest to highest, thus making the highest priority border visible when two borders overlap at the corners.
*/
+(void) drawBorderAroundUIView:(UIView *) view thicknessLeft:(CGFloat) thicknessLeft colorLeft:(UIColor *)colorLeft marginLeft:(CGFloat) marginLeft zOrderLeft:(int) zOrderLeft thicknessRight:(CGFloat) thicknessRight colorRight:(UIColor *)colorRight marginRight:(CGFloat) marginRight zOrderRight:(int) zOrderRight thicknessTop:(CGFloat) thicknessTop colorTop:(UIColor *)colorTop marginTop:(CGFloat) marginTop zOrderTop:(int) zOrderTop thicknessBottom:(CGFloat) thicknessBottom colorBottom:(UIColor *)colorBottom marginBottom:(CGFloat) marginBottom zOrderBottom:(int) zOrderBottom{
//make margins be the outside edge and make positive margin represent a smaller rectangle
marginBottom = -1 * marginBottom - thicknessBottom;
marginTop = -1 * marginTop - thicknessTop;
marginLeft = -1 * marginLeft - thicknessLeft;
marginRight = -1 * marginRight - thicknessRight;
//get reference points for corners
CGPoint upperLeftCorner = CGPointZero;
CGPoint lowerLeftCorner = CGPointMake(upperLeftCorner.x, upperLeftCorner.y + view.frame.size.height);
CGPoint upperRightCorner = CGPointMake(upperLeftCorner.x + view.frame.size.width, upperLeftCorner.y);
//left
CALayer *leftBorder = [CALayer layer];
leftBorder.frame = CGRectMake(upperLeftCorner.x - thicknessLeft - marginLeft, upperLeftCorner.y - thicknessTop - marginTop, thicknessLeft, view.frame.size.height + marginTop + marginBottom + thicknessBottom + thicknessTop);
leftBorder.backgroundColor = colorLeft.CGColor;
//right
CALayer *rightBorder = [CALayer layer];
rightBorder.frame = CGRectMake(upperRightCorner.x + marginRight, upperRightCorner.y - thicknessTop - marginTop, thicknessRight, view.frame.size.height + marginTop + marginBottom + thicknessBottom + thicknessTop);
rightBorder.backgroundColor = colorRight.CGColor;
//top
CALayer *topBorder = [CALayer layer];
topBorder.frame = CGRectMake(upperLeftCorner.x - thicknessLeft - marginLeft, upperLeftCorner.y - thicknessTop - marginTop, view.frame.size.width + marginLeft + marginRight + thicknessLeft + thicknessRight, thicknessTop);
topBorder.backgroundColor = colorTop.CGColor;
//bottom
CALayer *bottomBorder = [CALayer layer];
bottomBorder.frame = CGRectMake(upperLeftCorner.x - thicknessLeft - marginLeft, lowerLeftCorner.y + marginBottom, view.frame.size.width + marginLeft + marginRight + thicknessLeft + thicknessRight, thicknessBottom);
bottomBorder.backgroundColor = colorBottom.CGColor;
//define dictionary keys to be used for adding borders in order of zOrder
NSString *borderDK = @"border";
NSString *zOrderDK = @"zOrder";
//storing borders in dictionaries in preparation to add them in order of zOrder
NSDictionary *leftBorderDictionary = [NSDictionary dictionaryWithObjectsAndKeys:leftBorder, borderDK, [NSNumber numberWithInt:zOrderLeft], zOrderDK, nil];
NSDictionary *rightBorderDictionary = [NSDictionary dictionaryWithObjectsAndKeys:rightBorder, borderDK, [NSNumber numberWithInt:zOrderRight], zOrderDK, nil];
NSDictionary *topBorderDictionary = [NSDictionary dictionaryWithObjectsAndKeys:topBorder, borderDK, [NSNumber numberWithInt:zOrderTop], zOrderDK, nil];
NSDictionary *bottomBorderDictionary = [NSDictionary dictionaryWithObjectsAndKeys:bottomBorder, borderDK, [NSNumber numberWithInt:zOrderBottom], zOrderDK, nil];
NSMutableArray *borders = [NSMutableArray arrayWithObjects:leftBorderDictionary, rightBorderDictionary, topBorderDictionary, bottomBorderDictionary, nil];
//add borders in order of zOrder (lowest -> highest). Thus the highest zOrder will be added last so it will be on top.
while (borders.count)
{
//look for the next lowest zOrder border to add
NSDictionary *nextBorderToLayDown = [borders objectAtIndex:0];
for (int indexOfBorder = 0; indexOfBorder < borders.count; indexOfBorder++)
{
NSDictionary *borderAtIndex = [borders objectAtIndex:indexOfBorder];
if ([[borderAtIndex objectForKey:zOrderDK] intValue] < [[nextBorderToLayDown objectForKey:zOrderDK] intValue])
{
nextBorderToLayDown = borderAtIndex;
}
}
//add the border to the view
[view.layer addSublayer:[nextBorderToLayDown objectForKey:borderDK]];
[borders removeObject:nextBorderToLayDown];
}
}
I know this is an old question, but I thought I'd present one more solution that could be used if you'd like to avoid using named function expressions. (Not saying you should or should not avoid them, just presenting another solution)
var fn = (function() {
var innerFn = function(counter) {
console.log(counter);
if(counter > 0) {
innerFn(counter-1);
}
};
return innerFn;
})();
console.log("running fn");
fn(3);
var copyFn = fn;
console.log("running copyFn");
copyFn(3);
fn = function() { console.log("done"); };
console.log("fn after reassignment");
fn(3);
console.log("copyFn after reassignment of fn");
copyFn(3);
I tried ssh -X
but it was unbearably slow.
I also tried RSE, but it didn't even support building the project with a Makefile (I'm being told that this has changed since I posted my answer, but I haven't tried that out)
I read that NX is faster than X11 forwarding, but I couldn't get it to work.
Finally, I found out that my server supports X2Go (the link has install instructions if yours does not). Now I only had to:
sudo apt-get install x2goclient
on Ubuntu),Everything is just as if I was working on a local machine, including building, debugging, and code indexing. And there are no noticeable lags.
Set force Portrait or Landscape mode, Add lines respectively.
Import below line:
import android.content.pm.ActivityInfo;
Add Below line just above setContentView(R.layout.activity_main);
For Portrait:
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);//Set Portrait
For Landscap:
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);//Set Landscape
This will definitely work.
It would be helpful if you provided more information - e.g. what OS your using, what you want to accomplish, etc. But, generally speaking cURL is a very powerful command-line tool I frequently use (in linux) for imitating HTML requests:
For example:
curl --data "post1=value1&post2=value2&etc=valetc" http://host/resource
OR, for a RESTful API:
curl -X POST -d @file http://host/resource
You can check out more information here-> http://curl.haxx.se/
EDITs:
OK. So basically you're looking to stress test your REST server? Then cURL really isn't helpful unless you want to write your own load-testing program, even then sockets would be the way to go. I would suggest you check out Gatling. The Gatling documentation explains how to set up the tool, and from there your can run all kinds of GET, POST, PUT and DELETE requests.
Unfortunately, short of writing your own program - i.e. spawning a whole bunch of threads and inundating your REST server with different types of requests - you really have to rely on a stress/load-testing toolkit. Just using a REST client to send requests isn't going to put much stress on your server.
More EDITs
So in order to simulate a post request on a socket, you basically have to build the initial socket connection with the server. I am not a C# guy, so I can't tell you exactly how to do that; I'm sure there are 1001 C# socket tutorials on the web. With most RESTful APIs you usually need to provide a URI to tell the server what to do. For example, let's say your API manages a library, and you are using a POST request to tell the server to update information about a book with an id of '34'. Your URI might be
http://localhost/library/book/34
Therefore, you should open a connection to localhost on port 80 (or 8080, or whatever port your server is on), and pass along an HTML request header. Going with the library example above, your request header might look as follows:
POST library/book/34 HTTP/1.0\r\n
X-Requested-With: XMLHttpRequest\r\n
Content-Type: text/html\r\n
Referer: localhost\r\n
Content-length: 36\r\n\r\n
title=Learning+REST&author=Some+Name
From here, the server should shoot back a response header, followed by whatever the API is programed to tell the client - usually something to say the POST succeeded or failed. To stress test your API, you should essentially do this over and over again by creating a threaded process.
Also, if you are posting JSON data, you will have to alter your header and content accordingly. Frankly, if you are looking to do this quick and clean, I would suggest using python (or perl) which has several libraries for creating POST, PUT, GET and DELETE request, as well as POSTing and PUTing JSON data. Otherwise, you might end up doing more programming than stress testing. Hope this helps!
How about the JDK source code, but accessed through a 3rd party like docjar? For example, the Collections source.
That way, there's no big download.
My solution:
Option Explicit
Public datHora As Date
Function Cronometro(action As Integer) As Integer
'This return the seconds between two >calls
Cronometro = 0
If action = 1 Then 'Start
datHora = Now
End If
If action = 2 Then 'Time until that moment
Cronometro = DateDiff("s", datHora, Now)
End If
End Function
How to use? Easy...
dummy= Cronometro(1) ' This starts the timer
seconds= Cronometro(2) ' This returns the seconds between the first call and this one
Try this
function test()
{
$("body").append("<input type='button' id='field' />");
}
Here is another way, without the need for nesting the repeaters.
From the Angularjs docs:
It is possible to get ngRepeat to iterate over the properties of an object using the following syntax:
<div ng-repeat="(key, value) in steps"> {{key}} : {{value}} </div>
To fix this problem, I had to discover that I misspelled the name of the controller in the declaration of Angular routes:
.when('/todo',{
templateUrl: 'partials/todo.html',
controller: 'TodoCtrl'
})
Try with:
@Scheduled(cron = "0 1 1 * * ?")
Below you can find the example patterns from the spring forum:
* "0 0 * * * *" = the top of every hour of every day.
* "*/10 * * * * *" = every ten seconds.
* "0 0 8-10 * * *" = 8, 9 and 10 o'clock of every day.
* "0 0 8,10 * * *" = 8 and 10 o'clock of every day.
* "0 0/30 8-10 * * *" = 8:00, 8:30, 9:00, 9:30 and 10 o'clock every day.
* "0 0 9-17 * * MON-FRI" = on the hour nine-to-five weekdays
* "0 0 0 25 12 ?" = every Christmas Day at midnight
Cron expression is represented by six fields:
second, minute, hour, day of month, month, day(s) of week
(*)
means match any
*/X
means "every X"
?
("no specific value") - useful when you need to specify something in one of the two fields in which the character is allowed, but not the other. For example, if I want my trigger to fire on a particular day of the month (say, the 10th), but I don't care what day of the week that happens to be, I would put "10" in the day-of-month field and "?" in the day-of-week field.
PS: In order to make it work, remember to enable it in your application context: https://docs.spring.io/spring/docs/3.2.x/spring-framework-reference/html/scheduling.html#scheduling-annotation-support
Code below (taken from my blog article - http://todayguesswhat.blogspot.com/2021/01/manually-verifying-rsa-sha-signature-in.html ) is hopefully helpful in understanding what is present in a standard SHA with RSA signature. This should work in standard Oracle JDK and does not require Bouncy Castle libraries. It is using the sun.security classes to process the decrypted signature contents - you could just as easily manually parse.
In the example below, the message digest algorithm is SHA-512 which produces a 64 byte (512-bit) checksum.
SHA-1 would be pretty similar - but producing a 20-byte (160-bit) checksum.
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.MessageDigest;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.Signature;
import java.util.Arrays;
import javax.crypto.Cipher;
import sun.security.util.DerInputStream;
import sun.security.util.DerValue;
public class RSASignatureVerification
{
public static void main(String[] args) throws Exception
{
KeyPairGenerator generator = KeyPairGenerator.getInstance("RSA");
generator.initialize(2048);
KeyPair keyPair = generator.generateKeyPair();
PrivateKey privateKey = keyPair.getPrivate();
PublicKey publicKey = keyPair.getPublic();
String data = "hello oracle";
byte[] dataBytes = data.getBytes("UTF8");
Signature signer = Signature.getInstance("SHA512withRSA");
signer.initSign(privateKey);
signer.update(dataBytes);
byte[] signature = signer.sign(); // signature bytes of the signing operation's result.
Signature verifier = Signature.getInstance("SHA512withRSA");
verifier.initVerify(publicKey);
verifier.update(dataBytes);
boolean verified = verifier.verify(signature);
if (verified)
{
System.out.println("Signature verified!");
}
/*
The statement that describes signing to be equivalent to RSA encrypting the
hash of the message using the private key is a greatly simplified view
The decrypted signatures bytes likely convey a structure (ASN.1) encoded
using DER with the hash just one component of the structure.
*/
// lets try decrypt signature and see what is in it ...
Cipher cipher = Cipher.getInstance("RSA");
cipher.init(Cipher.DECRYPT_MODE, publicKey);
byte[] decryptedSignatureBytes = cipher.doFinal(signature);
/*
sample value of decrypted signature which was 83 bytes long
30 51 30 0D 06 09 60 86 48 01 65 03 04 02 03 05
00 04 40 51 00 41 75 CA 3B 2B 6B C0 0A 3F 99 E3
6B 7A 01 DC F2 9B 36 E6 0D D4 31 89 53 A3 D9 80
6D AE DD 45 7E 55 45 01 FC C8 73 D2 DD 8D E5 B9
E0 71 57 13 41 D0 CD FF CA 58 01 03 A3 DD 95 A1
C1 EE C8
Taking above sample bytes ...
0x30 means A SEQUENCE - which contains an ordered field of one or more types.
It is encoded into a TLV triplet that begins with a Tag byte of 0x30.
DER uses T,L,V (tag bytes, length bytes, value bytes) format
0x51 is the length = 81 decimal (13 bytes)
the 0x30 (48 decimal) that follows begins a second sequence
https://tools.ietf.org/html/rfc3447#page-43
the DER encoding T of the DigestInfo value is equal to the following for SHA-512
0D 06 09 60 86 48 01 65 03 04 02 03 05 00 04 40 || H
where || is concatenation and H is the hash value.
0x0D is the length = 13 decimal (13 bytes)
0x06 means an OBJECT_ID tag
0x09 means the object id is 9 bytes ...
https://docs.microsoft.com/en-au/windows/win32/seccertenroll/about-object-identifier?redirectedfrom=MSDN
taking 2.16.840.1.101.3.4.2.3 (object id for SHA512 Hash Algorithm)
The first two nodes of the OID are encoded onto a single byte.
The first node is multiplied by the decimal 40 and the result is added to the value of the second node
2 * 40 + 16 = 96 decimal = 60 hex
Node values less than or equal to 127 are encoded on one byte.
1 101 3 4 2 3 corresponds to in hex 01 65 03 04 02 03
Node values greater than or equal to 128 are encoded on multiple bytes.
Bit 7 of the leftmost byte is set to one. Bits 0 through 6 of each byte contains the encoded value.
840 decimal = 348 hex
-> 0000 0011 0100 1000
set bit 7 of the left most byte to 1, ignore bit 7 of the right most byte,
shifting right nibble of leftmost byte to the left by 1 bit
-> 1000 0110 X100 1000 in hex 86 48
05 00 ; NULL (0 Bytes)
04 40 ; OCTET STRING (0x40 Bytes = 64 bytes
SHA512 produces a 512-bit (64-byte) hash value
51 00 41 ... C1 EE C8 is the 64 byte hash value
*/
// parse DER encoded data
DerInputStream derReader = new DerInputStream(decryptedSignatureBytes);
byte[] hashValueFromSignature = null;
// obtain sequence of entities
DerValue[] seq = derReader.getSequence(0);
for (DerValue v : seq)
{
if (v.getTag() == 4)
{
hashValueFromSignature = v.getOctetString(); // SHA-512 checksum extracted from decrypted signature bytes
}
}
MessageDigest md = MessageDigest.getInstance("SHA-512");
md.update(dataBytes);
byte[] hashValueCalculated = md.digest();
boolean manuallyVerified = Arrays.equals(hashValueFromSignature, hashValueCalculated);
if (manuallyVerified)
{
System.out.println("Signature manually verified!");
}
else
{
System.out.println("Signature could NOT be manually verified!");
}
}
}
jQuery.post(post_url,{ content: "John" } )_x000D_
.done(function( data ) {_x000D_
_x000D_
_x000D_
});_x000D_
_x000D_
I used the technique what u have replied above, it works fine but my problem is i need to generate a pdf conent using john as text . I have been able to echo the passed data. but getting empty in when generating pdf uisng below content ples check
ob_start();_x000D_
_x000D_
include_once(JPATH_SITE .'/components/com_gaevents/pdfgenerator.php');_x000D_
$content = ob_get_clean();_x000D_
_x000D_
_x000D_
_x000D_
$test = $_SESSION['content'] ;_x000D_
_x000D_
require_once(JPATH_SITE.'/html2pdf/html2pdf.class.php');_x000D_
$html2pdf = new HTML2PDF('P', 'A4', 'en', true, 'UTF-8',0 ); _x000D_
$html2pdf->setDefaultFont('Arial');_x000D_
$html2pdf->WriteHTML($test);
_x000D_
All I had to do was to run this command:
git config --global credential.helper wincred
Then I was prompted for password twice.
Next time it worked without prompting me for password.
The big thing to get your head around is that the File
class tries to represent a view of what Sun like to call "hierarchical pathnames" (basically a path like c:/foo.txt
or /usr/muggins
). This is why you create files in terms of paths. The operations you are describing are all operations upon this "pathname".
getPath()
fetches the path that the File was created with (../foo.txt
)getAbsolutePath()
fetches the path that the File was created with, but includes information about the current directory if the path is relative (/usr/bobstuff/../foo.txt
)getCanonicalPath()
attempts to fetch a unique representation of the absolute path to the file. This eliminates indirection from ".." and "." references (/usr/foo.txt
).Note I say attempts - in forming a Canonical Path, the VM can throw an IOException
. This usually occurs because it is performing some filesystem operations, any one of which could fail.
alter table your_table
alter column LoginDate datetime;
If you're doing it in VBA (and not in a query) then: where field like "AA" and field not like "BB" then would not work.
You'd have to use: where field like "AA" and field like "BB" = false then
Scenario:
Your domain: mydomain.com
Domain you wish to send to: theirdomain.com
1. Determine the mail server you're sending to. Open a CMD prompt Type
NSLOOKUP
set q=mx
theirdomain.com
Response:
Non-authoritative answer:
theirdomain.com MX preference = 50, mail exchanger = mail.theirdomain.com
Nslookup_big
EDIT Be sure to type exit to terminate NSLOOKUP.
2. Connect to their mail server
SMTP communicates over port 25. We will now try to use TELNET to connect to their mail server "mail.theirdomain.com"
Open a CMD prompt
TELNET MAIL.THEIRDOMAIN.COM 25
You should see something like this as a response:
220 mx.google.com ESMTP 6si6253627yxg.6
Be aware that different servers will come up with different greetings but you should get SOMETHING. If nothing comes up at this point there are 2 possible problems. Port 25 is being blocked at your firewall, or their server is not responding. Try a different domain, if that works then it's not you.
3. Send an Email
Now, use simple SMTP commands to send a test email. This is very important, you CANNOT use the backspace key, it will work onscreen but not be interpreted correctly. You have to type these commands perfectly.
ehlo mydomain.com
mail from:<[email protected]>
rcpt to:<[email protected]>
data
This is a test, please do not respond
.
quit
So, what does that all mean? EHLO - introduce yourself to the mail server HELO can also be used but EHLO tells the server to use the extended command set (not that we're using that).
MAIL FROM - who's sending the email. Make sure to place this is the greater than/less than brackets as many email servers will require this (Postini).
RCPT TO - who you're sending it to. Again you need to use the brackets. See Step #4 on how to test relaying mail!
DATA - tells the SMTP server that what follows is the body of your email. Make sure to hit "Enter" at the end.
. - the period alone on the line tells the SMTP server you're all done with the data portion and it's clear to send the email.
quit - exits the TELNET session.
4. Test SMTP relay Testing SMTP relay is very easy, and simply requires a small change to the above commands. See below:
ehlo mydomain.com
mail from:<[email protected]>
rcpt to:<[email protected]>
data
This is a test, please do not respond
.
quit
See the difference? On the RCPT TO line, we're sending to a domain that is not controlled by the SMTP server we're sending to. You will get an immediate error is SMTP relay is turned off. If you're able to continue and send an email, then relay is allowed by that server.
Another way to get the user name (and most of the information) is to access the database directly and read the info from the tables.
The solution is already answered here above (long ago).
But the implicit question "why does it work in FF and IE but not in Chrome and Safari" is found in the error text "Not allowed to load local resource": Chrome and Safari seem to use a more strict implementation of sandboxing (for security reasons) than the other two (at this time 2011).
This applies for local access. In a (normal) server environment (apache ...) the file would simply not have been found.
Try Wrap
widget to wrap text as text grows:
Example:
Wrap(
direction: Axis.vertical, //Vertical || Horizontal
children: <Widget>[
Text(
'Your Text',
style: TextStyle(fontSize: 30),
),
Text(
'Your Text',
style: TextStyle(fontSize: 30),
),
],
),
Use the start command as follows.
start "C:\Program Files (x86)\Google\Chrome\Application\chrome.exe" http://www.google.com
It will be better to close chrome instances before you open a new one. You can do that as follows:
taskkill /IM chrome.exe
start "C:\Program Files (x86)\Google\Chrome\Application\chrome.exe" http://www.google.com
That'll work for you.
In a function:
a += 1
will be interpreted by the compiler as assign to a => Create local variable a
, which is not what you want. It will probably fail with a a not initialized
error since the (local) a has indeed not been initialized:
>>> a = 1
>>> def f():
... a += 1
...
>>> f()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 2, in f
UnboundLocalError: local variable 'a' referenced before assignment
You might get what you want with the (very frowned upon, and for good reasons) global
keyword, like so:
>>> def f():
... global a
... a += 1
...
>>> a
1
>>> f()
>>> a
2
In general however, you should avoid using global variables which become extremely quickly out of hand. And this is especially true for multithreaded programs, where you don't have any synchronization mechanism for your thread1
to know when a
has been modified. In short: threads are complicated, and you cannot expect to have an intuitive understanding of the order in which events are happening when two (or more) threads work on the same value. The language, compiler, OS, processor... can ALL play a role, and decide to modify the order of operations for speed, practicality or any other reason.
The proper way for this kind of thing is to use Python sharing tools (locks and friends), or better, communicate data via a Queue instead of sharing it, e.g. like this:
from threading import Thread
from queue import Queue
import time
def thread1(threadname, q):
#read variable "a" modify by thread 2
while True:
a = q.get()
if a is None: return # Poison pill
print a
def thread2(threadname, q):
a = 0
for _ in xrange(10):
a += 1
q.put(a)
time.sleep(1)
q.put(None) # Poison pill
queue = Queue()
thread1 = Thread( target=thread1, args=("Thread-1", queue) )
thread2 = Thread( target=thread2, args=("Thread-2", queue) )
thread1.start()
thread2.start()
thread1.join()
thread2.join()
With SSL/https and with CSRF_COOKIE_HTTPONLY = False, I still don't have csrftoken in the cookie, either using the getCookie(name) function proposed in django Doc or the jquery.cookie.js proposed by fivef.
Wtower summary is perfect and I thought it would work after removing CSRF_COOKIE_HTTPONLY from settings.py but it does'nt in https!
Why csrftoken is not visible in document.cookie???
Instead of getting
"django_language=fr; csrftoken=rDrGI5cp98MnooPIsygWIF76vuYTkDIt"
I get only
"django_language=fr"
WHY? Like SSL/https removes X-CSRFToken from headers I thought it was due to the proxy header params of Nginx but apparently not... Any idea?
Unlike django doc Notes, it seems impossible to work with csrf_token in cookies with https. The only way to pass csrftoken is through the DOM by using {% csrf_token %} in html and get it in jQuery by using
var csrftoken = $('input[name="csrfmiddlewaretoken"]').val();
It is then possible to pass it to ajax either by header (xhr.setRequestHeader), either by params.
Consider using a package to automatically generate inline styles from your css files. A good one is Grunt Critical or Critical css for Laravel.
Python lets you put the indented clause on the same line if it's only one line:
if "exam" in example: print "yes!"
def squared(x): return x * x
class MyException(Exception): pass
item = objects.Find(obj => obj.property==myValue);
I did it like this for my project:
.btn-outlined.btn-primary {_x000D_
color: #000;_x000D_
}_x000D_
.btn-outlined.btn-primary:active, .btn-outlined.btn-positive:active, .btn-outlined.btn-negative:active {_x000D_
color:#000;_x000D_
}_x000D_
.btn-block {_x000D_
display: block;_x000D_
width: 100%;_x000D_
padding: 15px 0;_x000D_
margin-bottom: 10px;_x000D_
font-size: 18px;_x000D_
font-family: Arial, Helvetica, sans-serif;_x000D_
text-align: center;_x000D_
}
_x000D_
<label for="fileUpload" class="btn btn-primary btn-block btn-outlined">Your text</label>_x000D_
<input type="file" id="fileUpload"style="display: none;">
_x000D_
The "Premature end of script headers" error message is probably the most loathed and common error message you'll find. What the error actually means, is that the script stopped for whatever reason before it returned any output to the web server. A common cause of this for script writers is to fail to set a content type before printing output code. In Perl for example, before printing any HTML it is necessary to tell the Perl script to set the content type to text/html, this is done by sending a header, like so:
print "Content-type: text/html\n\n";
Other answers are great, I just want to add... a different approach usable in PowerShell: Install GNUWin32 utils and use grep to view the lines / redirect the output to file http://gnuwin32.sourceforge.net/
This overwrites the new file every time:
grep "step[49]" logIn.log > logOut.log
This appends the log output, in case you overwrite the logIn file and want to keep the data:
grep "step[49]" logIn.log >> logOut.log
Note: to be able to use GNUWin32 utils globally you have to add the bin folder to your system path.
You want strtol
or strtoul
. See also the Unix man page
def recursive_copy_files(source_path, destination_path, override=False):
"""
Recursive copies files from source to destination directory.
:param source_path: source directory
:param destination_path: destination directory
:param override if True all files will be overridden otherwise skip if file exist
:return: count of copied files
"""
files_count = 0
if not os.path.exists(destination_path):
os.mkdir(destination_path)
items = glob.glob(source_path + '/*')
for item in items:
if os.path.isdir(item):
path = os.path.join(destination_path, item.split('/')[-1])
files_count += recursive_copy_files(source_path=item, destination_path=path, override=override)
else:
file = os.path.join(destination_path, item.split('/')[-1])
if not os.path.exists(file) or override:
shutil.copyfile(item, file)
files_count += 1
return files_count
My Problem was that I was not in the correct git directory that I just cloned.
When you execute the Java Virtual Machine (JVM) with the java
command,
java ClassName argument1 argument2 ...
When you execute your application, you specify its class name as an argument to the java command, as above
the JVM attempts to invoke the main method of the class you specify
—at this point, no objects of the class have been created.
Declaring
main
as staticallows
the JVM toinvoke
mainwithout
creating aninstance
of the class.
let's back to the command
ClassName
is a command-line argument
to the JVM that tells it which class to execute. Following the ClassName, you can also specify a list of Strings
(separated by spaces) as command-line arguments that the JVM will pass to your application. -Such arguments might be used to specify options (e.g., a filename) to run the application- this is why there is a parameter called String[] args
in the main
References:Java™ How To Program (Early Objects), Tenth Edition
The golden rule is to NOT under ANY circumstances lock your users browser. After that, I usually look at execution time, followed by memory usage (unless you're doing something crazy, in which case it could be a higher priority).
if (intent.resolveActivity(getPackageManager()) == null) {
Utils.showToast(activity, no_app_available_to_complete_this_task);
} else {
startActivityForResult(intent, 1);
}
class MyActivity{
private final Handler handler = new Handler();
private Runnable yourRunnable;
protected void onCreate(@Nullable Bundle savedInstanceState) {
// ....
this.yourRunnable = new Runnable() {
@Override
public void run() {
//code
}
};
this.handler.postDelayed(this.yourRunnable, 2000);
}
@Override
protected void onDestroy() {
// to avoid memory leaks
this.handler.removeCallbacks(this.yourRunnable);
}
}
And to be double sure you can be combined it with the "static class" method as described in the tronman answer
Another hints for Unexpected token
errors.
There are two major differences between javascript objects and json:
Correct JSON
{
"english": "bag",
"kana": "kaban",
"kanji": "K"
}
Error JSON 1
{
'english': 'bag',
'kana': 'kaban',
'kanji': 'K'
}
Error JSON 2
{
english: "bag",
kana: "kaban",
kanji: "K"
}
Remark
This is not a direct answer for that question. But it's an answer for Unexpected token
errors. So it may be help others who stumple upon that question.
For any method in a Spring CrudRepository you should be able to specify the @Query yourself. Something like this should work:
@Query( "select o from MyObject o where inventoryId in :ids" )
List<MyObject> findByInventoryIds(@Param("ids") List<Long> inventoryIdList);
Can't get much simpler than this :)
ssh host "test -e /path/to/file"
if [ $? -eq 0 ]; then
# your file exists
fi
As suggested by dimo414, this can be collapsed to:
if ssh host "test -e /path/to/file"; then
# your file exists
fi
if (chapeau) {
You forgot the ending brace to this if
statement, so the subsequent else if
is considered a syntax error. You need to add the brace when the if
statement body is complete:
if (chapeau) {
cout << "le Professeur Violet";
}
else if (moustaches) {
cout << "le Colonel Moutarde";
}
// ...
Just had a similar issue
Resolved it by checking in httpd.conf
# AllowOverride controls what directives may be placed in .htaccess files.
# It can be "All", "None", or any combination of the keywords:
# Options FileInfo AuthConfig Limit
#
AllowOverride All <--- make sure this is not set to "None"
It is worth bearing in mind I tried (from Mark's answer) the "put garbage in the .htaccess" which did give a server error - but even though it was being read, it wasn't being acted on due to no overrides allowed.
I struggled with the same problem just a minute ago. My project was generated using the v 1.6.0 of angular-cli.
1. npm update -g @angular/cli
2. editing my package.json changing the line
"@angular/cli": "1.6.0",
to
"@angular/cli": "^1.6.0",
3. npm update
I hope my help is effective ?
Try this for the file format:
[default]
aws_access_key_id=<your access key>
aws_secret_access_key=<your secret access key>
I saved this file as ~/.aws/credentials with ProfileCredentialsProvider().
For python2 and python3 compatibility, you can use:
# Python 2 and 3
from imp import reload
reload(mymodule)
man ssh
gives me this options would could be useful.
-i identity_file Selects a file from which the identity (private key) for RSA or DSA authentication is read. The default is ~/.ssh/identity for protocol version 1, and ~/.ssh/id_rsa and ~/.ssh/id_dsa for pro- tocol version 2. Identity files may also be specified on a per- host basis in the configuration file. It is possible to have multiple -i options (and multiple identities specified in config- uration files).
So you could create an alias in your bash config with something like
alias ssh="ssh -i /path/to/private_key"
I haven't looked into a ssh configuration file, but like the -i
option this too could be aliased
-F configfile Specifies an alternative per-user configuration file. If a configuration file is given on the command line, the system-wide configuration file (/etc/ssh/ssh_config) will be ignored. The default for the per-user configuration file is ~/.ssh/config.
As of Rails 5, the rake
commandline tool has been aliased as rails
so now
rails db:reset
instead of rake db:reset
will work just as well
How about
CAST(2229.999 AS DECIMAL(6,2))
to get a decimal with 2 decimal places
Centering is one of the biggest issues in CSS. However, some tricks exist:
To center your table horizontally, you can set left and right margin to auto:
<style>
#test {
width:100%;
height:100%;
}
table {
margin: 0 auto; /* or margin: 0 auto 0 auto */
}
</style>
To center it vertically, the only way is to use javascript:
var tableMarginTop = Math.round( (testHeight - tableHeight) / 2 );
$('table').css('margin-top', tableMarginTop) # with jQuery
$$('table')[0].setStyle('margin-top', tableMarginTop) # with Mootools
No vertical-align:middle
is possible as a table is a block and not an inline element.
Here is a website that sums up CSS centering solutions: http://howtocenterincss.com/
You could store the data in an array of strings of some large fixed size. It should be efficient to access any particular character in that array of strings, and to treat that character as a byte.
It would be interesting to see the operations you want to support, perhaps expressed as an interface, to make the question more concrete.
The best non-sgi, non-boost STL solution is to extend map::iterator like so:
template<class map_type>
class key_iterator : public map_type::iterator
{
public:
typedef typename map_type::iterator map_iterator;
typedef typename map_iterator::value_type::first_type key_type;
key_iterator(const map_iterator& other) : map_type::iterator(other) {} ;
key_type& operator *()
{
return map_type::iterator::operator*().first;
}
};
// helpers to create iterators easier:
template<class map_type>
key_iterator<map_type> key_begin(map_type& m)
{
return key_iterator<map_type>(m.begin());
}
template<class map_type>
key_iterator<map_type> key_end(map_type& m)
{
return key_iterator<map_type>(m.end());
}
and then use them like so:
map<string,int> test;
test["one"] = 1;
test["two"] = 2;
vector<string> keys;
// // method one
// key_iterator<map<string,int> > kb(test.begin());
// key_iterator<map<string,int> > ke(test.end());
// keys.insert(keys.begin(), kb, ke);
// // method two
// keys.insert(keys.begin(),
// key_iterator<map<string,int> >(test.begin()),
// key_iterator<map<string,int> >(test.end()));
// method three (with helpers)
keys.insert(keys.begin(), key_begin(test), key_end(test));
string one = keys[0];
Imagine being an OS working with a string that some other thread was modifying behind your back. How could you validate anything without making a copy?
This works:
async function IsLoggedIn(): Promise<boolean> {
try {
await new Promise((resolve, reject) =>
app.auth().onAuthStateChanged(
user => {
if (user) {
// User is signed in.
resolve(user)
} else {
// No user is signed in.
reject('no user logged in')
}
},
// Prevent console error
error => reject(error)
)
)
return true
} catch (error) {
return false
}
}
In your "hostname".err file inside the data folder MySQL works on, try to look for a string that starts with:
"A temporary password is generated for roor@localhost "
you can use
less /mysql/data/dir/hostname.err
then slash command followed by the string you wish to look for
/"A temporary password"
Then press n, to go to the Next result.
You might want to try int.TryParse(string, out int)
in the KeyPress(object, KeyPressEventArgs)
event to check for numeric values. For the other problem you could use regular expressions instead.
I can stop at the first requirement "A daemon which cannot be stopped ..."
Not possible my friend; however, you can achieve the same with a much better tool, a kernel module.
http://www.infoq.com/articles/inotify-linux-file-system-event-monitoring
All daemons can be stopped. Some are more easily stopped than others. Even a daemon pair with the partner in hold down, respawning the partner if lost, can be stopped. You just have to work a little harder at it.
As of PHP 5.3, you can use openssl_random_pseudo_bytes():
$hex_string = bin2hex(openssl_random_pseudo_bytes(3));
I am just providing another case where you can get this error message. The solution will be the same as Adam has mentioned above. This is from a real code and I renamed the class name.
class FooReader {
public:
/** Constructor */
FooReader() : d(new FooReaderPrivate(this)) { } // will not compile here
.......
private:
FooReaderPrivate* d;
};
====== In a separate file =====
class FooReaderPrivate {
public:
FooReaderPrivate(FooReader*) : parent(p) { }
private:
FooReader* parent;
};
The above will no pass the compiler and get error: invalid use of incomplete type FooReaderPrivate. You basically have to put the inline portion into the *.cpp implementation file. This is OK. What I am trying to say here is that you may have a design issue. Cross reference of two classes may be necessary some cases, but I would say it is better to avoid them at the start of the design. I would be wrong, but please comment then I will update my posting.
It's due to the fact that you have one long word without spaces. You can use the word-wrap
property to cause the text to break:
#w74 { word-wrap: break-word; }
It has fairly good browser support, too. See documentation about it here.
@amir response in Swift :
// Get language prefered by user
let langageRegion = NSLocale.preferredLanguages().first!
let languageDic = NSLocale.componentsFromLocaleIdentifier(langageRegion)
let language = languageDic[NSLocaleLanguageCode]
In case you don't want to use the M2_HOME and want to direct the IntelliJ to the maven installation you can simply set it by:
A better way is to have a symlink e.g. 'latest' for the latest version and point your IntelliJ to use that for consistency, given latest points to the latest version of maven installed on your box.
If you want to get hour 0 of some date in the local time zone, pass the individual date parts to the Date
constructor.
new Date(2011,08,24); // month value is 0 based, others are 1 based.
Beginning of line or beginning of string?
/^CTR.*$/
/
= delimiter
^
= start of string
CTR
= literal CTR
$
= end of string
.*
= zero or more of any character except newline
/^CTR.*$/m
/
= delimiter
^
= start of line
CTR
= literal CTR
$
= end of line
.*
= zero or more of any character except newline
m
= enables multi-line mode, this sets regex to treat every line as a string, so ^
and $
will match start and end of line
While in multi-line mode you can still match the start and end of the string with \A\Z
permanent anchors
/\ACTR.*\Z/m
\A
= means start of string
CTR
= literal CTR
.*
= zero or more of any character except newline
\Z
= end of string
m
= enables multi-line mode
As such, another way to match the start of the line would be like this:
/(\A|\r|\n|\r\n)CTR.*/
or
/(^|\r|\n|\r\n)CTR.*/
\r
= carriage return / old Mac OS newline
\n
= line-feed / Unix/Mac OS X newline
\r\n
= windows newline
Note, if you are going to use the backslash \
in some program string that supports escaping, like the php double quotation marks ""
then you need to escape them first
so to run \r\nCTR.*
you would use it as "\\r\\nCTR.*"
In the answer from @mariubog (https://stackoverflow.com/a/27882337/1279002) I was using password grant types too as in the example but needed to set the client authentication scheme to form. Scopes were not supported by the endpoint for password and there was no need to set the grant type as the ResourceOwnerPasswordResourceDetails object sets this itself in the constructor.
...
public ResourceOwnerPasswordResourceDetails() {
setGrantType("password");
}
...
The key thing for me was the client_id and client_secret were not being added to the form object to post in the body if resource.setClientAuthenticationScheme(AuthenticationScheme.form);
was not set.
See the switch in:
org.springframework.security.oauth2.client.token.auth.DefaultClientAuthenticationHandler.authenticateTokenRequest()
Finally, when connecting to Salesforce endpoint the password token needed to be appended to the password.
@EnableOAuth2Client
@Configuration
class MyConfig {
@Value("${security.oauth2.client.access-token-uri}")
private String tokenUrl;
@Value("${security.oauth2.client.client-id}")
private String clientId;
@Value("${security.oauth2.client.client-secret}")
private String clientSecret;
@Value("${security.oauth2.client.password-token}")
private String passwordToken;
@Value("${security.user.name}")
private String username;
@Value("${security.user.password}")
private String password;
@Bean
protected OAuth2ProtectedResourceDetails resource() {
ResourceOwnerPasswordResourceDetails resource = new ResourceOwnerPasswordResourceDetails();
resource.setAccessTokenUri(tokenUrl);
resource.setClientId(clientId);
resource.setClientSecret(clientSecret);
resource.setClientAuthenticationScheme(AuthenticationScheme.form);
resource.setUsername(username);
resource.setPassword(password + passwordToken);
return resource;
}
@Bean
public OAuth2RestOperations restTemplate() {
return new OAuth2RestTemplate(resource(), new DefaultOAuth2ClientContext(new DefaultAccessTokenRequest()));
}
}
@Service
@SuppressWarnings("unchecked")
class MyService {
@Autowired
private OAuth2RestOperations restTemplate;
public MyService() {
restTemplate.getAccessToken();
}
}
There's a description of how to do this at Resize a column in a PostgreSQL table without changing data. You have to hack the database catalog data. The only way to do this officially is with ALTER TABLE, and as you've noted that change will lock and rewrite the entire table while it's running.
Make sure you read the Character Types section of the docs before changing this. All sorts of weird cases to be aware of here. The length check is done when values are stored into the rows. If you hack a lower limit in there, that will not reduce the size of existing values at all. You would be wise to do a scan over the whole table looking for rows where the length of the field is >40 characters after making the change. You'll need to figure out how to truncate those manually--so you're back some locks just on oversize ones--because if someone tries to update anything on that row it's going to reject it as too big now, at the point it goes to store the new version of the row. Hilarity ensues for the user.
VARCHAR is a terrible type that exists in PostgreSQL only to comply with its associated terrible part of the SQL standard. If you don't care about multi-database compatibility, consider storing your data as TEXT and add a constraint to limits its length. Constraints you can change around without this table lock/rewrite problem, and they can do more integrity checking than just the weak length check.
Change alert(buttons[i].text);
to alert(i);
Just be aware of TempData persistence, it's a bit tricky. For example if you even simply read TempData inside the current request, it would be removed and consequently you don't have it for the next request. Instead, you can use Peek
method. I would recommend reading this cool article:
How do I run an executable JAR file? If you have a jar file called Example.jar, follow these rules:
Open a notepad.exe.
Write : java -jar Example.jar.
Save it with the extension .bat.
Copy it to the directory which has the .jar file.
Double click it to run your .jar file.
After some investigation I have come to the conclusion that the following approach seems the best.
some/subpackage/Util.groovy
@GrabResolver(name = 'nexus', root = 'https://local-nexus-server:8443/repository/maven-public', m2Compatible = true)
@Grab('com.google.errorprone:error_prone_annotations:2.1.3')
@Grab('com.google.guava:guava:23.0')
@GrabExclude('com.google.errorprone:error_prone_annotations')
import com.google.common.base.Strings
class Util {
void msg(int a, String b, Map c) {
println 'Message printed by msg method inside Util.groovy'
println "Print 5 asterisks using the Guava dependency ${Strings.repeat("*", 5)}"
println "Arguments are a=$a, b=$b, c=$c"
}
}
example.groovy
#!/usr/bin/env groovy
Class clazz = new GroovyClassLoader().parseClass("${new File(getClass().protectionDomain.codeSource.location.path).parent}/some/subpackage/Util.groovy" as File)
GroovyObject u = clazz.newInstance()
u.msg(1, 'b', [a: 'b', c: 'd'])
In order to run the example.groovy
script, add it to your system path and type from any directory:
example.groovy
The script prints:
Message printed by msg method inside Util.groovy
Print 5 asterisks using the Guava dependency *****
Arguments are a=1, b=b, c=[a:b, c:d]
The above example was tested in the following environment: Groovy Version: 2.4.13 JVM: 1.8.0_151 Vendor: Oracle Corporation OS: Linux
The example demonstrates the following:
Util
class inside a groovy script.Util
class calling the Guava
third party library by including it as a Grape
dependency (@Grab('com.google.guava:guava:23.0')
).Util
class can reside in a subdirectory.Util
class.Additional comments/suggestions:
new Util()
, but most importantly it would have to be placed in a file named anything but Util.groovy. Refer to Scripts versus classes for more details about the differences between groovy scripts and groovy classes."${new File(getClass().protectionDomain.codeSource.location.path).parent}/some/subpackage/Util.groovy"
instead of "some/subpackage/Util.groovy"
. This will guarantee that the Util.groovy
file will always be found in relation to the groovy script's location (example.groovy
) and not the current working directory. For example, using "some/subpackage/Util.groovy"
would result in searching at WORK_DIR/some/subpackage/Util.groovy
.myScript.groovy
is a script name, and MyClass.groovy
is a class name. Naming my-script.groovy
will result in runtime errors in certain scenarios because the resulting class will not have a valid Java class name.Encapsulation helps in adhering to Single Responsibility principle and Abstraction helps in adhering to Code to Interface and not to implement.
Say I have a class for Car : Service Provider Class and Driver Class : Service Consumer Class.
For Abstraction : we define abstract Class for CAR and define all the abstract methods in it , which are function available in the car like : changeGear(), applyBrake().
Now the actual Car (Concrete Class i.e. like Mercedes , BMW will implement these methods in their own way and abstract the execution and end user will still apply break and change gear for particular concrete car instance and polymorphically the execution will happen as defined in concrete class.
For Encapsulation : Now say Mercedes come up with new feature/technology: Anti Skid Braking, while implementing the applyBrake(), it will encapsulate this feature in applyBrake() method and thus providing cohesion, and service consumer will still access by same method applyBrake() of the car object. Thus Encapsulation lets further in same concrete class implementation.
What do you mean timestamp? If you mean milliseconds since the Unix epoch:
GregorianCalendar cal = new GregorianCalendar(2007, 9 - 1, 23);
long millis = cal.getTimeInMillis();
If you want an actual java.sql.Timestamp object:
Timestamp ts = new Timestamp(millis);
Check Following : 1) Package names 2) Import Statements (import every required packages) 3) Proper set of braces ,i.e { } 4) Check Syntax too.. i.e semicolons,commas,etc.
If you want to keep the innerHTML of the element and only strip the outermost tag, you can do this:
$(".contentToStrip").each(function(){
$(this).replaceWith($(this).html());
});
info frame
to show the stack frame info
To read the memory at given addresses you should take a look at x
x/x $esp
for hex x/d $esp
for signed x/u $esp
for unsigned etc. x uses the format syntax, you could also take a look at the current instruction via x/i $eip
etc.
I would like to expand on the ===
operator.
===
is not an equality operator!
Not.
Let's get that point really across.
You might be familiar with ===
as an equality operator in Javascript and PHP, but this just not an equality operator in Ruby and has fundamentally different semantics.
So what does ===
do?
===
is the pattern matching operator!
===
matches regular expressions===
checks range membership===
checks being instance of a class ===
calls lambda expressions===
sometimes checks equality, but mostly it does notSo how does this madness make sense?
Enumerable#grep
uses ===
internallycase when
statements use ===
internallyrescue
uses ===
internallyThat is why you can use regular expressions and classes and ranges and even lambda expressions in a case when
statement.
Some examples
case value
when /regexp/
# value matches this regexp
when 4..10
# value is in range
when MyClass
# value is an instance of class
when ->(value) { ... }
# lambda expression returns true
when a, b, c, d
# value matches one of a through d with `===`
when *array
# value matches an element in array with `===`
when x
# values is equal to x unless x is one of the above
end
All these example work with pattern === value
too, as well as with grep
method.
arr = ['the', 'quick', 'brown', 'fox', 1, 1, 2, 3, 5, 8, 13]
arr.grep(/[qx]/)
# => ["quick", "fox"]
arr.grep(4..10)
# => [5, 8]
arr.grep(String)
# => ["the", "quick", "brown", "fox"]
arr.grep(1)
# => [1, 1]
date()
itself is only for formatting, but it accepts a second parameter.
date("F j, Y", time() - 60 * 60 * 24);
To keep it simple I just subtract 24 hours from the unix timestamp.
A modern oop-approach is using DateTime
$date = new DateTime();
$date->sub(new DateInterval('P1D'));
echo $date->format('F j, Y') . "\n";
Or in your case (more readable/obvious)
$date = new DateTime();
$date->add(DateInterval::createFromDateString('yesterday'));
echo $date->format('F j, Y') . "\n";
(Because DateInterval
is negative here, we must add()
it here)
See also: DateTime::sub()
and DateInterval
Say we have:
public enum MyEnum {
Test1, Test2, Test3
}
To get the name of a enum variable use name()
:
MyEnum e = MyEnum.Test1;
String name = e.name(); // Returns "Test1"
To get the enum from a (string) name, use valueOf()
:
String name = "Test1";
MyEnum e = Enum.valueOf(MyEnum.class, name);
If you require integer
values to match enum fields, extend the enum class:
public enum MyEnum {
Test1(1), Test2(2), Test3(3);
public final int value;
MyEnum(final int value) {
this.value = value;
}
}
Now you can use:
MyEnum e = MyEnum.Test1;
int value = e.value; // = 1
And lookup the enum using the integer value:
MyEnum getValue(int value) {
for(MyEnum e: MyEunm.values()) {
if(e.value == value) {
return e;
}
}
return null;// not found
}
UPDATE table1 t1
SET t1.value =
(select t2.CODE from table2 t2
where t1.value = t2.DESC)
WHERE t1.UPDATETYPE='blah';
I'm not a big fan of any of the current answers, because they are either too verbose, or require you to jump around the code to understand what is going on.
I prefer doing this in a more react component centred way, by creating a <Switch/>
. The job of this component is to take a prop, and only render children whose child prop matches this one. So in the example below I have created a test
prop on the switch, and compared it to a value
prop on the children, only rendering the ones that match.
Example:
const Switch = props => {
const { test, children } = props
// filter out only children with a matching prop
return children.find(child => {
return child.props.value === test
})
}
const Sample = props => {
const someTest = true
return (
<Switch test={someTest}>
<div value={false}>Will display if someTest is false</div>
<div value={true}>Will display if someTest is true</div>
</Switch>
)
}
ReactDOM.render(
<Sample/>,
document.getElementById("react")
);
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
<div id="react"></div>
_x000D_
You can make the switch as simple or as complex as you want. Don't forget to perform more robust checking of the children and their value props.
I had a similar problem for xml. Just passing the error and solution (edited Jonathon version).
Code:
HttpGet xmlGet = new HttpGet( xmlContent );
Xml format:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<employee>
<code>CA</code>
<name>Cath</name>
<salary>300</salary>
</employee>
Error:
java.lang.IllegalArgumentException: Illegal character in path at index 0: <?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<contents>
<portalarea>CA</portalarea>
<portalsubarea>Cath</portalsubarea>
<direction>Navigator</direction>
</contents>
at java.net.URI.create(URI.java:859)
at org.apache.http.client.methods.HttpGet.<init>(HttpGet.java:69)
at de.vogella.jersey.first.Hello.validate(Hello.java:56)
Not Exactly perfect Solution: ( error vanished for that instance )
String theXml = URLEncoder.encode( xmlContent, "UTF-8" );
HttpGet xmlGet = new HttpGet( theXml );
Any idea What i should be doing ? It just cleared passed but had problem while doing this
HttpResponse response = httpclient.execute( xmlGet );
Sometimes doing this (the top-voted answer) is not always enough:
$('body').on('click', 'a.myclass', function() {
// do something
});
This can be an issue because of the order event handlers are fired. If you find yourself doing this, but it is causing issues because of the order in which it is handled.. You can always wrap that into a function, that when called "refreshes" the listener.
For example:
function RefreshSomeEventListener() {
// Remove handler from existing elements
$("#wrapper .specific-selector").off();
// Re-add event handler for all matching elements
$("#wrapper .specific-selector").on("click", function() {
// Handle event.
}
}
Because it is a function, whenever I set up my listener this way, I typically call it on document ready:
$(document).ready(function() {
// Other ready commands / code
// Call our function to setup initial listening
RefreshSomeEventListener();
});
Then, whenever you add some dynamically added element, call that method again:
function SomeMethodThatAddsElement() {
// Some code / AJAX / whatever.. Adding element dynamically
// Refresh our listener, so the new element is taken into account
RefreshSomeEventListener();
}
Hopefully this helps!
Regards,
#each
#each
runs a function for each element in an array. The following two code excerpts are equivalent:
x = 10
["zero", "one", "two"].each{|element|
x++
puts element
}
x = 10
array = ["zero", "one", "two"]
for i in 0..2
x++
puts array[i]
end
#map
#map
applies a function to each element of an array, returning the resulting array. The following are equivalent:
array = ["zero", "one", "two"]
newArray = array.map{|element| element.capitalize()}
array = ["zero", "one", "two"]
newArray = []
array.each{|element|
newArray << element.capitalize()
}
#map!
#map!
is like #map
, but modifies the array in place. The following are equivalent:
array = ["zero", "one", "two"]
array.map!{|element| element.capitalize()}
array = ["zero", "one", "two"]
array = array.map{|element| element.capitalize()}
I had trouble creating an AVD.
Either:
One of the first things you need to learn about SQL (and relational databases) is that you shouldn't store multiple values in a single field.
You should create another table and store one value per row.
This will make your querying easier, and your database structure better.
select
case when exists (select countryname from itemcountries where yourtable.id=itemcountries.id and countryname = @country) then 'national' else 'regional' end
from yourtable
Try this code
$('window').scrollDown(function(){$(#div).hide()});
$('window').scrollUp(function(){ $(#div).show() });
In ConfigureServices add services.AddCors();
BEFORE services.AddMvc();
Add UseCors in Configure
app.UseCors(builder => builder
.AllowAnyOrigin()
.AllowAnyMethod()
.AllowAnyHeader());
app.UseMvc();
Main point is that add app.UseCors
, before app.UseMvc()
.
Make sure you declare the CORS functionality before MVC so the middleware fires before the MVC pipeline gets control and terminates the request.
After the above method works you can change it configure a specific ORIGIN to accept api calls and avoid leaving your API so open to anyone
public void ConfigureServices(IServiceCollection services)
{
services.AddCors(options => options.AddPolicy("ApiCorsPolicy", builder =>
{
builder.WithOrigins("http://localhost:4200").AllowAnyMethod().AllowAnyHeader();
}));
services.AddMvc();
}
In the configure method tell CORS to use the policy you just created:
app.UseCors("ApiCorsPolicy");
app.UseMvc();
I just found this compact article on the subject - https://dzone.com/articles/cors-in-net-core-net-core-security-part-vi
The reason behind this error is : Flask app is already running, hasn't shut down and in middle of that we try to start another instance by: with app.app_context(): #Code Before we use this with statement we need to make sure that scope of the previous running app is closed.
When you get a UnicodeEncodeError
, it means that somewhere in your code you convert directly a byte string to a unicode one. By default in Python 2 it uses ascii encoding, and utf8 encoding in Python3 (both may fail because not every byte is valid in either encoding)
To avoid that, you must use explicit decoding.
If you may have 2 different encoding in your input file, one of them accepts any byte (say UTF8 and Latin1), you can try to first convert a string with first and use the second one if a UnicodeDecodeError occurs.
def robust_decode(bs):
'''Takes a byte string as param and convert it into a unicode one.
First tries UTF8, and fallback to Latin1 if it fails'''
cr = None
try:
cr = bs.decode('utf8')
except UnicodeDecodeError:
cr = bs.decode('latin1')
return cr
If you do not know original encoding and do not care for non ascii character, you can set the optional errors
parameter of the decode
method to replace
. Any offending byte will be replaced (from the standard library documentation):
Replace with a suitable replacement character; Python will use the official U+FFFD REPLACEMENT CHARACTER for the built-in Unicode codecs on decoding and ‘?’ on encoding.
bs.decode(errors='replace')
You can use the dangerouslySetInnerHTML
property to inject arbitrary HTML:
// Assume from another require()'ed module:_x000D_
var html = '<h1>Hello, world!</h1>'_x000D_
_x000D_
var MyComponent = React.createClass({_x000D_
render: function() {_x000D_
return React.createElement("h1", {dangerouslySetInnerHTML: {__html: html}})_x000D_
}_x000D_
})_x000D_
_x000D_
ReactDOM.render(React.createElement(MyComponent), document.getElementById('app'))
_x000D_
<script src="https://fb.me/react-0.14.3.min.js"></script>_x000D_
<script src="https://fb.me/react-dom-0.14.3.min.js"></script>_x000D_
<div id="app"></div>
_x000D_
You could even componentize this template behavior (untested):
class TemplateComponent extends React.Component {
constructor(props) {
super(props)
this.html = require(props.template)
}
render() {
return <div dangerouslySetInnerHTML={{__html: this.html}}/>
}
}
TemplateComponent.propTypes = {
template: React.PropTypes.string.isRequired
}
// use like
<TemplateComponent template='./template.html'/>
And with this, template.html
(in the same directory) looks something like (again, untested):
// ./template.html
module.exports = '<h1>Hello, world!</h1>'
Clean your data from your tables and then make relation between them.
Yes, you need to specify the encoding of the file you want to read.
Yes, this means that you have to know the encoding of the file you want to read.
No, there is no general way to guess the encoding of any given "plain text" file.
The one-arguments constructors of FileReader
always use the platform default encoding which is generally a bad idea.
Since Java 11 FileReader
has also gained constructors that accept an encoding: new FileReader(file, charset)
and new FileReader(fileName, charset)
.
In earlier versions of java, you need to use new InputStreamReader(
new FileInputStream(pathToFile)
, <encoding>)
.
I had accidentally enabled a different mode for the tab key. Fixed it by pressing Ctrl+Shift(for Mac only)+M.
From the Visual Studio Code Keybinding docs:
| Key | Command | Command id | | Ctrl + M | Toggle Use of Tab Key for Setting Focus | editor.action.toggleTabFocusMode |
The current tab control mode should also show up in the status bar:
The main difference between logging in with a postgres user or any other user created by us, is that when using the postgres user it is NOT necessary to specify the host with -h and instead for another user if.
$ psql -U postgres
# CREATE ROLE usertest LOGIN PASSWORD 'pwtest';
# CREATE DATABASE dbtest WITH OWNER = usertest;
# SHOW port;
# \q
$ psql -h localhost -d dbtest -U usertest -p 5432
GL
Running python -h
, I see a command line option:
-u : unbuffered binary stdout and stderr; also PYTHONUNBUFFERED=x see man page for details on internal buffering relating to '-u'
Here is the relevant doc.
You can delete any QuerySet you'd like. For example, to delete all blog posts with some Post model
Post.objects.all().delete()
and to delete any Post with a future publication date
Post.objects.filter(pub_date__gt=datetime.now()).delete()
You do, however, need to come up with a way to narrow down your QuerySet. If you just want a view to delete a particular object, look into the delete generic view.
EDIT:
Sorry for the misunderstanding. I think the answer is somewhere between. To implement your own, combine ModelForm
s and generic views. Otherwise, look into 3rd party apps that provide similar functionality. In a related question, the recommendation was django-filter.
I have created a Generic AsyncTask Listener which get result from AsycTask seperate class and give it to CallingActivity using Interface Callback.
new GenericAsyncTask(context,new AsyncTaskCompleteListener()
{
public void onTaskComplete(String response)
{
// do your work.
}
}).execute();
Interface
interface AsyncTaskCompleteListener<T> {
public void onTaskComplete(T result);
}
GenericAsyncTask
class GenericAsyncTask extends AsyncTask<String, Void, String>
{
private AsyncTaskCompleteListener<String> callback;
public A(Context context, AsyncTaskCompleteListener<String> cb) {
this.context = context;
this.callback = cb;
}
protected void onPostExecute(String result) {
finalResult = result;
callback.onTaskComplete(result);
}
}
Have a look at this , this question for more details.
Problem Cause
In mac os image rendering back end of matplotlib (what-is-a-backend to render using the API of Cocoa by default). There are Qt4Agg and GTKAgg and as a back-end is not the default. Set the back end of macosx that is differ compare with other windows or linux os.
Solution
~/.matplotlib
. ~/.matplotlib/matplotlibrc
there and add the following code: backend: TkAgg
From this link you can try different diagrams.
Load your "base" environment -- as OP's py34
-- when you load your terminal/shell.
If you use Bash, put the line:
conda activate py34
in your .bash_profile
(or .bashrc
):
$ echo 'conda activate py34' >> ~/.bash_profile
Every time you run a new terminal, conda environment py34
will be loaded.
Do not use "each". It is used for operations and changes in the same element. Use "map" to extract data from the element body and using it somewhere else.
I had a problem with surefire plugin itself. Going back to version 2.6 worked for me. Version 2.18/20/22.1 gave me the error. Now I tried version 3.0.0-M1 of surefire plugin and it works.
So something is wrong in surefire plgin between version 2.6 and 3.0.0. I assume there is something hardcoded as default which should not.
You can just use it like this:
Template t = ve.getTemplate("./src/main/resources/templates/email_html_new.vm");
It works.
You need to declare timer
outside the function. Otherwise, you get a brand new variable on each function invocation.
var timer;
function endAndStartTimer() {
window.clearTimeout(timer);
//var millisecBeforeRedirect = 10000;
timer = window.setTimeout(function(){alert('Hello!');},10000);
}
This tool gave me following results which helps me achieve the task as following code.
<div onclick="play();" id="vidwrap" style="height:315px;width:560px;background: black url('http://example.com/image.jpg') no-repeat center;overflow:hidden;cursor:pointer;"></div>
<script type="text/javascript">
function play(){
document.getElementById('vidwrap').innerHTML = '<iframe width="560" height="315" src="http://www.youtube.com/embed/xxxxxxxxx?autoplay=1" frameborder="0"></iframe>';
}
</script>
The easiest is setting a program variable (see GDB: assignment):
(gdb) l
6 {
7 int i;
8 struct file *f, *ftmp;
9
(gdb) set variable i = 10
(gdb) p i
$1 = 10
Or you can just update arbitrary (writable) location by address:
(gdb) set {int}0x83040 = 4
There's more. Read the manual.
When I use Junit4, import junit.framework.Assert; import junit.framework.TestCase; the warning info is :The type of Assert is deprecated
when import like this: import org.junit.Assert; import org.junit.Test; the warning has disappeared
possible duplicate of differences between 2 JUnit Assert classes
You can use attrchange jQuery plugin. The main function of the plugin is to bind a listener function on attribute change of HTML elements.
Code sample:
$("#myDiv").attrchange({
trackValues: true, // set to true so that the event object is updated with old & new values
callback: function(evnt) {
if(evnt.attributeName == "display") { // which attribute you want to watch for changes
if(evnt.newValue.search(/inline/i) == -1) {
// your code to execute goes here...
}
}
}
});
Nice and simple, from Pinal Dave's site:
http://blog.sqlauthority.com/2007/04/29/sql-server-random-number-generator-script-sql-query/
DECLARE @Random INT;
DECLARE @Upper INT;
DECLARE @Lower INT
SET @Lower = 3 ---- The lowest random number
SET @Upper = 7 ---- One more than the highest random number
SELECT @Random = ROUND(((@Upper - @Lower -1) * RAND() + @Lower), 0)
SELECT @Random
(I did make a slight change to the @Upper- to include the upper number, added 1.)
Here is GitHub's official document on Syncing a fork:
Syncing a fork
The Setup
Before you can sync, you need to add a remote that points to the upstream repository. You may have done this when you originally forked.
Tip: Syncing your fork only updates your local copy of the repository; it does not update your repository on GitHub.
$ git remote -v # List the current remotes origin https://github.com/user/repo.git (fetch) origin https://github.com/user/repo.git (push) $ git remote add upstream https://github.com/otheruser/repo.git # Set a new remote $ git remote -v # Verify new remote origin https://github.com/user/repo.git (fetch) origin https://github.com/user/repo.git (push) upstream https://github.com/otheruser/repo.git (fetch) upstream https://github.com/otheruser/repo.git (push)
Syncing
There are two steps required to sync your repository with the upstream: first you must fetch from the remote, then you must merge the desired branch into your local branch.
Fetching
Fetching from the remote repository will bring in its branches and their respective commits. These are stored in your local repository under special branches.
$ git fetch upstream # Grab the upstream remote's branches remote: Counting objects: 75, done. remote: Compressing objects: 100% (53/53), done. remote: Total 62 (delta 27), reused 44 (delta 9) Unpacking objects: 100% (62/62), done. From https://github.com/otheruser/repo * [new branch] master -> upstream/master
We now have the upstream's master branch stored in a local branch, upstream/master
$ git branch -va # List all local and remote-tracking branches * master a422352 My local commit remotes/origin/HEAD -> origin/master remotes/origin/master a422352 My local commit remotes/upstream/master 5fdff0f Some upstream commit
Merging
Now that we have fetched the upstream repository, we want to merge its changes into our local branch. This will bring that branch into sync with the upstream, without losing our local changes.
$ git checkout master # Check out our local master branch Switched to branch 'master' $ git merge upstream/master # Merge upstream's master into our own Updating a422352..5fdff0f Fast-forward README | 9 ------- README.md | 7 ++++++ 2 files changed, 7 insertions(+), 9 deletions(-) delete mode 100644 README create mode 100644 README.md
If your local branch didn't have any unique commits, git will instead perform a "fast-forward":
$ git merge upstream/master Updating 34e91da..16c56ad Fast-forward README.md | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-)
Tip: If you want to update your repository on GitHub, follow the instructions here
To produce patch for several commits, you should use format-patch
git command, e.g.
git format-patch -k --stdout R1..R2
This will export your commits into patch file in mailbox format.
To generate patch for the last commit, run:
git format-patch -k --stdout HEAD^
Then in another repository apply the patch by am
git command, e.g.
git am -3 -k file.patch
See: man git-format-patch
and git-am
.
You can try ScrollableStackView : https://github.com/gurhub/ScrollableStackView
It's Objective-C and Swift compatible library. It's available through CocoaPods.
Sample Code (Swift)
import ScrollableStackView
var scrollable = ScrollableStackView(frame: view.frame)
view.addSubview(scrollable)
// add your views with
let rectangle = UIView(frame: CGRect(x: 0, y: 0, width: 100, height: 55))
rectangle.backgroundColor = UIColor.blue
scrollable.stackView.addArrangedSubview(rectangle)
// ...
Sample Code (Objective-C)
@import ScrollableStackView
ScrollableStackView *scrollable = [[ScrollableStackView alloc] initWithFrame:self.view.frame];
scrollable.stackView.distribution = UIStackViewDistributionFillProportionally;
scrollable.stackView.alignment = UIStackViewAlignmentCenter;
scrollable.stackView.axis = UILayoutConstraintAxisVertical;
[self.view addSubview:scrollable];
UIView *rectangle = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 100, 55)];
[rectangle setBackgroundColor:[UIColor blueColor]];
// add your views with
[scrollable.stackView addArrangedSubview:rectangle];
// ...
I like Fernandes' answer even though you ask for the obj twice.
This should also do (more or less the same as Martin's A).
id obj;
if ((obj=[dict objectForKey:@"blah"])) {
// use obj
} else {
// Do something else like creating the obj and add the kv pair to the dict
}
Martin's and this answer both work on iPad2 iOS 5.0.1 9A405
I ran into this page while wondering the same question.
As others have noted, it's simple enough to just grab the __name__
attribute from a function in order to determine the name of the function. It's marginally trickier with objects that don't have a sane way to determine __name__
, i.e. base/primitive objects like basestring instances, ints, longs, etc.
Long story short, you could probably use the inspect module to make an educated guess about which one it is, but you would have to probably know what frame you're working in/traverse down the stack to find the right one. But I'd hate to imagine how much fun this would be trying to deal with eval/exec'ed code.
% python2 whats_my_name_again.py
needle => ''b''
['a', 'b']
[]
needle => '<function foo at 0x289d08ec>'
['c']
['foo']
needle => '<function bar at 0x289d0bfc>'
['f', 'bar']
[]
needle => '<__main__.a_class instance at 0x289d3aac>'
['e', 'd']
[]
needle => '<function bar at 0x289d0bfc>'
['f', 'bar']
[]
%
whats_my_name_again.py:
#!/usr/bin/env python
import inspect
class a_class:
def __init__(self):
pass
def foo():
def bar():
pass
a = 'b'
b = 'b'
c = foo
d = a_class()
e = d
f = bar
#print('globals', inspect.stack()[0][0].f_globals)
#print('locals', inspect.stack()[0][0].f_locals)
assert(inspect.stack()[0][0].f_globals == globals())
assert(inspect.stack()[0][0].f_locals == locals())
in_a_haystack = lambda: value == needle and key != 'needle'
for needle in (a, foo, bar, d, f, ):
print("needle => '%r'" % (needle, ))
print([key for key, value in locals().iteritems() if in_a_haystack()])
print([key for key, value in globals().iteritems() if in_a_haystack()])
foo()
Note that the "if ($str)"
and "IsNullOrEmpty"
tests don't work comparably in all instances: an assignment of $str=0
produces false for both, and depending on intended program semantics, this could yield a surprise.
Ok found the answer. exchange()
is the best way. Oddly the HttpEntity
class doesn't have a setBody()
method (it has getBody()
), but it is still possible to set the request body, via the constructor.
// Create the request body as a MultiValueMap
MultiValueMap<String, String> body = new LinkedMultiValueMap<String, String>();
body.add("field", "value");
// Note the body object as first parameter!
HttpEntity<?> httpEntity = new HttpEntity<Object>(body, requestHeaders);
ResponseEntity<MyModel> response = restTemplate.exchange("/api/url", HttpMethod.POST, httpEntity, MyModel.class);
Take a look here. Should be:
yourcommand &>filename
(redirects both stdout
and stderr
to filename).
Just use the JSON.stringify method and pass it through as the "data" parameter for the $.ajax function, like follows:
$.ajax({
type: "POST",
url: "index.php",
dataType: "json",
data: JSON.stringify({ paramName: info }),
success: function(msg){
$('.answer').html(msg);
}
});
You just need to make sure you include the JSON2.js file in your page...
I had these choices:
-----------------------------------------------
* 1 /usr/lib/jvm/jre-1.6.0-openjdk.x86_64/bin/java
+ 2 /usr/lib/jvm/jre-1.7.0-openjdk.x86_64/bin/java
3 /home/ec2-user/local/java/jre1.7.0_25/bin/java
When I chose 3, it didn't work. When I chose 2, it did work.
To expand on some of the previous answers, I found that Oracle DATE objects behave different from Oracle TIMESTAMP objects. In particular, if you set your NLS_DATE_FORMAT to include fractional seconds, the entire time portion is omitted.
My personal preference is to set DATE to "YYYY-MM-DD HH24:MI:SS", and to set TIMESTAMP to "YYYY-MM-DD HH24:MI:SSXFF".
Checking if v
contains the element x
:
#include <algorithm>
if(std::find(v.begin(), v.end(), x) != v.end()) {
/* v contains x */
} else {
/* v does not contain x */
}
Checking if v
contains elements (is non-empty):
if(!v.empty()){
/* v is non-empty */
} else {
/* v is empty */
}
Try this code, Let $ be defined
(function ($, Drupal) {
'use strict';
Drupal.behaviors.module_name = {
attach: function (context, settings) {
jQuery(document).ready(function($) {
$("#search_text").autocomplete({
source:results,
minLength:2,
position: { offset:'-30 0' },
select: function(event, ui ) {
goTo(ui.item.value);
return false;
}
});
});
}
};
})(jQuery, Drupal);
You can create a list of lists
public class MultiDimList: List<List<string>> { }
or a Dictionary of key-accessible Lists
public class MultiDimDictList: Dictionary<string, List<int>> { }
MultiDimDictList myDicList = new MultiDimDictList ();
myDicList.Add("ages", new List<int>());
myDicList.Add("Salaries", new List<int>());
myDicList.Add("AccountIds", new List<int>());
Generic versions, to implement suggestion in comment from @user420667
public class MultiDimList<T>: List<List<T>> { }
and for the dictionary,
public class MultiDimDictList<K, T>: Dictionary<K, List<T>> { }
// to use it, in client code
var myDicList = new MultiDimDictList<string, int> ();
myDicList.Add("ages", new List<T>());
myDicList["ages"].Add(23);
myDicList["ages"].Add(32);
myDicList["ages"].Add(18);
myDicList.Add("salaries", new List<T>());
myDicList["salaries"].Add(80000);
myDicList["salaries"].Add(100000);
myDicList.Add("accountIds", new List<T>());
myDicList["accountIds"].Add(321123);
myDicList["accountIds"].Add(342653);
or, even better, ...
public class MultiDimDictList<K, T>: Dictionary<K, List<T>>
{
public void Add(K key, T addObject)
{
if(!ContainsKey(key)) Add(key, new List<T>());
if (!base[key].Contains(addObject)) base[key].Add(addObject);
}
}
// and to use it, in client code
var myDicList = new MultiDimDictList<string, int> ();
myDicList.Add("ages", 23);
myDicList.Add("ages", 32);
myDicList.Add("ages", 18);
myDicList.Add("salaries", 80000);
myDicList.Add("salaries", 110000);
myDicList.Add("accountIds", 321123);
myDicList.Add("accountIds", 342653);
EDIT: to include an Add() method for nested instance:
public class NestedMultiDimDictList<K, K2, T>:
MultiDimDictList<K, MultiDimDictList<K2, T>>:
{
public void Add(K key, K2 key2, T addObject)
{
if(!ContainsKey(key)) Add(key,
new MultiDimDictList<K2, T>());
if (!base[key].Contains(key2))
base[key].Add(key2, addObject);
}
}
Well, you can easily accomplish the same effect using a regular expression. Assuming the separator is a space, it would look like:
awk '{ sub(/[^ ]+ +[^ ]+ +/, ""); print }'
let blurEffect = UIBlurEffect(style: UIBlurEffect.Style.dark)
let blurEffectView = UIVisualEffectView(effect: blurEffect)
blurEffectView.backgroundColor = .black
blurEffectView.alpha = 0.5
blurEffectView.frame = topView.bounds
if !self.presenting {
blurEffectView.frame.origin.x = 0
} else {
blurEffectView.frame.origin.x = -topView.frame.width
}
blurEffectView.frame.origin.x = -topView.frame.width
blurEffectView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
UIView.animate(withDuration: 0.2, delay: 0.0, options: [.curveEaseIn]) {
if !self.presenting {
blurEffectView.frame.origin.x = -topView.frame.width
} else {
blurEffectView.frame.origin.x = 0
}
view.addSubview(blurEffectView)
} completion: { (status) in
}
Try with: javac -encoding ISO-8859-1 file_name.java
Ok, this should be really easy:
$ sudo vi /etc/subversion/servers
Edit the file:
[Global]
http-proxy-host=my.proxy.com
http-proxy-port=3128
Save it, run svn
again and it will work.
You need to use objcopy to separate the debug information:
objcopy --only-keep-debug "${tostripfile}" "${debugdir}/${debugfile}"
strip --strip-debug --strip-unneeded "${tostripfile}"
objcopy --add-gnu-debuglink="${debugdir}/${debugfile}" "${tostripfile}"
I use the bash script below to separate the debug information into files with a .debug extension in a .debug directory. This way I can tar the libraries and executables in one tar file and the .debug directories in another. If I want to add the debug info later on I simply extract the debug tar file and voila I have symbolic debug information.
This is the bash script:
#!/bin/bash
scriptdir=`dirname ${0}`
scriptdir=`(cd ${scriptdir}; pwd)`
scriptname=`basename ${0}`
set -e
function errorexit()
{
errorcode=${1}
shift
echo $@
exit ${errorcode}
}
function usage()
{
echo "USAGE ${scriptname} <tostrip>"
}
tostripdir=`dirname "$1"`
tostripfile=`basename "$1"`
if [ -z ${tostripfile} ] ; then
usage
errorexit 0 "tostrip must be specified"
fi
cd "${tostripdir}"
debugdir=.debug
debugfile="${tostripfile}.debug"
if [ ! -d "${debugdir}" ] ; then
echo "creating dir ${tostripdir}/${debugdir}"
mkdir -p "${debugdir}"
fi
echo "stripping ${tostripfile}, putting debug info into ${debugfile}"
objcopy --only-keep-debug "${tostripfile}" "${debugdir}/${debugfile}"
strip --strip-debug --strip-unneeded "${tostripfile}"
objcopy --add-gnu-debuglink="${debugdir}/${debugfile}" "${tostripfile}"
chmod -x "${debugdir}/${debugfile}"
I think a nice solution is with the function filter of pandas and regex (match everything except "b"):
df.filter(regex="^(?!b$)")
void
is a reserved JavaScript keyword. It evaluates the expression and always returns undefined
.
It seems that the good-old ENVIRON
awk built-in hash is not mentioned at all. An example of its usage:
$ X=Solaris awk 'BEGIN{print ENVIRON["X"], ENVIRON["TERM"]}'
Solaris rxvt
The correct syntax is:
FOR EACH ROW SET NEW.bname = CONCAT( UCASE( LEFT( NEW.bname, 1 ) )
, LCASE( SUBSTRING( NEW.bname, 2 ) ) )
Use setNegative button, no Positive button required! I promise you'll win x
You are looking for the cp
command. You need to change directories so that you are outside of the directory you are trying to copy.
If the directory you're copying is called dir1
and you want to copy it to your /home/Pictures
folder:
cp -r dir1/ ~/Pictures/
Linux is case-sensitive and also needs the /
after each directory to know that it isn't a file. ~
is a special character in the terminal that automatically evaluates to the current user's home directory. If you need to know what directory you are in, use the command pwd
.
When you don't know how to use a Linux command, there is a manual page that you can refer to by typing:
man [insert command here]
at a terminal prompt.
Also, to auto complete long file paths when typing in the terminal, you can hit Tab after you've started typing the path and you will either be presented with choices, or it will insert the remaining part of the path.
For UTF-16, the character needs four bytes (two code units) if it starts with 0xD800 or greater; such a character is called a "surrogate pair." More specifically, a surrogate pair has the form:
[0xD800 - 0xDBFF] [0xDC00 - 0xDFF]
where [...] indicates a two-byte code unit with the given range. Anything <= 0xD7FF is one code unit (two bytes). Anything >= 0xE000 is invalid (except BOM markers, arguably).
See http://unicodebook.readthedocs.io/unicode_encodings.html, section 7.5.
String fname = ((EditText)findViewById(R.id.txtFirstName)).getText().toString();
String lname = ((EditText)findViewById(R.id.txtLastName)).getText().toString();
((EditText)findViewById(R.id.txtFullName)).setText(fname + " "+lname);
This just happen to me because in the php.ini the date.timezone was not set!
;date.timezone=Europe/Berlin
Using the php date() function triggered that warning.
I am using Sequelize ORM 6.0.0 and am using "logging": false as the rest but posted my answer for latest version of the ORM.
const sequelize = new Sequelize(
process.env.databaseName,
process.env.databaseUser,
process.env.password,
{
host: process.env.databaseHost,
dialect: process.env.dialect,
"logging": false,
define: {
// Table names won't be pluralized.
freezeTableName: true,
// All tables won't have "createdAt" and "updatedAt" Auto fields.
timestamps: false
}
}
);
Note: I am storing my secretes in a configuration file .env
observing the 12-factor methodology.
In PHP 5.3 or greater, you can get it like this:
$ip = getenv('HTTP_CLIENT_IP')?:
getenv('HTTP_X_FORWARDED_FOR')?:
getenv('HTTP_X_FORWARDED')?:
getenv('HTTP_FORWARDED_FOR')?:
getenv('HTTP_FORWARDED')?:
getenv('REMOTE_ADDR');
You can also use List's inbuilt foreach, such as:
List<T>.ForEach(item => Console.Write(item));
This code also runs significantly faster!
The above code also makes you able to manipulate Console.WriteLine, such as doing:
List<T>.ForEach(item => Console.Write(item + ",")); //Put a,b etc.
If you mean something like
SELECT * FROM AnotherTable
WHERE EXISTS (SELECT 1 FROM table WHERE...)
then it's a myth that the 1
is better than
SELECT * FROM AnotherTable
WHERE EXISTS (SELECT * FROM table WHERE...)
The 1
or *
in the EXISTS is ignored and you can write this as per Page 191 of the ANSI SQL 1992 Standard:
SELECT * FROM AnotherTable
WHERE EXISTS (SELECT 1/0 FROM table WHERE...)
Generates a WHERE field IN (‘item’, ‘item’) SQL query joined with AND if appropriate,
$this->db->where_in()
ex : $this->db->where_in('id', array('1','2','3'));
Generates a WHERE field IN (‘item’, ‘item’) SQL query joined with OR if appropriate
$this->db->or_where_in()
ex : $this->db->where_in('id', array('1','2','3'));
Both are synchronized version of HashMap, with difference in their core functionality and their internal structure.
ConcurrentHashMap consist of internal segments which can be viewed as independent HashMaps Conceptually. All such segments can be locked by separate threads in high concurrent executions. So, multiple threads can get/put key-value pairs from ConcurrentHashMap without blocking/waiting for each other. This is implemented for higher throughput.
whereas
Collections.synchronizedMap(), we get a synchronized version of HashMap and it is accessed in blocking manner. This means if multiple threads try to access synchronizedMap at same time, they will be allowed to get/put key-value pairs one at a time in synchronized manner.
You can use PHP to add a stylesheet for IE 10
Like:
if (stripos($_SERVER['HTTP_USER_AGENT'], 'MSIE 10')) {
<link rel="stylesheet" type="text/css" href="../ie10.css" />
}
Use FROM_UNIXTIME()
:
SELECT
FROM_UNIXTIME(timestamp)
FROM
your_table;
See also: MySQL documentation on FROM_UNIXTIME()
.
Totally agree with @tir38 and @android_griezmann. This would be the version in kotlin:
interface servicesEndPoint {
@Multipart
@POST("user/updateprofile")
fun updateProfile(@Part("user_id") id:RequestBody, @Part("full_name") other:fullName, @Part image: MultipartBody.Part, @Part("other") other:RequestBody): Single<UploadPhotoResponse>
companion object {
val API_BASE_URL = "YOUR_URL"
fun create(): servicesPhotoEndPoint {
val retrofit = Retrofit.Builder()
.addCallAdapterFactory(RxJava2CallAdapterFactory.create())
.addConverterFactory(GsonConverterFactory.create())
.baseUrl(API_BASE_URL)
.build()
return retrofit.create(servicesPhotoEndPoint::class.java)
}
}
}
// pass it like this
val file = File(RealPathUtils.getRealPathFromURI_API19(context, uri))
val requestFile: RequestBody = RequestBody.create(MediaType.parse("multipart/form-data"), file)
// MultipartBody.Part is used to send also the actual file name
val body: MultipartBody.Part = MultipartBody.Part.createFormData("image", file.name, requestFile)
// add another part within the multipart request
val fullName: RequestBody = RequestBody.create(MediaType.parse("multipart/form-data"), "Your Name")
servicesEndPoint.create().updateProfile(id, fullName, body, fullName)
To obtain the real path, use RealPathUtils. Check this class in the answers of @Harsh Bhavsar in this question: How to get the Full file path from URI.
To getRealPathFromURI_API19 you need permissions of READ_EXTERNAL_STORAGE
:last
is not part of the css spec, this is jQuery specific.
you should be looking for last-child
var first = div.querySelector('[move_id]:first-child');
var last = div.querySelector('[move_id]:last-child');
Use BigDecimal.valueOf(double d)
instead of new BigDecimal(double d)
. The last one has precision errors by float and double.
Did you dump your master gc log? So I met similar issue and I found SPARK_DRIVER_MEMORY only set the Xmx heap. The initial heap size remains 1G and the heap size never scale up to the Xmx heap.
Passing "--conf "spark.driver.extraJavaOptions=-Xms20g" resolves my issue.
ps aux | grep java and the you'll see the follow log:=
24501 30.7 1.7 41782944 2318184 pts/0 Sl+ 18:49 0:33 /usr/java/latest/bin/java -cp /opt/spark/conf/:/opt/spark/jars/* -Xmx30g -Xms20g
Based on an answer by Clay Bridges, here is an example of filtering using blocks (change yourArray
to your array variable name and testFunc
to the name of your testing function):
yourArray = [yourArray objectsAtIndexes:[yourArray indexesOfObjectsPassingTest:^BOOL(id obj, NSUInteger idx, BOOL *stop) {
return [self testFunc:obj];
}]];
After six days I find the answer which make me crazy! The answer is disable proxy at web.config file:
<system.net>
<defaultProxy>
<proxy usesystemdefault="False"/>
</defaultProxy>
</system.net>
This is the way that I have approached.
public class AppFCMService extends FirebaseMessagingService {
private final static String TAG = "FCM Message";
String notify, requstId, Notification;
PendingIntent pendingIntent;
@Override
public void onMessageReceived(RemoteMessage remoteMessage) {
Log.d(TAG, "From: " + remoteMessage.getFrom());
Log.d(TAG, "Notification Message Body: " + remoteMessage.getNotification().getBody());
//split string and getting order id from notification
String Str = remoteMessage.getNotification().getBody();
String[] tmp;
tmp = Str.split(" ");
String temp1 = tmp[0];
String temp2 = tmp[1];
String id = tmp[2];
notify = temp1 + " " + temp2;
requstId = id;
showNotification(remoteMessage.getNotification().getBody());
}
private void showNotification(String messageBody) {
// check whether session has been initiated or not
if (new SessionHelper(getApplicationContext()).isLoggedIn()) {
if (notify.equalsIgnoreCase("Travel request")) {
Intent intent = new Intent(this, ViewTravelDetailsActivity.class);
intent.putExtra("TravelRequestID", requstId);
intent.putExtra("BackPress", "Notify");
pendingIntent = PendingIntent.getActivity(this, 0, intent,
PendingIntent.FLAG_ONE_SHOT);
} else if (notify.equalsIgnoreCase("Timesheet replied")) {
Intent intent = new Intent(this, ViewReplyActivity.class);
intent.putExtra("timesheetActivityID", requstId);
intent.putExtra("BackPress", "Notify");
intent.putExtra("RealmData", "DeleteRealm");
intent.putExtra("isToday", "true");
pendingIntent = PendingIntent.getActivity(this, 0, intent,
PendingIntent.FLAG_ONE_SHOT);
} else {
Intent intent = new Intent(this, Dashboard.class);
intent.putExtra("timesheetActivityID", requstId);
pendingIntent = PendingIntent.getActivity(this, 0, intent,
PendingIntent.FLAG_ONE_SHOT);
}
} else {
Intent intent = new Intent(this, LoginActivity.class);
intent.putExtra("timesheetActivityID", requstId);
pendingIntent = PendingIntent.getActivity(this, 0, intent,
PendingIntent.FLAG_ONE_SHOT);
}
Bitmap notifyImage = BitmapFactory.decodeResource(getResources(), R.mipmap.ic_launcher);
Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this)
.setSmallIcon(R.mipmap.ic_launcher)
.setLargeIcon(notifyImage)
.setColor(Color.parseColor("#FFE74C3C"))
.setContentTitle("TEST")
.setContentText(messageBody)
.setAutoCancel(true)
.setSound(defaultSoundUri)
.setContentIntent(pendingIntent);
NotificationManager notificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(0, notificationBuilder.build());
}
}
First of all - prerequisite for downcast is that object you are casting is of the type you are casting to. Casting with dynamic_cast will check this condition in runtime (provided that casted object has some virtual functions) and throw bad_cast
or return NULL
pointer on failure. Compile-time casts will not check anything and will just lead tu undefined behaviour if this prerequisite does not hold.
Now analyzing your code:
DerivedType m_derivedType = m_baseType;
Here there is no casting. You are creating a new object of type DerivedType
and try to initialize it with value of m_baseType variable.
Next line is not much better:
DerivedType m_derivedType = (DerivedType)m_baseType;
Here you are creating a temporary of DerivedType
type initialized with m_baseType
value.
The last line
DerivedType * m_derivedType = (DerivedType*) & m_baseType;
should compile provided that BaseType
is a direct or indirect public base class of DerivedType
. It has two flaws anyway:
static_cast<DerivedType *>(&m_baseType)
BaseType m_baseType;
so any use of m_derivedType
pointer will result in undefined behaviour.I finally figured out the regex to change these all in old Python2 example scripts. Otherwise use 2to3.py.
Try it out on Regexr.com, doesn't work in NP++(?):
find: (?<=print)( ')(.*)(')
replace: ('$2')
for variables:
(?<=print)( )(.*)(\n)
('$2')\n
for label and variable:
(?<=print)( ')(.*)(',)(.*)(\n)
('$2',$4)\n
If you are using a Form Control
, you can get the same property as ActiveX
by using OLEFormat.Object
property of the Shape Object
. Better yet assign it in a variable declared as OptionButton to get the Intellisense kick in.
Dim opt As OptionButton
With Sheets("Sheet1") ' Try to be always explicit
Set opt = .Shapes("Option Button 1").OLEFormat.Object ' Form Control
Debug.Pring opt.Value ' returns 1 (true) or -4146 (false)
End With
But then again, you really don't need to know the value.
If you use Form Control
, you associate a Macro
or sub routine with it which is executed when it is selected. So you just need to set up a sub routine that identifies which button is clicked and then execute a corresponding action for it.
For example you have 2 Form Control
Option Buttons.
Sub CheckOptions()
Select Case Application.Caller
Case "Option Button 1"
' Action for option button 1
Case "Option Button 2"
' Action for option button 2
End Select
End Sub
In above code, you have only one sub routine assigned to both option buttons.
Then you test which called the sub routine by checking Application.Caller
.
This way, no need to check whether the option button value is true or false.
To fix this, i put this class on the webpage
<style>
td.vcenter {
vertical-align: middle !important;
text-align: center !important;
}
</style>
and this in my TemplateField
<asp:TemplateField ItemStyle-CssClass="vcenter">
as the CSS class points directly to the td (tabledata) element and has the !important statment at the end each setting. It will over rule bootsraps CSS class settings.
Hope it helps
I just went through this trouble. In my case I had a working script
SET devenvPath=C:\Program Files (x86)\Microsoft Visual Studio\2017\Professional\Common7\IDE\devenv.exe
"%devenvPath%" mySolution.sln /Rebuild "DebugWithUT|AnyCpu" /Out mySolution.Build.log
Today I started getting this exact error. But now I remember installing VS2019 day before. Looks like it changed something for VS2017. I went to VS2017 Update, installed latest version/update and it fixed it back.
Another solution, you can solve your problem using replaceAll
with some regex ^.{1}
(regex demo) for example :
String str = "Jamaica";
int nbr = 1;
str = str.replaceAll("^.{" + nbr + "}", "");//Output = amaica
In case any one wants it in Kotlin :
val dialogBuilder = AlertDialog.Builder(this)
// ...Irrelevant code for customizing the buttons and title
val dialogView = layoutInflater.inflate(R.layout.alert_label_editor, null)
dialogBuilder.setView(dialogView)
val editText = dialogView.findViewById(R.id.label_field)
editText.setText("test label")
val alertDialog = dialogBuilder.create()
alertDialog.show()
Reposted @user370305's answer.
Keyboard(BT) commands can be passed through command prompt
open command prompt and write "adb shell input keyevent keycode"
examples:-
for "enter" write
adb shell input keyevent 23
up
adb shell input keyevent 19
down
adb shell input keyevent 20
left
adb shell input keyevent 21
right
adb shell input keyevent 22
keycode List:
0 --> "KEYCODE_0"
1 --> "KEYCODE_SOFT_LEFT"
2 --> "KEYCODE_SOFT_RIGHT"
3 --> "KEYCODE_HOME"
4 --> "KEYCODE_BACK"
5 --> "KEYCODE_CALL"
6 --> "KEYCODE_ENDCALL"
7 --> "KEYCODE_0"
8 --> "KEYCODE_1"
9 --> "KEYCODE_2"
10 --> "KEYCODE_3"
11 --> "KEYCODE_4"
12 --> "KEYCODE_5"
13 --> "KEYCODE_6"
14 --> "KEYCODE_7"
15 --> "KEYCODE_8"
16 --> "KEYCODE_9"
17 --> "KEYCODE_STAR"
18 --> "KEYCODE_POUND"
19 --> "KEYCODE_DPAD_UP"
20 --> "KEYCODE_DPAD_DOWN"
21 --> "KEYCODE_DPAD_LEFT"
22 --> "KEYCODE_DPAD_RIGHT"
23 --> "KEYCODE_DPAD_CENTER"
24 --> "KEYCODE_VOLUME_UP"
25 --> "KEYCODE_VOLUME_DOWN"
26 --> "KEYCODE_POWER"
27 --> "KEYCODE_CAMERA"
28 --> "KEYCODE_CLEAR"
29 --> "KEYCODE_A"
30 --> "KEYCODE_B"
31 --> "KEYCODE_C"
32 --> "KEYCODE_D"
33 --> "KEYCODE_E"
34 --> "KEYCODE_F"
35 --> "KEYCODE_G"
36 --> "KEYCODE_H"
37 --> "KEYCODE_I"
38 --> "KEYCODE_J"
39 --> "KEYCODE_K"
40 --> "KEYCODE_L"
41 --> "KEYCODE_M"
42 --> "KEYCODE_N"
43 --> "KEYCODE_O"
44 --> "KEYCODE_P"
45 --> "KEYCODE_Q"
46 --> "KEYCODE_R"
47 --> "KEYCODE_S"
48 --> "KEYCODE_T"
49 --> "KEYCODE_U"
50 --> "KEYCODE_V"
51 --> "KEYCODE_W"
52 --> "KEYCODE_X"
53 --> "KEYCODE_Y"
54 --> "KEYCODE_Z"
55 --> "KEYCODE_COMMA"
56 --> "KEYCODE_PERIOD"
57 --> "KEYCODE_ALT_LEFT"
58 --> "KEYCODE_ALT_RIGHT"
59 --> "KEYCODE_SHIFT_LEFT"
60 --> "KEYCODE_SHIFT_RIGHT"
61 --> "KEYCODE_TAB"
62 --> "KEYCODE_SPACE"
63 --> "KEYCODE_SYM"
64 --> "KEYCODE_EXPLORER"
65 --> "KEYCODE_ENVELOPE"
66 --> "KEYCODE_ENTER"
67 --> "KEYCODE_DEL"
68 --> "KEYCODE_GRAVE"
69 --> "KEYCODE_MINUS"
70 --> "KEYCODE_EQUALS"
71 --> "KEYCODE_LEFT_BRACKET"
72 --> "KEYCODE_RIGHT_BRACKET"
73 --> "KEYCODE_BACKSLASH"
74 --> "KEYCODE_SEMICOLON"
75 --> "KEYCODE_APOSTROPHE"
76 --> "KEYCODE_SLASH"
77 --> "KEYCODE_AT"
78 --> "KEYCODE_NUM"
79 --> "KEYCODE_HEADSETHOOK"
80 --> "KEYCODE_FOCUS"
81 --> "KEYCODE_PLUS"
82 --> "KEYCODE_MENU"
83 --> "KEYCODE_NOTIFICATION"
84 --> "KEYCODE_SEARCH"
85 --> "KEYCODE_MEDIA_PLAY_PAUSE"
86 --> "KEYCODE_MEDIA_STOP"
87 --> "KEYCODE_MEDIA_NEXT"
88 --> "KEYCODE_MEDIA_PREVIOUS"
89 --> "KEYCODE_MEDIA_REWIND"
90 --> "KEYCODE_MEDIA_FAST_FORWARD"
91 --> "KEYCODE_MUTE"
92 --> "KEYCODE_PAGE_UP"
93 --> "KEYCODE_PAGE_DOWN"
94 --> "KEYCODE_PICTSYMBOLS"
...
122 --> "KEYCODE_MOVE_HOME"
123 --> "KEYCODE_MOVE_END"
You can try this
formDataToJSON($('#form_example'));
# Create a function to convert the serialize and convert the form data
# to JSON
# @param : $('#form_example');
# @return a JSON Stringify
function formDataToJSON(form) {
let obj = {};
let formData = form.serialize();
let formArray = formData.split("&");
for (inputData of formArray){
let dataTmp = inputData.split('=');
obj[dataTmp[0]] = dataTmp[1];
}
return JSON.stringify(obj);
}
I was able to fix this on Windows 7 64-bit running Python 3.4.3 by running the set
command at a command prompt to determine the existing Visual Studio tools environment variable; in my case it was VS140COMNTOOLS
for Visual Studio Community 2015.
Then run the following (substituting the variable on the right-hand side if yours has a different name):
set VS100COMNTOOLS=%VS140COMNTOOLS%
This allowed me to install the PyCrypto module that was previously giving me the same error as the OP.
For a more permanent solution, add this environment variable to your Windows environment via Control Panel ("Edit the system environment variables"), though you might need to use the actual path instead of the variable substitution.
For anyone having this problem today, the solution is simply:
list-style: "- "
Use Eclipse with EPIC: It gives you a nice IDE with debugging possibilities, including the ability to place breakpoints and the Perl Expression View
for inspecting the value of variables.
You can use DateTime::createFromFormat()
for this purpose:
function validateDate($date, $format = 'Y-m-d')
{
$d = DateTime::createFromFormat($format, $date);
// The Y ( 4 digits year ) returns TRUE for any integer with any number of digits so changing the comparison from == to === fixes the issue.
return $d && $d->format($format) === $date;
}
[Function taken from this answer. Also on php.net. Originally written by Glavic.]
Test cases:
var_dump(validateDate('2013-13-01')); // false
var_dump(validateDate('20132-13-01')); // false
var_dump(validateDate('2013-11-32')); // false
var_dump(validateDate('2012-2-25')); // false
var_dump(validateDate('2013-12-01')); // true
var_dump(validateDate('1970-12-01')); // true
var_dump(validateDate('2012-02-29')); // true
var_dump(validateDate('2012', 'Y')); // true
var_dump(validateDate('12012', 'Y')); // false
I believe, by default, boto picks the region which is set in aws cli. You can run command #aws configure and press enter (it shows what creds you have set in aws cli with region)twice to confirm your region.
I solved the problem.
This is a JAR file conflict.
It seems that I have two JAR files on my buildpath that include the same package and classes.
smack.jar
and android_maps_lib-1.0.2
Deleting this package from one of the JAR files solved the problem.
The best way to catch the position is by FindIndex
This function is available only for List<>
Example
int id = listMyObject.FindIndex(x => x.Id == 15);
If you have enumerator or array use this way
int id = myEnumerator.ToList().FindIndex(x => x.Id == 15);
or
int id = myArray.ToList().FindIndex(x => x.Id == 15);
>>> " xyz ".rstrip()
' xyz'
There is more about rstrip
in the documentation.