Use this
Fluttertoast.showToast(
msg: "This is Toast messaget",
toastLength: Toast.LENGTH_SHORT,
gravity: ToastGravity.CENTER,
timeInSecForIos: 1
);
Some dummy codes might help you.
private static NotificationCompat.Builder buildNotificationCommon(Context _context, .....) {
NotificationCompat.Builder builder = new NotificationCompat.Builder(_context)
.setWhen(System.currentTimeMillis()).......;
//Vibration
builder.setVibrate(new long[] { 1000, 1000, 1000, 1000, 1000 });
//LED
builder.setLights(Color.RED, 3000, 3000);
//Ton
builder.setSound(Uri.parse("uri://sadfasdfasdf.mp3"));
return builder;
}
Add below permission for Vibration in AndroidManifest.xml
file
<uses-permission android:name="android.permission.VIBRATE" />
I came up with this solution.
Click to view image of blurry effect
It is kind of a trick which uses an absolutely positioned child div
, sets its background image same as the parent div
and then uses the background-attachment:fixed
CSS property together with the same background
properties set on the parent element.
Then you apply filter:blur(10px)
(or any value) on the child div.
*{
margin:0;
padding:0;
box-sizing: border-box;
}
.background{
position: relative;
width:100%;
height:100vh;
background-image:url('https://images.unsplash.com/photo-1547937414-009abc449011?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=1350&q=80');
background-size:cover;
background-position: center;
background-repeat:no-repeat;
}
.blur{
position: absolute;
top:0;
left:0;
width:50%;
height:100%;
background-image:url('https://images.unsplash.com/photo-1547937414-009abc449011?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=1350&q=80');
background-position: center;
background-repeat: no-repeat;
background-attachment: fixed;
background-size:cover;
filter:blur(10px);
transition:filter .5s ease;
backface-visibility: hidden;
}
.background:hover .blur{
filter:blur(0);
}
.text{
display: inline-block;
font-family: sans-serif;
color:white;
font-weight: 600;
text-align: center;
position: relative;
left:25%;
top:50%;
transform:translate(-50%,-50%);
}
_x000D_
<head>
<title>Blurry Effect</title>
</head>
<body>
<div class="background">
<div class="blur"></div>
<h1 class="text">This is the <br>blurry side</h1>
</div>
</body>
_x000D_
You can use the String.format method as used in another answer to generate a string of 0's,
String.format("%0"+length+"d",0)
This can be applied to your problem by dynamically adjusting the number of leading 0's in a format string:
public String leadingZeros(String s, int length) {
if (s.length() >= length) return s;
else return String.format("%0" + (length-s.length()) + "d%s", 0, s);
}
It's still a messy solution, but has the advantage that you can specify the total length of the resulting string using an integer argument.
Follow these commands to fix the problem.
In a terminal:
Clean the entire NPM cache:
$ sudo npm cache clean -f
sudo npm install -g n
Install the latest stable version of Node.js:
sudo n stable
Now the latest version of Node.js was installed. Check the version using:
node -v
I have added the following on my excel sheet
=VLOOKUP(B2,Res_partner!$A$2:$C$21208,1,FALSE)
Still doesn't seem to work. I get an #N/A
BUT
=VLOOKUP(B2,Res_partner!$C$2:$C$21208,1,FALSE)
Works
This is how I do it, useful for simple custom objects to which you keep adding attributes:
Given an object created with obj = type("Obj",(object,),{})
, or by simply:
class Obj: pass
obj = Obj()
Add some attributes:
obj.name = 'gary'
obj.age = 32
then, to obtain a dictionary with only the custom attributes:
{key: value for key, value in obj.__dict__.items() if not key.startswith("__")}
# {'name': 'gary', 'age': 32}
If you are in a network of users, then the username will be different:
Environment.UserName
- Will Display format : 'Username'
rather than
System.Security.Principal.WindowsIdentity.GetCurrent().Name
- Will Display format : 'NetworkName\Username'
Choose the format you want.
I use this step, first Set delegate texfield in viewdidload.
override func viewDidLoad() {
super.viewDidLoad()
textfield.delegate = self
}
and then shouldChangeCharactersIn after you include UITextFieldDelegate.
extension viewController: UITextFieldDelegate {
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
let newLength = (textField.text?.utf16.count)! + string.utf16.count - range.length
if newLength <= 8 {
return true
} else {
return false
}
}
}
You can get the all record of the date '2016-07-14' by using it
whereDate('date','=','2016-07-14')
Or use the another code for dynamic date
whereDate('date',$date)
The documentation (https://angular.io/guide/template-syntax#!#star-template) gives the following example. Say we have template code like this:
<hero-detail *ngIf="currentHero" [hero]="currentHero"></hero-detail>
Before it will be rendered, it will be "de-sugared". That is, the asterix notation will be transcribed to the notation:
<template [ngIf]="currentHero">
<hero-detail [hero]="currentHero"></hero-detail>
</template>
If 'currentHero' is truthy this will be rendered as
<hero-detail> [...] </hero-detail>
But what if you want an conditional output like this:
<h1>Title</h1><br>
<p>text</p>
.. and you don't want the output be wrapped in a container.
You could write the de-sugared version directly like so:
<template [ngIf]="showContent">
<h1>Title</h1>
<p>text</p><br>
</template>
And this will work fine. However, now we need ngIf to have brackets [] instead of an asterix *, and this is confusing (https://github.com/angular/angular.io/issues/2303)
For that reason a different notation was created, like so:
<ng-container *ngIf="showContent"><br>
<h1>Title</h1><br>
<p>text</p><br>
</ng-container>
Both versions will produce the same results (only the h1 and p tag will be rendered). The second one is preferred because you can use *ngIf like always.
The basic one, ask tasklist to filter its output and only show the indicated process id information
tasklist /fi "pid eq 4444"
To only get the process name, the line must be splitted
for /f "delims=," %%a in ('
tasklist /fi "pid eq 4444" /nh /fo:csv
') do echo %%~a
In this case, the list of processes is retrieved without headers (/nh
) in csv format (/fo:csv
). The commas are used as token delimiters and the first token in the line is the image name
note: In some windows versions (one of them, my case, is the spanish windows xp version), the pid filter in the tasklist does not work. In this case, the filter over the list of processes must be done out of the command
for /f "delims=," %%a in ('
tasklist /fo:csv /nh ^| findstr /b /r /c:"[^,]*,\"4444\","
') do echo %%~a
This will generate the task list and filter it searching for the process id in the second column of the csv output.
edited: alternatively, you can suppose what has been made by the team that translated the OS to spanish. I don't know what can happen in other locales.
tasklist /fi "idp eq 4444"
As you have noticed, xscale
and yscale
does not support a simple linear re-scaling (unfortunately). As an alternative to Hooked's answer, instead of messing with the data, you can trick the labels like so:
ticks = ticker.FuncFormatter(lambda x, pos: '{0:g}'.format(x*scale))
ax.xaxis.set_major_formatter(ticks)
A complete example showing both x and y scaling:
import numpy as np
import pylab as plt
import matplotlib.ticker as ticker
# Generate data
x = np.linspace(0, 1e-9)
y = 1e3*np.sin(2*np.pi*x/1e-9) # one period, 1k amplitude
# setup figures
fig = plt.figure()
ax1 = fig.add_subplot(121)
ax2 = fig.add_subplot(122)
# plot two identical plots
ax1.plot(x, y)
ax2.plot(x, y)
# Change only ax2
scale_x = 1e-9
scale_y = 1e3
ticks_x = ticker.FuncFormatter(lambda x, pos: '{0:g}'.format(x/scale_x))
ax2.xaxis.set_major_formatter(ticks_x)
ticks_y = ticker.FuncFormatter(lambda x, pos: '{0:g}'.format(x/scale_y))
ax2.yaxis.set_major_formatter(ticks_y)
ax1.set_xlabel("meters")
ax1.set_ylabel('volt')
ax2.set_xlabel("nanometers")
ax2.set_ylabel('kilovolt')
plt.show()
And finally I have the credits for a picture:
Note that, if you have text.usetex: true
as I have, you may want to enclose the labels in $
, like so: '${0:g}$'
.
I thought the regular modulus operator would work for this in java, but it can't be hard to code. Just divide the numerator by the denominator, and take the integer portion of the result. Multiply that by the denominator, and subtract the result from the numerator.
x = n / d
xint = Integer portion of x
result = n - d * xint
In new version of jquery, could done it via following steps:
serializeArray()
push()
or similar methods to add additional params to the array,$.param(arr)
to get serialized string, which could be used as jquery ajax's data
param.Example code:
var paramArr = $("#loginForm").serializeArray();
paramArr.push( {name:'size', value:7} );
$.post("rest/account/login", $.param(paramArr), function(result) {
// ...
}
New Operator for lambda expression added in java 8
Lambda expression is the short way of method writing.
It is indirectly used to implement functional interface
Primary Syntax : (parameters) -> { statements; }
There are some basic rules for effective lambda expressions writting which you should konw.
You could use flatMap. It can filter and map in one.
$scope.appIds = $scope.applicationsHere.flatMap(obj => obj.selected ? obj.id : [])
Yes, the time complexity of this is O(n^2).
I did as follows and it worked: (Current date without timestamp)
SimpleDateFormat dateFormat = new SimpleDateFormat("MM/dd/yyyy");
Date today = dateFormat.parse(dateFormat.format(new Date()));
I tried this and got a ';'-delimited csv file:
--#SET TERMINATOR %
EXPORT TO result.csv OF DEL MODIFIED BY CHARDEL;
SELECT * FROM A
Add a line to your app.config in the configSections element
<configSections>
<section name="log4net"
type="log4net.Config.Log4NetConfigurationSectionHandler, log4net, Version=1.2.10.0,
Culture=neutral, PublicKeyToken=1b44e1d426115821" />
</configSections>
Then later add the log4Net section, but delegate to the actual log4Net config file elsewhere...
<log4net configSource="Config\Log4Net.config" />
In your application code, when you create the log, write
private static ILog GetLog(string logName)
{
ILog log = LogManager.GetLogger(logName);
return log;
}
You may want to look at Tibbo VSPDL for creating a linux virtual serial port using a Kernel driver -- it seems pretty new, and is available for download right now (beta version). Not sure about the license at this point, or whether they want to make it available commercially only in the future.
There are other commercial alternatives, such as http://www.ttyredirector.com/.
In Open Source, Remserial (GPL) may also do what you want, using Unix PTY's. It transmits the serial data in "raw form" to a network socket; STTY-like setup of terminal parameters must be done when creating the port, changing them later like described in RFC 2217 does not seem to be supported. You should be able to run two remserial instances to create a virtual nullmodem like com0com, except that you'll need to set up port speed etc in advance.
Socat (also GPL) is like an extended variant of Remserial with many many more options, including a "PTY" method for redirecting the PTY to something else, which can be another instance of Socat. For Unit tets, socat is likely nicer than remserial because you can directly cat files into the PTY. See the PTY example on the manpage. A patch exists under "contrib" to provide RFC2217 support for negotiating serial line settings.
What I did so that input didn't take up the whole line, and be able to place the input in a paragraph, I used a span tag and display to inline-block
html:
<span>cluster:
<input class="short-input" type="text" name="cluster">
</span>
css:
span{display: inline-block;}
<html>_x000D_
<head>_x000D_
<title>_x000D_
webpage_x000D_
</title>_x000D_
</head>_x000D_
<body style="background-color:blue;text-align:center">_x000D_
welcome to my page_x000D_
</body>_x000D_
</html>
_x000D_
var date = new Date();
date.setDate(date.getDate()-1);
$('#date').datepicker({
startDate: date
});
If the two byte arrays you mention is your entire key, the values are in the range 0-51, unique and the order within the a and b arrays is insignificant, my math tells me that there is only just about 26 million possible permutations and that you likely are trying to fill the map with values for all possible keys.
In this case, both filling and retrieving values from your data store would of course be much faster if you use an array instead of a HashMap and index it from 0 to 25989599.
For me, I was writing to a file that is opened in Excel.
Another way, just for completeness.
DECLARE @empNumber INT = 7123
SELECT STUFF('000000', 6-LEN(@empNumber)+1, LEN(@empNumber), @empNumber)
Or, as per your query
SELECT STUFF('000000', 6-LEN(EmployeeID)+1, LEN(EmployeeID), EmployeeID)
AS EmployeeCode
FROM dbo.RequestItems
WHERE ID=0
For those who are getting the path dynamicly... e.g. drag&drop:
Some main constructions get drag&dropped file with double quotes like:
"C:\MyPath\MyFile.txt"
Quick and nice solution is to use this function to remove chars from string:
void removeCharsFromString( string &str, char* charsToRemove ) {
for ( unsigned int i = 0; i < strlen(charsToRemove); ++i ) {
str.erase( remove(str.begin(), str.end(), charsToRemove[i]), str.end() );
}
}
string myAbsolutepath; //fill with your absolute path
removeCharsFromString( myAbsolutepath, "\"" );
myAbsolutepath
now contains just C:\MyPath\MyFile.txt
The function needs these libraries: <iostream>
<algorithm>
<cstring>
.
The function was based on this answer.
Working Fiddle: http://ideone.com/XOROjq
You can also use the FileReader class :
var reader = new FileReader();
reader.onload = function (e) {
var data = this.result;
}
reader.readAsDataURL( file );
To make your life simpler, you may want to consider using JAX-WS framework such as Apache CXF or Apache Axis2.
Here is the link that describes how to setup WS-Security for Apache CXF -> http://cxf.apache.org/docs/ws-security.html
EDIT
By the way, the Authorization
field just uses simple Base64 encoding.
According to this ( http://www.motobit.com/util/base64-decoder-encoder.asp ), the decoded value is german:german
.
You can get that error if you have an object with the same name as the schema. For example:
create sequence s2;
begin
s2.a;
end;
/
ORA-06550: line 2, column 6:
PLS-00302: component 'A' must be declared
ORA-06550: line 2, column 3:
PL/SQL: Statement ignored
When you refer to S2.MY_FUNC2
the object name is being resolved so it doesn't try to evaluate S2 as a schema name. When you just call it as MY_FUNC2
there is no confusion, so it works.
The documentation explains name resolution. The first piece of the qualified object name - S2 here - is evaluated as an object on the current schema before it is evaluated as a different schema.
It might not be a sequence; other objects can cause the same error. You can check for the existence of objects with the same name by querying the data dictionary.
select owner, object_type, object_name
from all_objects
where object_name = 'S2';
EDIT:
Ok I found why the int.ToString() in LINQtoEF fails, please read this post: Problem with converting int to string in Linq to entities
This works on my side :
List<string> materialTypes = (from u in result.Users
select u.LastName)
.Union(from u in result.Users
select SqlFunctions.StringConvert((double) u.UserId)).ToList();
On yours it should be like this:
IList<String> materialTypes = ((from tom in context.MaterialTypes
where tom.IsActive == true
select tom.Name)
.Union(from tom in context.MaterialTypes
where tom.IsActive == true
select SqlFunctions.StringConvert((double)tom.ID))).ToList();
Thanks, i've learnt something today :)
Found a really helpful link for that. Using SQLCMD for this is really easier than solving this with a stored procedure
http://www.excel-sql-server.com/sql-server-export-to-excel-using-bcp-sqlcmd-csv.htm
I had the same problem and solved by using Newtonsoft.Json;
var list = JsonConvert.SerializeObject(model,
Formatting.None,
new JsonSerializerSettings() {
ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore
});
return Content(list, "application/json");
You don't need to convert it
switch(op)
{
case Operator.PLUS:
{
// your code
// for plus operator
break;
}
case Operator.MULTIPLY:
{
// your code
// for MULTIPLY operator
break;
}
default: break;
}
By the way, use brackets
if user doesn't have any qr reader, what will happen to the application? if it crashes, may i ask user to download for example QrDroid and after that use it?
Interestingly, Google now introduced Mobile Vision APIs, they are integrated in play services itself.
In your Gradle file just add:
compile 'com.google.android.gms:play-services-vision:11.4.0'
Taken from this QR code tutorial.
UPDATE 2020:
Now QR code scanning is also a part of ML Kit, so you can bundle the model inside the app and use it by integrating the following gradle dependency:
dependencies {
// ...
// Use this dependency to bundle the model with your app
implementation 'com.google.mlkit:barcode-scanning:16.0.3'
}
Or you can use the following gradle dependency to dynamically download the models from Google Play Services:
dependencies {
// ...
// Use this dependency to use the dynamically downloaded model in Google Play Services
implementation 'com.google.android.gms:play-services-mlkit-barcode-scanning:16.1.2'
}
Taken from this link.
In Bootstrap 4 one should use the text-center
class to align inline-blocks.
NOTE: text-align:center;
defined in a custom class you apply to your parent element will work regardless of the Bootstrap version you are using. And that's exactly what .text-center
applies.
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css">_x000D_
_x000D_
<div class="container">_x000D_
<div class="row">_x000D_
<div class="col text-center">_x000D_
<button class="btn btn-default">Centered button</button>_x000D_
</div>_x000D_
</div>_x000D_
</div>
_x000D_
If the content to be centered is block or flex (not inline-
), one could use flexbox to center it:
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css">_x000D_
_x000D_
<div class="d-flex justify-content-center">_x000D_
<button class="btn btn-default">Centered button</button>_x000D_
</div>
_x000D_
... which applies display: flex; justify-content: center
to parent.
Note: don't use .row.justify-content-center
instead of .d-flex.justify-content-center
, as .row
applies negative margins on certain responsiveness intervals, which results into unexpected horizontal scrollbars (unless .row
is a direct child of .container
, which applies lateral padding to counteract the negative margin, on the correct responsiveness intervals). If you must use .row
, for whatever reason, override its margin and padding with .m-0.p-0
, in which case you end up with pretty much the same styles as .d-flex
.
Important note: The second solution is problematic when the centered content (the button) exceeds the width of the parent (.d-flex
) especially when the parent has viewport width, specifically because it makes it impossible to horizontally scroll to the start of the content (left-most).
So don't use it when the content to be centered could become wider than the available parent width and all content should be accessible.
Increasing SQL-Wait-Timeout worked for me in this case, try this:
mysql_query("SET @@session.wait_timeout=900", $link);
before you first "normal" SQL queries.
You can use HttpPost, there are methods to add Header to the Request.
DefaultHttpClient httpclient = new DefaultHttpClient();
String url = "http://localhost";
HttpPost httpPost = new HttpPost(url);
httpPost.addHeader("header-name" , "header-value");
HttpResponse response = httpclient.execute(httpPost);
The DateTime
should always be internally in the "american" (Gregorian) calendar. So if you do
var str = dateTime.ToString(@"yyyy/MM/dd hh:mm:ss tt", new CultureInfo("en-US"));
you should get what you want in many less lines.
I blindly followed the accepted answer of using pip3 freeze > requirements.txt
It generated a huge file that listed all the dependencies of the entire solution, which is not what I wanted.
So you need to figure out what sort of requirements.txt you are trying to generate.
If you need a requirements.txt file that has ALL the dependencies, then use the pip3
pip3 freeze > requirements.txt
However, if you want to generate a minimal requirements.txt that only lists the dependencies you need, then use the pipreqs package. Especially helpful if you have numerous requirements.txt files in per component level in the project and not a single file on the solution wide level.
pip install pipreqs
pipreqs [path to folder]
e.g. pipreqs .
First subtract the pivot point (cx,cy)
, then rotate it, then add the point again.
Untested:
POINT rotate_point(float cx,float cy,float angle,POINT p)
{
float s = sin(angle);
float c = cos(angle);
// translate point back to origin:
p.x -= cx;
p.y -= cy;
// rotate point
float xnew = p.x * c - p.y * s;
float ynew = p.x * s + p.y * c;
// translate point back:
p.x = xnew + cx;
p.y = ynew + cy;
return p;
}
Here's what worked for me to download the latest version of an artifact called "component.jar" with Maven 3.1.1 in the end (other suggestions did not, mostly due to maven version changes I believe)
This actually downloads the file and copies it into the local working directory
From bash:
mvn dependency:get \
-DrepoUrl=http://.../ \
-Dartifact=com.foo.something:component:LATEST:jar \
-Dtransitive=false \
-Ddest=component.jar \
solution for Bootstrap 4
You can use it
Alignment
use this class justify-content-center
Change the alignment of pagination components with flexbox utilities.
and learn more about it pagination
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" rel="stylesheet"/>_x000D_
_x000D_
_x000D_
_x000D_
<nav aria-label="Page navigation example">_x000D_
<ul class="pagination justify-content-center">_x000D_
<li class="page-item disabled">_x000D_
<a class="page-link" href="#" tabindex="-1">Previous</a>_x000D_
</li>_x000D_
<li class="page-item"><a class="page-link" href="#">1</a></li>_x000D_
<li class="page-item"><a class="page-link" href="#">2</a></li>_x000D_
<li class="page-item"><a class="page-link" href="#">3</a></li>_x000D_
<li class="page-item">_x000D_
<a class="page-link" href="#">Next</a>_x000D_
</li>_x000D_
</ul>_x000D_
</nav>
_x000D_
Do:
con.query('SET GLOBAL connect_timeout=28800')
con.query('SET GLOBAL interactive_timeout=28800')
con.query('SET GLOBAL wait_timeout=28800')
Parameter meaning (taken from MySQL Workbench in Navigator: Instance > Options File > Tab "Networking" > Section "Timeout Settings")
BTW: 28800 seconds are 8 hours, so for a 10 hour execution time these values should be actually higher.
You're getting None
because list.sort()
it operates in-place, meaning that it doesn't return anything, but modifies the list itself. You only need to call a.sort()
without assigning it to a
again.
There is a built in function sorted()
, which returns a sorted version of the list - a = sorted(a)
will do what you want as well.
It requires a bit of rearranging, but when
does a good job to replace conditionals above. Here's the example from above written using the declarative syntax. Note that test3
stage is now two different stages. One that runs on the master branch and one that runs on anything else.
stage ('Test 3: Master') {
when { branch 'master' }
steps {
echo 'I only execute on the master branch.'
}
}
stage ('Test 3: Dev') {
when { not { branch 'master' } }
steps {
echo 'I execute on non-master branches.'
}
}
I'm Daniel Stenberg.
I founded the curl project back in 1998, I wrote the initial curl version and I created libcurl. I've written more than half of all the 24,000 commits done in the source code repository up to this point in time. I'm still the lead developer of the project. To a large extent, curl is my baby.
I shipped the first version of curl as open source since I wanted to "give back" to the open source world that had given me so much code already. I had used so much open source and I wanted to be as cool as the other open source authors.
Thanks to it being open source, literally thousands of people have been able to help us out over the years and have improved the products, the documentation. the web site and just about every other detail around the project. curl and libcurl would never have become the products that they are today were they not open source. The list of contributors now surpass 1900 names and currently the list grows with a few hundred names per year.
Thanks to curl and libcurl being open source and liberally licensed, they were immediately adopted in numerous products and soon shipped by operating systems and Linux distributions everywhere thus getting a reach beyond imagination.
Thanks to them being "everywhere", available and liberally licensed they got adopted and used everywhere and by everyone. It created a defacto transfer library standard.
At an estimated six billion installations world wide, we can safely say that curl is the most widely used internet transfer library in the world. It simply would not have gone there had it not been open source. curl runs in billions of mobile phones, a billion Windows 10 installations, in a half a billion games and several hundred million TVs - and more.
Should I have released it with proprietary license instead and charged users for it? It never occured to me, and it wouldn't have worked because I would never had managed to create this kind of stellar project on my own. And projects and companies wouldn't have used it.
Now, why do I and my fellow curl developers still continue to develop curl and give it away for free to the world?
Yes. So insanely much.
But I'm not satisfied with this and I'm not just leaning back, happy with what we've done. I keep working on curl every single day, to improve, to fix bugs, to add features and to make sure curl keeps being the number one file transfer solution for the world even going forward.
We do mistakes along the way. We make the wrong decisions and sometimes we implement things in crazy ways. But to win in the end and to conquer the world is about patience and endurance and constantly going back and reconsidering previous decisions and correcting previous mistakes. To continuously iterate, polish off rough edges and gradually improve over time.
Never give in. Never stop. Fix bugs. Add features. Iterate. To the end of time.
Yeah. For real.
Sure I get tired at times. Working on something every day for over twenty years isn't a paved downhill road. Sometimes there are obstacles. During times things are rough. Occasionally people are just as ugly and annoying as people can be.
But curl is my life's project and I have patience. I have thick skin and I don't give up easily. The tough times pass and most days are awesome. I get to hang out with awesome people and the reward is knowing that my code helps driving the Internet revolution everywhere is an ego boost above normal.
curl will never be "done" and so far I think work on curl is pretty much the most fun I can imagine. Yes, I still think so even after twenty years in the driver's seat. And as long as I think it's fun I intend to keep at it.
Go to this link
Download version tar.gz for windows and just extract files to the folder by your needs. On the left pane, you can select which version of openjdk to download
Tutorial: unzip as expected. You need to set system variable PATH to include your directory with openjdk so you can type java -version in console.
Pure Bash, without an extra process:
for (( COUNTER=0; COUNTER<=10; COUNTER+=2 )); do
echo $COUNTER
done
ArrayList<Integer> a = new ArrayList<Number>();
Does not work because the fact that Number is a super class of Integer does not mean that List<Number>
is a super class of List<Integer>
. Generics are removed during compilation and do not exist on runtime, so parent-child relationship of collections cannot be be implemented: the information about element type is simply removed.
ArrayList<? extends Object> a1 = new ArrayList<Object>();
a1.add(3);
I cannot explain why it does not work. It is really strange but it is a fact. Really syntax <? extends Object>
is mostly used for return values of methods. Even in this example Object o = a1.get(0)
is valid.
ArrayList<?> a = new ArrayList<?>()
This does not work because you cannot instantiate list of unknown type...
What about something like this, without a button:
<input type="text" placeholder="Search..." [value]="searchValue" onblur="this.value=''">
You use mysql_real_escape_string() in code similar to the following one.
$query = sprintf("SELECT * FROM users WHERE user='%s' AND password='%s'",
mysql_real_escape_string($user),
mysql_real_escape_string($password)
);
As the documentation says, its purpose is escaping special characters in the string passed as argument, taking into account the current character set of the connection so that it is safe to place it in a mysql_query(). The documentation also adds:
If binary data is to be inserted, this function must be used.
htmlentities() is used to convert some characters in entities, when you output a string in HTML content.
You can use the following library:
https://github.com/pnowy/NativeCriteria
The library is built on the top of the Hibernate "create sql query" so it supports all databases supported by Hibernate (the Hibernate session and JPA providers are supported). The builder patter is available and so on (object mappers, result mappers).
You can find the examples on github page, the library is available at Maven central of course.
NativeCriteria c = new NativeCriteria(new HibernateQueryProvider(hibernateSession), "table_name", "alias");
c.addJoin(NativeExps.innerJoin("table_name_to_join", "alias2", "alias.left_column", "alias2.right_column"));
c.setProjection(NativeExps.projection().addProjection(Lists.newArrayList("alias.table_column","alias2.table_column")));
Spotlight.js is a great library for iterating over the window object and other host objects looking for certain things.
// find all "length" properties
spotlight.byName('length');
// or find all "map" properties on jQuery
spotlight.byName('map', { 'object': jQuery, 'path': '$' });
// or all properties with `RegExp` values
spotlight.byKind('RegExp');
// or all properties containing "oo" in their name
spotlight.custom(function(value, key) { return key.indexOf('oo') > -1; });
You'll like it for this.
I had similar issue when connecting to RDS Oracle even when client and server were both set to TLSv1.2 the certs was right and java was 1.8.0_141 So Finally I had to apply patch at Java Cryptography Extension (JCE) Unlimited Strength Jurisdiction Policy Files
After applying the patch the issue went away and connection went fine.
Try :
Msg * "insert your message here"
If you are using Windows XP's command.com, this will open a message box.
Opening a new cmd window isn't quite what you were asking for, I gather. You could also use VBScript, and use this with your .bat file. You would open it from the bat file with this command:
cd C:\"location of vbscript"
What this does is change the directory command.com will search for files from, then on the next line:
"insert name of your vbscript here".vbs
Then you create a new Notepad document, type in
<script type="text/vbscript">
MsgBox "your text here"
</script>
You would then save this as a .vbs file (by putting ".vbs" at the end of the filename), save as "All Files" in the drop down box below the file name (so it doesn't save as .txt), then click Save!
The answer depends on what kind of groups you want to retrieve. The System.DirectoryServices.AccountManagement
namespace provides two group retrieval methods:
GetGroups - Returns a collection of group objects that specify the groups of which the current principal is a member.
This overloaded method only returns the groups of which the principal is directly a member; no recursive searches are performed.
GetAuthorizationGroups - Returns a collection of principal objects that contains all the authorization groups of which this user is a member. This function only returns groups that are security groups; distribution groups are not returned.
This method searches all groups recursively and returns the groups in which the user is a member. The returned set may also include additional groups that system would consider the user a member of for authorization purposes.
So GetGroups
gets all groups of which the user is a direct member, and GetAuthorizationGroups
gets all authorization groups of which the user is a direct or indirect member.
Despite the way they are named, one is not a subset of the other. There may be groups returned by GetGroups
not returned by GetAuthorizationGroups
, and vice versa.
Here's a usage example:
PrincipalContext domainContext = new PrincipalContext(ContextType.Domain, "MyDomain", "OU=AllUsers,DC=MyDomain,DC=Local");
UserPrincipal inputUser = new UserPrincipal(domainContext);
inputUser.SamAccountName = "bsmith";
PrincipalSearcher adSearcher = new PrincipalSearcher(inputUser);
inputUser = (UserPrincipal)adSearcher.FindAll().ElementAt(0);
var userGroups = inputUser.GetGroups();
If you're looking for the simplest way to check for a database object's existence before removing it, here's one way (example uses a SPROC, just like your example above but could be modified for tables, indexes, etc...):
IF (OBJECT_ID('MyProcedure') IS NOT NULL)
DROP PROCEDURE MyProcedure
GO
This is quick and elegant, but you need to make sure you have unique object names across all object types since it does not take that into account.
I Hope this helps!
IDs are unique. Classes aren't. Elements can also have multiple classes. Also classes can be dynamically added and removed to an element.
Anywhere you can use an ID you could use a class instead. The reverse is not true.
The convention seems to be to use IDs for page elements that are on every page (like "navbar" or "menu") and classes for everything else but this is only convention and you'll find wide variance in usage.
One other difference is that for form input elements, the <label>
element references a field by ID so you need to use IDs if you're going to use <label>
. is an accessibility thing and you really should use it.
In years gone by IDs were also preferred because they're easily accessible in Javascript (getElementById). With the advent of jQuery and other Javascript frameworks this is pretty much a non-issue now.
Way back when the same issue happened with me.
Dependency was there for ejs in JSON file, tried installing it locally and globally but did not work.
Then what I did was manually adding the module by:
app.set('view engine','ejs');
app.engine('ejs', require('ejs').__express);
Then it works.
This is the shortest way you can do that
list.push($('<li>', {text: blocks[i] }));
$('ul').append(list);
Where blocks in an array. and you need to loop through the array.
requirements.txt
allows the following ways of specifying a dependency on a package in a git repository as of pip 7.0:1
[-e] git+git://git.myproject.org/SomeProject#egg=SomeProject
[-e] git+https://git.myproject.org/SomeProject#egg=SomeProject
[-e] git+ssh://git.myproject.org/SomeProject#egg=SomeProject
-e [email protected]:SomeProject#egg=SomeProject (deprecated as of Jan 2020)
For Github that means you can do (notice the omitted -e
):
git+git://github.com/mozilla/elasticutils.git#egg=elasticutils
Why the extra answer?
I got somewhat confused by the -e
flag in the other answers so here's my clarification:
The -e
or --editable
flag means that the package is installed in <venv path>/src/SomeProject
and thus not in the deeply buried <venv path>/lib/pythonX.X/site-packages/SomeProject
it would otherwise be placed in.2
Documentation
The default RatingBar widget is sorta' lame.
The source makes reference to style "?android:attr/ratingBarStyleIndicator
" in addition to the "?android:attr/ratingBarStyleSmall
" that you're already familiar with. ratingBarStyleIndicator
is slightly smaller but it's still pretty ugly and the comments note that these styles "don't support interaction".
You're probably better-off rolling your own. There's a decent-looking guide at http://kozyr.zydako.net/2010/05/23/pretty-ratingbar/ showing how to do this. (I haven't done it myself yet, but will be attempting in a day or so.)
Good luck!
p.s. Sorry, was going to post a link to the source for you to poke around in but I'm a new user and can't post more than 1 URL. If you dig your way through the source tree, it's located at frameworks/base/core/java/android/widget/RatingBar.java
Here's a working example in which the execution of the service is started in the OnTimedEvent of the Timer which is implemented as delegate in the ServiceBase class and the Timer logic is encapsulated in a method called SetupProcessingTimer():
public partial class MyServiceProject: ServiceBase
{
private Timer _timer;
public MyServiceProject()
{
InitializeComponent();
}
private void SetupProcessingTimer()
{
_timer = new Timer();
_timer.AutoReset = true;
double interval = Settings.Default.Interval;
_timer.Interval = interval * 60000;
_timer.Enabled = true;
_timer.Elapsed += new ElapsedEventHandler(OnTimedEvent);
}
private void OnTimedEvent(object source, ElapsedEventArgs e)
{
// begin your service work
MakeSomething();
}
protected override void OnStart(string[] args)
{
SetupProcessingTimer();
}
...
}
The Interval is defined in app.config in minutes:
<userSettings>
<MyProject.Properties.Settings>
<setting name="Interval" serializeAs="String">
<value>1</value>
</setting>
</MyProject.Properties.Settings>
</userSettings>
VB
Dim arr() As String = {"ravi", "Kumar", "Ravi", "Ramesh"}
Dim result = arr.Where(Function(a) a.Contains("ra")).Select(Function(s) Array.IndexOf(arr, s)).ToArray()
C#
string[] arr = { "ravi", "Kumar", "Ravi", "Ramesh" };
var result = arr.Where(a => a.Contains("Ra")).Select(a => Array.IndexOf(arr, a)).ToArray();
-----Detailed------
Module Module1
Sub Main()
Dim arr() As String = {"ravi", "Kumar", "Ravi", "Ramesh"}
Dim searchStr = "ra"
'Not case sensitive - checks if item starts with searchStr
Dim result1 = arr.Where(Function(a) a.ToLower.StartsWith(searchStr)).Select(Function(s) Array.IndexOf(arr, s)).ToArray
'Case sensitive - checks if item starts with searchStr
Dim result2 = arr.Where(Function(a) a.StartsWith(searchStr)).Select(Function(s) Array.IndexOf(arr, s)).ToArray
'Not case sensitive - checks if item contains searchStr
Dim result3 = arr.Where(Function(a) a.ToLower.Contains(searchStr)).Select(Function(s) Array.IndexOf(arr, s)).ToArray
Stop
End Sub
End Module
Do not use [^\w\s]
, this will remove letters with accents (like àèéìòù), not to mention to Cyrillic or Chinese, letters coming from such languages will be completed removed.
You really don't want remove these letters together with all the special characters. You have two chances:
[^èéòàùì\w\s]
.\p{...}
syntax.var str = "????::: résd,$%& adùf"
var search = XRegExp('([^?<first>\\pL ]+)');
var res = XRegExp.replace(str, search, '',"all");
console.log(res); // returns "????::: resd,adf"
console.log(str.replace(/[^\w\s]/gi, '') ); // returns " rsd adf"
console.log(str.replace(/[^\wèéòàùì\s]/gi, '') ); // returns " résd adùf"
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/xregexp/3.1.1/xregexp-all.js"></script>
_x000D_
There are many solutions to this, some more convenient than others, and they don't always work.
Here's all you can try, going from 'quick' to 'annoying':
File
-> Invalidate Caches / Restart
and restart PyCharm.
Run
-> Edit Configurations
-> Configuration
-> Python Interpreter
.File
-> Settings
Project: [name]
-> Project Interpreter
-> 'Project Interpreter': Gear icon -> More...
File
-> Settings
Project: [name]
-> Project Interpreter
-> 'Project Interpreter': Gear icon -> More...
.idea
folder~/.PyCharm50
on Mac%homepath%/.PyCharm50
on WindowsIf you are using Docker, take note:
pip3
not pip
, especially with remote docker and docker-compose interpreters.PYTHONPATH
. More info here: https://intellij-support.jetbrains.com/hc/en-us/community/posts/115000058690-Module-not-found-in-PyCharm-but-externally-in-Python .SELECT column_name, COUNT(column_name)
FROM table_name
GROUP BY column_name
$('#thisElement').find('.classToSelect')
will find any descendents of #thisElement
with class classToSelect
.
To add to the previous answers, and address some of the discussions around nulls and NPE I'm using Guava Optionals to handle absent/invalid cases. This works great for URI/parameter parsing.
public enum E {
A,B,C;
public static Optional<E> fromString(String s) {
try {
return Optional.of(E.valueOf(s.toUpperCase()));
} catch (IllegalArgumentException|NullPointerException e) {
return Optional.absent();
}
}
}
For those not aware, here's some more info on avoiding null with Optional: https://code.google.com/p/guava-libraries/wiki/UsingAndAvoidingNullExplained#Optional
Depending of the editor that you're using there are some shortcuts to comment a block of lines.
Another workaround would be to put your code in an "if (0)" conditional block ;)
If your strings are in Unicode you should use preg_split
with /u
modifier
From comments in php documentation:
function mb_str_split( $string ) {
# Split at all position not after the start: ^
# and not before the end: $
return preg_split('/(?<!^)(?!$)/u', $string );
}
With Spring Boot
its not necessary to have any config file like persistence.xml
. You can configure with annotations
Just configure your DB config for JPA in the
spring.datasource.driverClassName=oracle.jdbc.driver.OracleDriver
spring.datasource.url=jdbc:oracle:thin:@DB...
spring.datasource.username=username
spring.datasource.password=pass
spring.jpa.database-platform=org.hibernate.dialect....
spring.jpa.show-sql=true
Then you can use CrudRepository
provided by Spring where you have standard CRUD
transaction methods. There you can also implement your own SQL's
like JPQL
.
@Transactional
public interface ObjectRepository extends CrudRepository<Object, Long> {
...
}
And if you still need to use the Entity Manager
you can create another class.
public class ObjectRepositoryImpl implements ObjectCustomMethods{
@PersistenceContext
private EntityManager em;
}
This should be in your pom.xml
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.2.5.RELEASE</version>
</parent>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-orm</artifactId>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>4.3.11.Final</version>
</dependency>
</dependencies>
In my case NDK location was the issue.
go to File->Project Structure->SDK Location
and add NDK location
calling import setuptools
will monkey patch distutils to force compatibility with Visual Studio. Calling vcvars32.bat
manually will setup the virtual environment and prevent other common errors the compiler will throw. For VS 2017 the file is located at
"C:\Program Files (x86)\Microsoft Visual Studio\2017\Community\VC\Auxiliary\Build\vcvars32.bat"
Here is the setup script I use to quickly compile .pyx files to .pyd: (Note: it uses the 3rd party module send2trash
# cython_setup.py
import sys, os, time, platform, subprocess
from setuptools import setup, find_packages
from Cython.Build import cythonize
from traceback import format_exc
# USAGE:
#
# from cython_setup import run
# run(pyx_path)
# vcvars = r"C:\Program Files (x86)\Microsoft Visual Studio\2017\Community\VC\Auxiliary\Build\vcvars32.bat"
# NOTE: to use visual studio 2017 you must have setuptools version 34+
vcvars = r"C:\Program Files (x86)\Microsoft Visual Studio\2017\BuildTools\VC\Auxiliary\Build\vcvars32.bat"
def _build_ext():
try:
pyx_path = sys.argv.pop(-1)
pyx_path = os.path.abspath(pyx_path)
if not os.path.exists(pyx_path):
raise FileNotFoundError(f"{pyx_path} does not exist")
project_name = sys.argv.pop(-1)
os.chdir(os.path.abspath(os.path.dirname(pyx_path)))
print("cwd: %s" % os.getcwd())
print(os.path.abspath("build"))
setup(
name=project_name,
# cmdclass = {'build_ext': build_ext},
packages=find_packages(),
# ext_modules=cythonize(extensions)
ext_modules=cythonize(pyx_path,
compiler_directives={'language_level': 3, 'infer_types': True, 'binding': False},
annotate=True),
# include_dirs = [numpy.get_include()]
build_dir=os.path.abspath("build")
)
except:
input(format_exc())
def retry(func):
def wrapper(*args, **kw):
tries = 0
while True:
try:
return func(*args, **kw)
except Exception:
tries += 1
if tries > 4:
raise
time.sleep(0.4)
return wrapper
@retry
def cleanup(pyx_path):
from send2trash import send2trash
c_file = os.path.splitext(pyx_path)[0] + ".c"
if os.path.exists(c_file):
os.remove(c_file)
if os.path.exists("build"):
send2trash("build")
def move_pyd_files(pyx_path):
pyx_dir = os.path.dirname(pyx_path)
build_dir = os.path.join(pyx_dir, "build")
if not os.path.exists(build_dir):
raise RuntimeError(f"build_dir {build_dir} did not exist....")
found_pyd = False
for top, dirs, nondirs in os.walk(build_dir):
for name in nondirs:
if name.lower().endswith(".pyd") or name.lower().endswith(".so"):
found_pyd = True
old_path = os.path.join(top, name)
new_path = os.path.join(pyx_dir, name)
if os.path.exists(new_path):
print(f"removing {new_path}")
os.remove(new_path)
print(f"file created at {new_path}")
os.rename(old_path, new_path)
if not found_pyd:
raise RuntimeError("Never found .pyd file to move")
def run(pyx_path):
"""
:param pyx_path:
:type pyx_path:
:return: this function creates the batch file, which in turn calls this module, which calls cythonize, once done
the batch script deletes itself... I'm sure theres a less convoluted way of doing this, but it works
:rtype:
"""
try:
project_name = os.path.splitext(os.path.basename(pyx_path))[0]
run_script(project_name, os.path.abspath(pyx_path))
except:
input(format_exc())
def run_script(project_name, pyx_path):
dirname = os.path.dirname(pyx_path)
# ------------------------------
os.chdir(dirname)
if os.path.exists(vcvars):
# raise RuntimeError(
# f"Could not find vcvars32.bat at {vcvars}\nis Visual Studio Installed?\nIs setuptools version > 34?")
subprocess.check_call(f'call "{vcvars}"', shell=True)
cmd = "python" if platform.system() == "Windows" else "python3"
subprocess.check_call(f'{cmd} "{__file__}" build_ext "{project_name}" "{pyx_path}"', shell=True)
move_pyd_files(pyx_path)
cleanup(pyx_path)
if len(sys.argv) > 2:
_build_ext()
select * from table where
(dtColumn between #3/1/2009# and #3/31/2009#) and
(hour(dtColumn) between 6 and 22) and
(weekday(dtColumn, 1) between 2 and 4)
is there a way to disable it?
Yes, you only need to use the JSON_UNESCAPED_SLASHES
flag.
!important read before: https://stackoverflow.com/a/10210367/367456 (know what you're dealing with - know your enemy)
json_encode($str, JSON_UNESCAPED_SLASHES);
If you don't have PHP 5.4 at hand, pick one of the many existing functions and modify them to your needs, e.g. http://snippets.dzone.com/posts/show/7487 (archived copy).
<?php
/*
* Escaping the reverse-solidus character ("/", slash) is optional in JSON.
*
* This can be controlled with the JSON_UNESCAPED_SLASHES flag constant in PHP.
*
* @link http://stackoverflow.com/a/10210433/367456
*/
$url = 'http://www.example.com/';
echo json_encode($url), "\n";
echo json_encode($url, JSON_UNESCAPED_SLASHES), "\n";
Example Output:
"http:\/\/www.example.com\/"
"http://www.example.com/"
For python3 use either with xxxx = name
of yourfile
.
exec(open('./xxxx.py').read())
If you can get a View
in that fragment, you can access the context from there:
view.getContext().startActivity(intent);
I believe I have found a better solution. The idea to change the function to python universal function (see documentation), which can exercise parallel computation under the hood.
One can write his own customised ufunc
in C, which surely is more efficient, or by invoking np.frompyfunc
, which is built-in factory method. After testing, this is more efficient than np.vectorize
:
f = lambda x, y: x * y
f_arr = np.frompyfunc(f, 2, 1)
vf = np.vectorize(f)
arr = np.linspace(0, 1, 10000)
%timeit f_arr(arr, arr) # 307ms
%timeit f_arr(arr, arr) # 450ms
I have also tested larger samples, and the improvement is proportional. For comparison of performances of other methods, see this post
The isdigit
method of the str
type returns True
iff the given string is nothing but one or more digits. If it's not, you know the string should be treated as just a string.
I actually ran into this same prob trying to install Scrapy which depends on cryptography being installed first. I'm on Win764-bit with Python 2.7 64-bit installed. @jsonm's answer eventually worked for me, but first I had to Copy C:\Program Files (x86)\Microsoft Visual Studio 9.0\VC\bin\vcvarsx86_amd64.bat
to the x86_amd64
subdir within that bin dir so the vcvarsall.bat
would stop throwing an error saying it was missing the config. If you need to configure env vars for a different setup, be sure to copy to corresponding vcvars bat file to the corresponding subdir or the first command below might not work.
Then I ran the following from a commandline as per @jsonm's instructions (tweaked for my config)...
C:\> "C:\Program Files (x86)\Microsoft Visual Studio 9.0\VC\vcvarsall.bat" x86_amd64
C:\> set LIB=C:\OpenSSL-Win64\lib;%LIB%
C:\> set INCLUDE=C:\OpenSSL-Win64\include;%INCLUDE%
C:\> pip install cryptography
And it worked.
Essentially console.log()
allows you to output variables in your javascript debugger of choice instead of flashing an alert()
every time you want to inspect something... additionally, for more complex objects it will give you a tree view to inspect the object further instead of having to convert elements to strings like an alert()
.
In SQL Server 2016 the wizard is a separate app. (Important: Excel wizard is only available in the 32-bit version of the wizard!). Use the MSDN page for instructions:
On the Start menu, point to All Programs, point toMicrosoft SQL Server , and then click Import and Export Data.
—or—
In SQL Server Data Tools (SSDT), right-click the SSIS Packages folder, and then click SSIS Import and Export Wizard.
—or—
In SQL Server Data Tools (SSDT), on the Project menu, click SSIS Import and Export Wizard.
—or—
In SQL Server Management Studio, connect to the Database Engine server type, expand Databases, right-click a database, point to Tasks, and then click Import Data or Export data.
—or—
In a command prompt window, run DTSWizard.exe, located in C:\Program Files\Microsoft SQL Server\100\DTS\Binn.
After that it should be pretty much the same (possibly with minor variations in the UI) as in @marc_s's answer.
This worked for me!
App/build.gradle
//Add this....Keep both version same
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
function pink(){ document.body.style.background = "pink"; }
function sky(){ document.body.style.background = "skyblue"; }
_x000D_
<p onclick="pink()" style="padding:10px;background:pink">Pink</p>
<p onclick="sky()" style="padding:10px;background:skyblue">Sky</p>
_x000D_
Without For loop:
Dim newColumn As New Data.DataColumn("Foo", GetType(System.String))
newColumn.DefaultValue = "Your DropDownList value"
table.Columns.Add(newColumn)
C#:
System.Data.DataColumn newColumn = new System.Data.DataColumn("Foo", typeof(System.String));
newColumn.DefaultValue = "Your DropDownList value";
table.Columns.Add(newColumn);
If i am understanding your question. You now have both VMs on the same network segment VMnet8,
Thanks
Example for you to work from
HTML:
<input type="text" value="This is some text" id="text" style="width: 150px;" />
<br />
<input type="button" value="Click Me" id="button" />?
jQuery:
<script type="text/javascript">
$(function () {
$('#button').on('click', function () {
var text = $('#text');
text.val(text.val() + ' after clicking');
});
});
<script>
Javascript
<script type="text/javascript">
document.getElementById("button").addEventListener('click', function () {
var text = document.getElementById('text');
text.value += ' after clicking';
});
</script>
Working jQuery example: http://jsfiddle.net/geMtZ/ ?
If you don't want something complicated, then:
import warnings
warnings.filterwarnings("ignore", category=FutureWarning)
I think your problem is that the margin should be specified in the border tag and not in the grid.
The error should be with the params. Please verify that the params is a dictionary object. If it is just a list/tuple of arguments use only one * (*params
) instead of two * (**params
). This will explode the list/tuple into the proper amount of arguments.
Or, if the params is coming from some other part of code as a JSON file, please do json.loads(params)
, because the JSON objects sometimes behave as string and so you need to make it as a JSON using load from string (loads).
super(HStoreDictionary, self).__init__(value, **params)
Hope this helps!
In short, no, you can't.
Long answer, extension methods are just syntactic sugar. IE:
If you have an extension method on string let's say:
public static string SomeStringExtension(this string s)
{
//whatever..
}
When you then call it:
myString.SomeStringExtension();
The compiler just turns it into:
ExtensionClass.SomeStringExtension(myString);
So as you can see, there's no way to do that for static methods.
And another thing just dawned on me: what would really be the point of being able to add static methods on existing classes? You can just have your own helper class that does the same thing, so what's really the benefit in being able to do:
Bool.Parse(..)
vs.
Helper.ParseBool(..);
Doesn't really bring much to the table...
Since IPv4 addresses are 4 byte long, you could use an INT
(UNSIGNED
) that has exactly 4 bytes:
`ipv4` INT UNSIGNED
And INET_ATON
and INET_NTOA
to convert them:
INSERT INTO `table` (`ipv4`) VALUES (INET_ATON("127.0.0.1"));
SELECT INET_NTOA(`ipv4`) FROM `table`;
For IPv6 addresses you could use a BINARY
instead:
`ipv6` BINARY(16)
And use PHP’s inet_pton
and inet_ntop
for conversion:
'INSERT INTO `table` (`ipv6`) VALUES ("'.mysqli_real_escape_string(inet_pton('2001:4860:a005::68')).'")'
'SELECT `ipv6` FROM `table`'
$ipv6 = inet_pton($row['ipv6']);
I had the exact same problem, this - "meta http-equiv="X-UA-Compatible" content="IE=7">" works great in IE8 and IE9, but not in IE10. There is a bug in the server browser definition files that shipped with .NET 2.0 and .NET 4, namely that they contain definitions for a certain range of browser versions. But the versions for some browsers (like IE 10) aren't within those ranges any more. Therefore, ASP.NET sees them as unknown browsers and defaults to a down-level definition, which has certain inconveniences, like that it does not support features like JavaScript.
My thanks to Scott Hanselman for this fix.
Here is the link -
This MS KP fix just adds missing files to the asp.net on your server. I installed it and rebooted my server and it now works perfectly. I would have thought that MS would have given this fix a wider distribution.
Rick
Unfortunately, there's no exit two levels of for
statement, but there are a few workarounds to do what you want:
Goto. In general, using goto
is considered to be bad practice (and rightfully so), but using goto
solely for a forward jump out of structured control statements is usually considered to be OK, especially if the alternative is to have more complicated code.
For Each item In itemList
For Each item1 In itemList1
If item1.Text = "bla bla bla" Then
Goto end_of_for
End If
Next
Next
end_of_for:
Dummy outer block
Do
For Each item In itemList
For Each item1 In itemList1
If item1.Text = "bla bla bla" Then
Exit Do
End If
Next
Next
Loop While False
or
Try
For Each item In itemlist
For Each item1 In itemlist1
If item1 = "bla bla bla" Then
Exit Try
End If
Next
Next
Finally
End Try
Separate function: Put the loops inside a separate function, which can be exited with return
. This might require you to pass a lot of parameters, though, depending on how many local variables you use inside the loop. An alternative would be to put the block into a multi-line lambda, since this will create a closure over the local variables.
Boolean variable: This might make your code a bit less readable, depending on how many layers of nested loops you have:
Dim done = False
For Each item In itemList
For Each item1 In itemList1
If item1.Text = "bla bla bla" Then
done = True
Exit For
End If
Next
If done Then Exit For
Next
Another option is to use the Aggregate extension rather than Join:
String s = myDict.Select(x => x.Key + "=" + x.Value).Aggregate((s1, s2) => s1 + ";" + s2);
Assuming the submodule's repository does contain a commit you want to use (unlike the commit that is referenced from current state of the super-project), there are two ways to do it.
The first requires you to already know the commit from the submodule that you want to use. It works from the “inside, out” by directly adjusting the submodule then updating the super-project. The second works from the “outside, in” by finding the super-project's commit that modified the submodule and then reseting the super-project's index to refer to a different submodule commit.
If you already know which commit you want the submodule to use, cd
to the submodule, check out the commit you want, then git add
and git commit
it back in the super-project.
Example:
$ git submodule update
fatal: reference is not a tree: e47c0a16d5909d8cb3db47c81896b8b885ae1556
Unable to checkout 'e47c0a16d5909d8cb3db47c81896b8b885ae1556' in submodule path 'sub'
Oops, someone made a super-project commit that refers to an unpublished commit in the submodule sub
. Somehow, we already know that we want the submodule to be at commit 5d5a3ee314476701a20f2c6ec4a53f88d651df6c
. Go there and check it out directly.
$ cd sub
$ git checkout 5d5a3ee314476701a20f2c6ec4a53f88d651df6c
Note: moving to '5d5a3ee314476701a20f2c6ec4a53f88d651df6c' which isn't a local branch
If you want to create a new branch from this checkout, you may do so
(now or later) by using -b with the checkout command again. Example:
git checkout -b <new_branch_name>
HEAD is now at 5d5a3ee... quux
$ cd ..
Since we are checking out a commit, this produces a detached HEAD in the submodule. If you want to make sure that the submodule is using a branch, then use git checkout -b newbranch <commit>
to create and checkout a branch at the commit or checkout the branch that you want (e.g. one with the desired commit at the tip).
A checkout in the submodule is reflected in the super-project as a change to the working tree. So we need to stage the change in the super-project's index and verify the results.
$ git add sub
$ git submodule update
$ git diff
$ git diff --cached
diff --git c/sub i/sub
index e47c0a1..5d5a3ee 160000
--- c/sub
+++ i/sub
@@ -1 +1 @@
-Subproject commit e47c0a16d5909d8cb3db47c81896b8b885ae1556
+Subproject commit 5d5a3ee314476701a20f2c6ec4a53f88d651df6c
The submodule update was silent because the submodule is already at the specified commit. The first diff shows that the index and worktree are the same. The third diff shows that the only staged change is moving the sub
submodule to a different commit.
git commit
This commits the fixed-up submodule entry.
If you are not sure which commit you should use from the submodule, you can look at the history in the superproject to guide you. You can also manage the reset directly from the super-project.
$ git submodule update
fatal: reference is not a tree: e47c0a16d5909d8cb3db47c81896b8b885ae1556
Unable to checkout 'e47c0a16d5909d8cb3db47c81896b8b885ae1556' in submodule path 'sub'
This is the same situation as above. But this time we will focus on fixing it from the super-project instead of dipping into the submodule.
$ git log --oneline -p -- sub
ce5d37c local change in sub
diff --git a/sub b/sub
index 5d5a3ee..e47c0a1 160000
--- a/sub
+++ b/sub
@@ -1 +1 @@
-Subproject commit 5d5a3ee314476701a20f2c6ec4a53f88d651df6c
+Subproject commit e47c0a16d5909d8cb3db47c81896b8b885ae1556
bca4663 added sub
diff --git a/sub b/sub
new file mode 160000
index 0000000..5d5a3ee
--- /dev/null
+++ b/sub
@@ -0,0 +1 @@
+Subproject commit 5d5a3ee314476701a20f2c6ec4a53f88d651df6c
OK, it looks like it went bad in ce5d37c
, so we will restore the submodule from its parent (ce5d37c~
).
Alternatively, you can take the submodule's commit from the patch text (5d5a3ee314476701a20f2c6ec4a53f88d651df6c
) and use the above “inside, out” process instead.
$ git checkout ce5d37c~ -- sub
This reset the submodule entry for sub
to what it was at commit ce5d37c~
in the super-project.
$ git submodule update
Submodule path 'sub': checked out '5d5a3ee314476701a20f2c6ec4a53f88d651df6c'
The submodule update went OK (it indicates a detached HEAD).
$ git diff ce5d37c~ -- sub
$ git diff
$ git diff --cached
diff --git c/sub i/sub
index e47c0a1..5d5a3ee 160000
--- c/sub
+++ i/sub
@@ -1 +1 @@
-Subproject commit e47c0a16d5909d8cb3db47c81896b8b885ae1556
+Subproject commit 5d5a3ee314476701a20f2c6ec4a53f88d651df6c
The first diff shows that sub
is now the same in ce5d37c~
. The second diff shows that the index and worktree are the same. The third diff shows the only staged change is moving the sub
submodule to a different commit.
git commit
This commits the fixed-up submodule entry.
Based in the answer of @DanielQ
Swift 4 and Swift 3
import UIKit
extension UIImageView {
func setRounded() {
self.layer.cornerRadius = (self.frame.width / 2) //instead of let radius = CGRectGetWidth(self.frame) / 2
self.layer.masksToBounds = true
}
}
You can use it in any ViewController
with:
imageView.setRounded()
CASE might help you out:
SELECT t.first_name,
t.last_name,
t.employid,
t.status
FROM employeetable t
WHERE t.status = (CASE WHEN status_flag = STATUS_ACTIVE THEN 'A'
WHEN status_flag = STATUS_INACTIVE THEN 'T'
ELSE null END)
AND t.business_unit = (CASE WHEN source_flag = SOURCE_FUNCTION THEN 'production'
WHEN source_flag = SOURCE_USER THEN 'users'
ELSE null END)
AND t.first_name LIKE firstname
AND t.last_name LIKE lastname
AND t.employid LIKE employeeid;
The CASE statement evaluates multiple conditions to produce a single value. So, in the first usage, I check the value of status_flag, returning 'A', 'T' or null depending on what it's value is, and compare that to t.status. I do the same for the business_unit column with a second CASE statement.
You can use axe selectors for this.
There are two approaches:
<
)#a:hover < #content + #b
This axe style rule will select #b
, which is the immediate sibling of #content
, which is the immediate parent of #a
which has a :hover
state.
div {
display: inline-block;
margin: 30px;
font-weight: bold;
}
#content {
width: 160px;
height: 160px;
background-color: rgb(255, 0, 0);
}
#a, #b {
width: 100px;
height: 100px;
line-height: 100px;
text-align: center;
}
#a {
color: rgb(255, 0, 0);
background-color: rgb(255, 255, 0);
cursor: pointer;
}
#b {
display: none;
color: rgb(255, 255, 255);
background-color: rgb(0, 0, 255);
}
#a:hover < #content + #b {
display: inline-block;
}
_x000D_
<div id="content">
<div id="a">Hover me</div>
</div>
<div id="b">Show me</div>
<script src="https://rouninmedia.github.io/axe/axe.js"></script>
_x000D_
\
)#a:hover \ #b
This axe style rule will select #b
, which is present in the same document as #a
which has a :hover
state.
div {
display: inline-block;
margin: 30px;
font-weight: bold;
}
#content {
width: 160px;
height: 160px;
background-color: rgb(255, 0, 0);
}
#a, #b {
width: 100px;
height: 100px;
line-height: 100px;
text-align: center;
}
#a {
color: rgb(255, 0, 0);
background-color: rgb(255, 255, 0);
cursor: pointer;
}
#b {
display: none;
color: rgb(255, 255, 255);
background-color: rgb(0, 0, 255);
}
#a:hover \ #b {
display: inline-block;
}
_x000D_
<div id="content">
<div id="a">Hover me</div>
</div>
<div id="b">Show me</div>
<script src="https://rouninmedia.github.io/axe/axe.js"></script>
_x000D_
This is lighter weight than xrange
(and the while loop) since it doesn't even need to create the int
objects. It also works equally well in Python2 and Python3
from itertools import repeat
for i in repeat(None, 10):
do_sth()
ax.set_title('My Title\n', fontsize="15", color="red")
plt.imshow(myfile, origin="upper")
If you put '\n'
right after your title string, the plot is drawn just below the title. That might be a fast solution too.
create new style in styles.xml
<style name="myDialog" parent="android:style/Theme.Dialog">
<item name="android:windowNoTitle">true</item>
</style>
then add this to your manifest:
<activity android:name=".youractivity" android:theme="@style/myDialog"></activity>
If your data contains any newlines or commas, you will need to escape those first:
const escape = text =>
text.replace(/\\/g, "\\\\")
.replace(/\n/g, "\\n")
.replace(/,/g, "\\,")
escaped_array = test_array.map(fields => fields.map(escape))
Then simply do:
csv = escaped_array.map(fields => fields.join(","))
.join("\n")
If you want to make it downloadable in-browser:
dl = "data:text/csv;charset=utf-8," + csv
window.open(encodeURI(dl))
IN completion to above answers, you can also customize your fallbacks for each async call you do, so that each call to the generic ASYNC method will populate different data, depending on the onTaskDone stuff you put there.
Main.FragmentCallback FC= new Main.FragmentCallback(){
@Override
public void onTaskDone(String results) {
localText.setText(results); //example TextView
}
};
new API_CALL(this.getApplicationContext(), "GET",FC).execute("&Books=" + Main.Books + "&args=" + profile_id);
Remind: I used interface on the main activity thats where "Main" comes, like this:
public interface FragmentCallback {
public void onTaskDone(String results);
}
My API post execute looks like this:
@Override
protected void onPostExecute(String results) {
Log.i("TASK Result", results);
mFragmentCallback.onTaskDone(results);
}
The API constructor looks like this:
class API_CALL extends AsyncTask<String,Void,String> {
private Main.FragmentCallback mFragmentCallback;
private Context act;
private String method;
public API_CALL(Context ctx, String api_method,Main.FragmentCallback fragmentCallback) {
act=ctx;
method=api_method;
mFragmentCallback = fragmentCallback;
}
Just my alternative, short and clean:
/**
* @param int $bytes Number of bytes (eg. 25907)
* @param int $precision [optional] Number of digits after the decimal point (eg. 1)
* @return string Value converted with unit (eg. 25.3KB)
*/
function formatBytes($bytes, $precision = 2) {
$unit = ["B", "KB", "MB", "GB"];
$exp = floor(log($bytes, 1024)) | 0;
return round($bytes / (pow(1024, $exp)), $precision).$unit[$exp];
}
or, more stupid and efficent:
function formatBytes($bytes, $precision = 2) {
if ($bytes > pow(1024,3)) return round($bytes / pow(1024,3), $precision)."GB";
else if ($bytes > pow(1024,2)) return round($bytes / pow(1024,2), $precision)."MB";
else if ($bytes > 1024) return round($bytes / 1024, $precision)."KB";
else return ($bytes)."B";
}
>>> 'QH QD JC KD JS'.split()
['QH', 'QD', 'JC', 'KD', 'JS']
Return a list of the words in the string, using
sep
as the delimiter string. Ifmaxsplit
is given, at mostmaxsplit
splits are done (thus, the list will have at mostmaxsplit+1
elements). Ifmaxsplit
is not specified, then there is no limit on the number of splits (all possible splits are made).If
sep
is given, consecutive delimiters are not grouped together and are deemed to delimit empty strings (for example,'1,,2'.split(',')
returns['1', '', '2']
). Thesep
argument may consist of multiple characters (for example,'1<>2<>3'.split('<>')
returns['1', '2', '3']
). Splitting an empty string with a specified separator returns['']
.If
sep
is not specified or isNone
, a different splitting algorithm is applied: runs of consecutive whitespace are regarded as a single separator, and the result will contain no empty strings at the start or end if the string has leading or trailing whitespace. Consequently, splitting an empty string or a string consisting of just whitespace with aNone
separator returns[]
.For example,
' 1 2 3 '.split()
returns['1', '2', '3']
, and' 1 2 3 '.split(None, 1)
returns['1', '2 3 ']
.
jQuery can handle JSONP, just pass an url formatted with the callback=? parameter to the $.getJSON
method, for example:
$.getJSON("https://api.ipify.org/?format=json", function(e) {_x000D_
console.log(e.ip);_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
_x000D_
This example is of a really simple JSONP service implemented on with api.ipify.org
.
If you aren't looking for a cross-domain solution the script can be simplified even more, since you don't need the callback parameter, and you return pure JSON.
A straight forward template filter for this problem. The built-in function int() never rounds up. F-Strings (i.e. f'') require python 3.6.
@app_template_filter()
def diffTime(end, start):
diff = (end - start).total_seconds()
d = int(diff / 86400)
h = int((diff - (d * 86400)) / 3600)
m = int((diff - (d * 86400 + h * 3600)) / 60)
s = int((diff - (d * 86400 + h * 3600 + m *60)))
if d > 0:
fdiff = f'{d}d {h}h {m}m {s}s'
elif h > 0:
fdiff = f'{h}h {m}m {s}s'
elif m > 0:
fdiff = f'{m}m {s}s'
else:
fdiff = f'{s}s'
return fdiff
in jquery we have to use selector($) to declare variables
var test=$("<%=ddl.ClientId%>");
here we can get the id of drop down to j query variable
Postman will query Google API impersonating a Web Application
Generate an OAuth 2.0 token:
Create an OAuth 2.0 client ID
getpostman.com
to the Authorized domains. Click Save.https://www.getpostman.com/oauth2/callback
Client ID
and Client secret
fields for later useIn Postman select Authorization tab and select "OAuth 2.0" type. Click 'Get New Access Token'
https://www.getpostman.com/oauth2/callback
https://accounts.google.com/o/oauth2/auth
https://accounts.google.com/o/oauth2/token
Client ID
generated in the step 2 (e.g., '123456789012-abracadabra1234546789blablabla12.apps.googleusercontent.com')Client secret
generated in the step 2 (e.g., 'ABRACADABRAus1ZMGHvq9R-L')You can use async/await
for this. I would explain more, but there's nothing really to it. It's just a regular for
loop but I added the await
keyword before the construction of your Promise
What I like about this is your Promise can resolve a normal value instead of having a side effect like your code (or other answers here) include. This gives you powers like in The Legend of Zelda: A Link to the Past where you can affect things in both the Light World and the Dark World – ie, you can easily work with data before/after the Promised data is available without having to resort to deeply nested functions, other unwieldy control structures, or stupid IIFEs.
// where DarkWorld is in the scary, unknown future
// where LightWorld is the world we saved from Ganondorf
LightWorld ... await DarkWorld
So here's what that will look like ...
const someProcedure = async n =>_x000D_
{_x000D_
for (let i = 0; i < n; i++) {_x000D_
const t = Math.random() * 1000_x000D_
const x = await new Promise(r => setTimeout(r, t, i))_x000D_
console.log (i, x)_x000D_
}_x000D_
return 'done'_x000D_
}_x000D_
_x000D_
someProcedure(10).then(x => console.log(x)) // => Promise_x000D_
// 0 0_x000D_
// 1 1_x000D_
// 2 2_x000D_
// 3 3_x000D_
// 4 4_x000D_
// 5 5_x000D_
// 6 6_x000D_
// 7 7_x000D_
// 8 8_x000D_
// 9 9_x000D_
// done
_x000D_
See how we don't have to deal with that bothersome .then
call within our procedure? And async
keyword will automatically ensure that a Promise
is returned, so we can chain a .then
call on the returned value. This sets us up for great success: run the sequence of n
Promises, then do something important – like display a success/error message.
Swift 3 syntax:
func textFieldDidBeginEditing(_ textField: UITextField) {
// add if for some desired textfields
animateViewMoving(up: true, moveValue: 100)
}
func textFieldDidEndEditing(_ textField: UITextField) {
// add if for some desired textfields
animateViewMoving(up: false, moveValue: 100)
}
func animateViewMoving (up:Bool, moveValue :CGFloat){
textFieldDidEndEditing(_ textField: UITextField) {
let movementDuration:TimeInterval = 0.5
let movement:CGFloat = ( up ? -moveValue : moveValue)
UIView.beginAnimations("animateView", context: nil)
UIView.setAnimationBeginsFromCurrentState(true)
UIView.setAnimationDuration(movementDuration)
self.view.frame = self.view.frame.offsetBy(dx: 0, dy: movement)
UIView.commitAnimations()
}
this is a nice method to get what you want you can add "if" conditions for certain textfields but this type works for all... Hope it can be useful for everyone
I have to give a great deal of credit to Markus Jarderot for his post - the majority of my post is inspired from his.
I found that Markus' answer still fails some of the IPv6 examples in the Perl script referenced by his answer.
Here is my regex that passes all of the examples in that Perl script:
r"""^
\s* # Leading whitespace
# Zero-width lookaheads to reject too many quartets
(?:
# 6 quartets, ending IPv4 address; no wildcards
(?:[0-9a-f]{1,4}(?::(?!:))){6}
(?:25[0-4]|2[0-4]\d|1\d\d|[1-9]\d|\d)
(?:\.(?:25[0-4]|2[0-4]\d|1\d\d|[1-9]\d|\d)){3}
|
# 0-5 quartets, wildcard, ending IPv4 address
(?:(?:[0-9a-f]{1,4}(?::(?!:))){0,4}[0-9a-f]{1,4})?
(?:::(?!:))
(?:25[0-4]|2[0-4]\d|1\d\d|[1-9]\d|\d)
(?:\.(?:25[0-4]|2[0-4]\d|1\d\d|[1-9]\d|\d)){3}
|
# 0-4 quartets, wildcard, 0-1 quartets, ending IPv4 address
(?:(?:[0-9a-f]{1,4}(?::(?!:))){0,3}[0-9a-f]{1,4})?
(?:::(?!:))
(?:[0-9a-f]{1,4}(?::(?!:)))?
(?:25[0-4]|2[0-4]\d|1\d\d|[1-9]\d|\d)
(?:\.(?:25[0-4]|2[0-4]\d|1\d\d|[1-9]\d|\d)){3}
|
# 0-3 quartets, wildcard, 0-2 quartets, ending IPv4 address
(?:(?:[0-9a-f]{1,4}(?::(?!:))){0,2}[0-9a-f]{1,4})?
(?:::(?!:))
(?:[0-9a-f]{1,4}(?::(?!:))){0,2}
(?:25[0-4]|2[0-4]\d|1\d\d|[1-9]\d|\d)
(?:\.(?:25[0-4]|2[0-4]\d|1\d\d|[1-9]\d|\d)){3}
|
# 0-2 quartets, wildcard, 0-3 quartets, ending IPv4 address
(?:(?:[0-9a-f]{1,4}(?::(?!:))){0,1}[0-9a-f]{1,4})?
(?:::(?!:))
(?:[0-9a-f]{1,4}(?::(?!:))){0,3}
(?:25[0-4]|2[0-4]\d|1\d\d|[1-9]\d|\d)
(?:\.(?:25[0-4]|2[0-4]\d|1\d\d|[1-9]\d|\d)){3}
|
# 0-1 quartets, wildcard, 0-4 quartets, ending IPv4 address
(?:[0-9a-f]{1,4}){0,1}
(?:::(?!:))
(?:[0-9a-f]{1,4}(?::(?!:))){0,4}
(?:25[0-4]|2[0-4]\d|1\d\d|[1-9]\d|\d)
(?:\.(?:25[0-4]|2[0-4]\d|1\d\d|[1-9]\d|\d)){3}
|
# wildcard, 0-5 quartets, ending IPv4 address
(?:::(?!:))
(?:[0-9a-f]{1,4}(?::(?!:))){0,5}
(?:25[0-4]|2[0-4]\d|1\d\d|[1-9]\d|\d)
(?:\.(?:25[0-4]|2[0-4]\d|1\d\d|[1-9]\d|\d)){3}
|
# 8 quartets; no wildcards
(?:[0-9a-f]{1,4}(?::(?!:))){7}[0-9a-f]{1,4}
|
# 0-7 quartets, wildcard
(?:(?:[0-9a-f]{1,4}(?::(?!:))){0,6}[0-9a-f]{1,4})?
(?:::(?!:))
|
# 0-6 quartets, wildcard, 0-1 quartets
(?:(?:[0-9a-f]{1,4}(?::(?!:))){0,5}[0-9a-f]{1,4})?
(?:::(?!:))
(?:[0-9a-f]{1,4})?
|
# 0-5 quartets, wildcard, 0-2 quartets
(?:(?:[0-9a-f]{1,4}(?::(?!:))){0,4}[0-9a-f]{1,4})?
(?:::(?!:))
(?:(?:[0-9a-f]{1,4}(?::(?!:))){0,1}[0-9a-f]{1,4})?
|
# 0-4 quartets, wildcard, 0-3 quartets
(?:(?:[0-9a-f]{1,4}(?::(?!:))){0,3}[0-9a-f]{1,4})?
(?:::(?!:))
(?:(?:[0-9a-f]{1,4}(?::(?!:))){0,2}[0-9a-f]{1,4})?
|
# 0-3 quartets, wildcard, 0-4 quartets
(?:(?:[0-9a-f]{1,4}(?::(?!:))){0,2}[0-9a-f]{1,4})?
(?:::(?!:))
(?:(?:[0-9a-f]{1,4}(?::(?!:))){0,3}[0-9a-f]{1,4})?
|
# 0-2 quartets, wildcard, 0-5 quartets
(?:(?:[0-9a-f]{1,4}(?::(?!:))){0,1}[0-9a-f]{1,4})?
(?:::(?!:))
(?:(?:[0-9a-f]{1,4}(?::(?!:))){0,4}[0-9a-f]{1,4})?
|
# 0-1 quartets, wildcard, 0-6 quartets
(?:[0-9a-f]{1,4})?
(?:::(?!:))
(?:(?:[0-9a-f]{1,4}(?::(?!:))){0,5}[0-9a-f]{1,4})?
|
# wildcard, 0-7 quartets
(?:::(?!:))
(?:(?:[0-9a-f]{1,4}(?::(?!:))){0,6}[0-9a-f]{1,4})?
)
(?:/(?:1(?:2[0-7]|[01]\d)|\d\d?))? # With an optional CIDR routing prefix (0-128)
\s* # Trailing whitespace
$"""
I also put together a Python script to test all of those IPv6 examples; it's here on Pastebin because it was too large to post here.
You can run the script with test result and example arguments in the form of "[result]=[example]", so like:
python script.py Fail=::1.2.3.4: pass=::127.0.0.1 false=::: True=::1
or you can simply run all of the tests by specifying no arguments, so like:
python script.py
Anyway, I hope this helps somebody else!
If you have stopped the mongod.exe service from the task manager, you need to restart the service. In my case I stopped the service from task manager and on restart it doesn't automatically started.
Basically it's safe to copy the repository folder if the svn server is stopped. (source: https://groups.google.com/forum/?fromgroups#!topic/visualsvn/i_55khUBrys%5B1-25%5D )
So if you're allowed to stop the server, do it and just copy the repository, either with some script or a backup tool. Cobian Backup fits here nicely as it can stop and start services automatically, and it can do incremental backups so you're only backing up parts of repository that have changed recently (useful if the repository is large and you're backing up to remote location).
Example:
Add a backup task:
Set source to repository folder (e.g. C:\Repositories\
),
Add pre-backup event "STOP_SERVICE"
VisualSVN,
Add post-backup event, "START_SERVICE"
VisualSVN,
Set other options as needed. We've set up incremental backups including removal of old ones, backup schedule, destination, compression incl. archive splitting etc.
Profit!
Do you mean elif
?
VBA subs are no macros. A VBA sub can be a macro, but it is not a must.
The term "macro" is only used for recorded user actions. from these actions a code is generated and stored in a sub. This code is simple and do not provide powerful structures like loops, for example Do .. until, for .. next, while.. do, and others.
The more elegant way is, to design and write your own VBA code without using the macro features!
VBA is a object based and event oriented language. Subs, or bette call it "sub routines", are started by dedicated events. The event can be the pressing of a button or the opening of a workbook and many many other very specific events.
If you focus to VB6 and not to VBA, then you can state, that there is always a main-window or main form. This form is started if you start the compiled executable "xxxx.exe".
In VBA you have nothing like this, but you have a XLSM file wich is started by Excel. You can attach some code to the Workbook_Open event. This event is generated, if you open your desired excel file which is called a workbook. Inside the workbook you have worksheets.
It is useful to get more familiar with the so called object model of excel. The workbook has several events and methods. Also the worksheet has several events and methods.
In the object based model you have objects, that have events and methods. methods are action you can do with a object. events are things that can happen to an object. An objects can contain another objects, and so on. You can create new objects, like sheets or charts.
A possible solution might be to use the JSON dumps() method, so you can convert the dictionary to a string ---
import json
a={"a":10, "b":20}
b={"b":20, "a":10}
c = [json.dumps(a), json.dumps(b)]
set(c)
json.dumps(a) in c
Output -
set(['{"a": 10, "b": 20}'])
True
Any changes you commit, like deleting all your project files, will still be in place after a pull. All a pull does is merge the latest changes from somewhere else into your own branch, and if your branch has deleted everything, then at best you'll get merge conflicts when upstream changes affect files you've deleted. So, in short, yes everything is up to date.
If you describe what outcome you'd like to have instead of "all files deleted", maybe someone can suggest an appropriate course of action.
Update:
GET THE MOST RECENT OF THE CODE ON MY SYSTEM
What you don't seem to understand is that you already have the most recent code, which is yours. If what you really want is to see the most recent of someone else's work that's on the master branch, just do:
git fetch upstream
git checkout upstream/master
Note that this won't leave you in a position to immediately (re)start your own work. If you need to know how to undo something you've done or otherwise revert changes you or someone else have made, then please provide details. Also, consider reading up on what version control is for, since you seem to misunderstand its basic purpose.
Good question. You will need to modify the HTML itself rather than rely on DOM properties.
var opt = $("option[val=ID]"),
html = $("<div>").append(opt.clone()).html();
html = html.replace(/\>/, ' selected="selected">');
opt.replaceWith(html);
The code grabs the option element for Indonesia, clones it and puts it into a new div (not in the document) to retrieve the full HTML string: <option value="ID">Indonesia</option>
.
It then does a string replace to add the attribute selected="selected"
as a string, before replacing the original option with this new one.
I tested it on IE7. See it with the reset button working properly here: http://jsfiddle.net/XmW49/
Copy the python file to /bin:
sudo cp -i /path/to/your_script.py /bin
Add A New Cron Job:
sudo crontab -e
Scroll to the bottom and add the following line (after all the #'s
):
@reboot python /bin/your_script.py &
The “&” at the end of the line means the command is run in the background and it won’t stop the system booting up.
Test it:
sudo reboot
Add this file to your Desktop: test_code.py (run it to check that it works for you)
from os.path import expanduser
import datetime
file = open(expanduser("~") + '/Desktop/HERE.txt', 'w')
file.write("It worked!\n" + str(datetime.datetime.now()))
file.close()
Run the following commands:
sudo cp -i ~/Desktop/test_code.py /bin
sudo crontab -e
Add the following line and save it:
@reboot python /bin/test_code.py &
Now reboot your computer and you should find a new file on your Desktop: HERE.txt
1. Authorization
You have received access data like this:
Username: johndoe
Password: zznAQOoWyj8uuAgq
Consumer Key: ggczWttBWlTjXCEtk3Yie_WJGEIa
Consumer Secret: uuzPjjJykiuuLfHkfgSdXLV98Ciga
Which you can call in cURL like this:
curl -k -d "grant_type=password&username=Username&password=Password" \
-H "Authorization: Basic Base64(consumer-key:consumer-secret)" \
https://somedomain.test.com/token
or for this case it would be:
curl -k -d "grant_type=password&username=johndoe&password=zznAQOoWyj8uuAgq" \
-H "Authorization: Basic zzRjettzNUJXbFRqWENuuGszWWllX1iiR0VJYTpRelBLZkp5a2l2V0xmSGtmZ1NkWExWzzhDaWdh" \
https://somedomain.test.com/token
Answer would be something like:
{
"access_token": "zz8d62zz-56zz-34zz-9zzf-azze1b8057f8",
"refresh_token": "zzazz4c3-zz2e-zz25-zz97-ezz6e219cbf6",
"scope": "default",
"token_type": "Bearer",
"expires_in": 3600
}
2. Calling API
Here is how you call some API that uses authentication from above. Limit
and offset
are just examples of 2 parameters that API could implement.
You need access_token
from above inserted after "Bearer "
.So here is how you call some API with authentication data from above:
curl -k -X GET "https://somedomain.test.com/api/Users/Year/2020/Workers?offset=1&limit=100" -H "accept: application/json" -H "Authorization: Bearer zz8d62zz-56zz-34zz-9zzf-azze1b8057f8"
Same thing from above implemented in Python. I've put text in comments so code could be copy-pasted.
# Authorization data
import base64
import requests
username = 'johndoe'
password= 'zznAQOoWyj8uuAgq'
consumer_key = 'ggczWttBWlTjXCEtk3Yie_WJGEIa'
consumer_secret = 'uuzPjjJykiuuLfHkfgSdXLV98Ciga'
consumer_key_secret = consumer_key+":"+consumer_secret
consumer_key_secret_enc = base64.b64encode(consumer_key_secret.encode()).decode()
# Your decoded key will be something like:
#zzRjettzNUJXbFRqWENuuGszWWllX1iiR0VJYTpRelBLZkp5a2l2V0xmSGtmZ1NkWExWzzhDaWdh
headersAuth = {
'Authorization': 'Basic '+ str(consumer_key_secret_enc),
}
data = {
'grant_type': 'password',
'username': username,
'password': password
}
## Authentication request
response = requests.post('https://somedomain.test.com/token', headers=headersAuth, data=data, verify=True)
j = response.json()
# When you print that response you will get dictionary like this:
{
"access_token": "zz8d62zz-56zz-34zz-9zzf-azze1b8057f8",
"refresh_token": "zzazz4c3-zz2e-zz25-zz97-ezz6e219cbf6",
"scope": "default",
"token_type": "Bearer",
"expires_in": 3600
}
# You have to use `access_token` in API calls explained bellow.
# You can get `access_token` with j['access_token'].
# Using authentication to make API calls
## Define header for making API calls that will hold authentication data
headersAPI = {
'accept': 'application/json',
'Authorization': 'Bearer '+j['access_token'],
}
### Usage of parameters defined in your API
params = (
('offset', '0'),
('limit', '20'),
)
# Making sample API call with authentication and API parameters data
response = requests.get('https://somedomain.test.com/api/Users/Year/2020/Workers', headers=headersAPI, params=params, verify=True)
api_response = response.json()
Started working after adding property:
mail.smtp.starttls.enable=true
Using:
mail.smtp.host=smtp.office365.com
mail.smtp.port=587
mail.transport.protocol=smtp
mail.smtp.auth=true
mail.smtp.starttls.enable=true
[email protected]
mail.smtp.password=xxx
[email protected]
For future googlers (thousands have now googled this question):
To set your mind at ease, the onClick
event does work with divs in react, so double-check your code syntax.
These are right:
<div onClick={doThis}>
<div onClick={() => doThis()}>
These are wrong:
<div onClick={doThis()}>
<div onClick={() => doThis}>
(and don't forget to close your tags... Watch for this:
<div onClick={doThis}
missing closing tag on the div)
For Linux
On the old machine:
code --list-extensions > vscode-extensions.list
On the new machine:
cat vscode-extensions.list | xargs -L 1 code --install-extension
Use this, works for me and solve problems with small screen.
<div class="row">
<!-- (fixed content) JUST VISIBLE IN LG SCREEN -->
<div class="col-lg-3 device-lg visible-lg">
<div class="affix">
fixed position
</div>
</div>
<div class="col-lg-9">
<!-- (fixed content) JUST VISIBLE IN NO LG SCREEN -->
<div class="device-sm visible-sm device-xs visible-xs device-md visible-md ">
<div>
NO fixed position
</div>
</div>
Normal data enter code here
</div>
</div>
Well, you're on the right path, Benno!
There are some tips regarding VBA programming that might help you out.
Use always explicit references to the sheet you want to interact with. Otherwise, Excel may 'assume' your code applies to the active sheet and eventually you'll see it screws your spreadsheet up.
As lionz mentioned, get in touch with the native methods Excel offers. You might use them on most of your tricks.
Explicitly declare your variables... they'll show the list of methods each object offers in VBA. It might save your time digging on the internet.
Now, let's have a draft code...
Remember this code must be within the Excel Sheet object, as explained by lionz. It only applies to Sheet 2, is up to you to adapt it to both Sheet 2 and Sheet 3 in the way you prefer.
Hope it helps!
Private Sub Worksheet_Change(ByVal Target As Range)
Dim oSheet As Excel.Worksheet
'We only want to do something if the changed cell is B6, right?
If Target.Address = "$B$6" Then
'Checks if it's a number...
If IsNumeric(Target.Value) Then
'Let's avoid values out of your bonds, correct?
If Target.Value > 0 And Target.Value < 51 Then
'Let's assign the worksheet we'll show / hide rows to one variable and then
' use only the reference to the variable itself instead of the sheet name.
' It's safer.
'You can alternatively replace 'sheet 2' by 2 (without quotes) which will represent
' the sheet index within the workbook
Set oSheet = ActiveWorkbook.Sheets("Sheet 2")
'We'll unhide before hide, to ensure we hide the correct ones
oSheet.Range("A7:A56").EntireRow.Hidden = False
oSheet.Range("A" & Target.Value + 7 & ":A56").EntireRow.Hidden = True
End If
End If
End If
End Sub
If both the tables have the same schema then use this query: insert into database_name.table_name select * from new_database_name.new_table_name where='condition'
Replace database_name with the name of your 1st database and table_name with the name of table you want to copy from also replace new_database_name with the name of your other database where you wanna copy and new_table_name is the name of the table.
git rev-parse --show-toplevel
could be enough if executed within a git repo.
From git rev-parse
man page:
--show-toplevel
Show the absolute path of the top-level directory.
For older versions (before 1.7.x), the other options are listed in "Is there a way to get the git root directory in one command?":
git rev-parse --git-dir
That would give the path of the .git
directory.
The OP mentions:
git rev-parse --show-prefix
which returns the local path under the git repo root. (empty if you are at the git repo root)
Note: for simply checking if one is in a git repo, I find the following command quite expressive:
git rev-parse --is-inside-work-tree
And yes, if you need to check if you are in a .git
git-dir folder:
git rev-parse --is-inside-git-dir
I've discovered another reason for this error. It has to do with the CSS-in-JS returning a null value to the top-level JSX of the return function in a React component.
For example:
const Css = styled.div`
<whatever css>
`;
export function exampleFunction(args1) {
...
return null;
}
export default class ExampleComponent extends Component {
...
render() {
const CssInJs = exampleFunction(args1);
...
return (
<CssInJs>
<OtherCssInJs />
...
</CssInJs>
);
}
I would get this warning:
Warning: React.createElement: type is invalid -- expected a string (for built-in components) or a class/function (for composite components) but got: null.
Followed by this error:
Uncaught Error: Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: null.
I discovered it was because there was no CSS with the CSS-in-JS component that I was trying to render. I fixed it by making sure there was CSS being returned and not a null value.
For example:
const Css = styled.div`
<whatever css>
`;
export function exampleFunction(args1) {
...
return Css;
}
export default class ExampleComponent extends Component {
...
render() {
const CssInJs = exampleFunction(args1);
...
return (
<CssInJs>
<OtherCssInJs />
...
</CssInJs>
);
}
The resolution of DateTime.Now
depends on your system timer (~10ms on a current Windows OS)...so it's giving the same ending value there (it doesn't count any more finite than that).
A horrendous example using regular expressions (you could easily clean this up :) ):
def f(s):
return s.group(1).lower() + "_" + s.group(2).lower()
p = re.compile("([A-Z]+[a-z]+)([A-Z]?)")
print p.sub(f, "CamelCase")
print p.sub(f, "getHTTPResponseCode")
Works for getHTTPResponseCode though!
Alternatively, using lambda:
p = re.compile("([A-Z]+[a-z]+)([A-Z]?)")
print p.sub(lambda x: x.group(1).lower() + "_" + x.group(2).lower(), "CamelCase")
print p.sub(lambda x: x.group(1).lower() + "_" + x.group(2).lower(), "getHTTPResponseCode")
EDIT: It should also be pretty easy to see that there's room for improvement for cases like "Test", because the underscore is unconditionally inserted.
You may have real characters "\" in the string (the single quote strings, as said @Robik).
If you are quite sure the '\r' or '\n' strings should be replaced as well, I'm not talking of special characters here but a sequence of two chars '\' and 'r', then escape the '\' in the replace string and it will work:
str_replace(array("\r\n","\r","\n","\\r","\\n","\\r\\n"),"<br/>",$description);
Assume i have two arrays. The first one has student details and the student marks details. Both arrays have the common key, that is ‘studentId’
let studentDetails = [
{ studentId: 1, studentName: 'Sathish', gender: 'Male', age: 15 },
{ studentId: 2, studentName: 'kumar', gender: 'Male', age: 16 },
{ studentId: 3, studentName: 'Roja', gender: 'Female', age: 15 },
{studentId: 4, studentName: 'Nayanthara', gender: 'Female', age: 16},
];
let studentMark = [
{ studentId: 1, mark1: 80, mark2: 90, mark3: 100 },
{ studentId: 2, mark1: 80, mark2: 90, mark3: 100 },
{ studentId: 3, mark1: 80, mark2: 90, mark3: 100 },
{ studentId: 4, mark1: 80, mark2: 90, mark3: 100 },
];
I want to merge the two arrays based on the key ‘studentId’. I have created a function to merge the two arrays.
const mergeById = (array1, array2) =>
array1.map(itm => ({
...array2.find((item) => (item.studentId === itm.studentId) && item),
...itm
}));
here is the code to get the final result
let result = mergeById(studentDetails, studentMark
);
[
{"studentId":1,"mark1":80,"mark2":90,"mark3":100,"studentName":"Sathish","gender":"Male","age":15},{"studentId":2,"mark1":80,"mark2":90,"mark3":100,"studentName":"kumar","gender":"Male","age":16},{"studentId":3,"mark1":80,"mark2":90,"mark3":100,"studentName":"Roja","gender":"Female","age":15},{"studentId":4,"mark1":80,"mark2":90,"mark3":100,"studentName":"Nayanthara","gender":"Female","age":16}
]
I know this is an old thread, but there's a newer way then having to use fsutil or diskpart.
Run this powershell command.
Get-Volume | Format-List AllocationUnitSize, FileSystemLabel
I think this suits perfect for any color you have:
a {
color: inherit;
}
It's possible your session domain does not match your app URL and/or the host being used to access the application.
1.) Check your .env file:
SESSION_DOMAIN=example.com
APP_URL=example.com
2.) Check config/session.php
Verify values to make sure they are correct.
This happens because when you click the "Accept" button on the download page in your browser, the webpage saves a cookie that it uses to check your agreement before letting you download the file. The problem occurs when trying to download from the command line using wget and it's because there's no cookie information sent with the wget request for downloading the file so from the file server's perspective, you're a completely new user who hasn't accepted the license agreement.
One solution is to send cookie information using the --header option of the wget utility (as shown above in other answers). Ideally if some content is protected, you'd use the various session management options available with wget. For this particular problem however, it's solved (currently) by sending the Cookie
header with the download request.
Adding dependencies didn't fix the issue at my end.
The issue was happening at my end because of "additional" fields that are part of the "@Entity" class and don't exist in the database.
I removed the additional fields from the @Entity class and it worked.
In my examples I use the 'b' flag ('wb', 'rb') when opening the files because you said you wanted to read bytes. The 'b' flag tells Python not to interpret end-of-line characters which can differ between operating systems. If you are reading text, then omit the 'b' and use 'w' and 'r' respectively.
This reads the entire file in one chunk using the "simplest" Python code. The problem with this approach is that you could run out memory when reading a large file:
ifile = open(input_filename,'rb')
ofile = open(output_filename, 'wb')
ofile.write(ifile.read())
ofile.close()
ifile.close()
This example is refined to read 1MB chunks to ensure it works for files of any size without running out of memory:
ifile = open(input_filename,'rb')
ofile = open(output_filename, 'wb')
data = ifile.read(1024*1024)
while data:
ofile.write(data)
data = ifile.read(1024*1024)
ofile.close()
ifile.close()
This example is the same as above but leverages using with to create a context. The advantage of this approach is that the file is automatically closed when exiting the context:
with open(input_filename,'rb') as ifile:
with open(output_filename, 'wb') as ofile:
data = ifile.read(1024*1024)
while data:
ofile.write(data)
data = ifile.read(1024*1024)
See the following:
This is a mix of the two previous answers:
PreparedStatement ps = c.prepareStatement("INSERT INTO employees VALUES (?, ?)");
ps.setString(1, "John");
ps.setString(2,"Doe");
ps.addBatch();
ps.clearParameters();
ps.setString(1, "Dave");
ps.setString(2,"Smith");
ps.addBatch();
ps.clearParameters();
int[] results = ps.executeBatch();
If you want to run the script directly, you can:
PYTHONPATH
).sys.path
in the your script.Then:
import module_you_wanted
I like these two because they seem the most logical, the latter being shorter and probably fastest (shown here using set
literal syntax which has been backported to Python 2.7):
all(x in {'a', 'b', 'c'} for x in ['a', 'b'])
# or
{'a', 'b'}.issubset({'a', 'b', 'c'})
You can't declare an extern
local method inside of a method, or any other method with an attribute. Move your DLL import into the class:
using System.Runtime.InteropServices;
public class WindowHandling
{
[DllImport("User32.dll")]
public static extern int SetForegroundWindow(IntPtr point);
public void ActivateTargetApplication(string processName, List<string> barcodesList)
{
Process p = Process.Start("notepad++.exe");
p.WaitForInputIdle();
IntPtr h = p.MainWindowHandle;
SetForegroundWindow(h);
SendKeys.SendWait("k");
IntPtr processFoundWindow = p.MainWindowHandle;
}
}
I faced same problem but that was related proxy. it was resolved by setting proxy.
Set http_proxy=http://myuserid:mypassword@myproxyname:myproxyport
Set https_proxy=http://myuserid:mypassword@myproxyname:myproxyport
This might help someone.
I've found that the best (and easiest) way to delete leading, trailing (and excessive) spaces in Excel is to use a third-party plugin. I've been using ASAP Utilities for Excel and it accomplishes the task as well as adds many other much-needed features. This approach doesn't require writing formulas and can remove spaces on any selection spanning multiple columns and/or rows. I also use this to sanitize and remove the uninvited non-breaking space that often finds its way into Excel data when copying-and-pasting from other Microsoft products.
More information regarding ASAP Utilities and trimming can be found here:
http://www.asap-utilities.com/asap-utilities-excel-tools-tip.php?tip=87
You would probably use your example like this
var newText = "<span>" + $("p").text().split(" ").join("</span> <span>") + "</span>";
This will put span tags around all the words in you paragraphs, turning
<p>Test is a demo.</p>
into
<p><span>Test</span> <span>is</span> <span>a</span> <span>demo.</span></p>
I do not know what the practical use of this could be.
I use UIUserInterfaceSizeClass
to detect a orientation changed in a UIViewController
class just like that:
override func willTransition(to newCollection: UITraitCollection, with coordinator: UIViewControllerTransitionCoordinator) {
let isiPadLandscapePortrait = newCollection.horizontalSizeClass == .regular && newCollection.verticalSizeClass == .regular
let isiPhonePlustLandscape = newCollection.horizontalSizeClass == .regular && newCollection.verticalSizeClass == .compact
let isiPhonePortrait = newCollection.horizontalSizeClass == .compact && newCollection.verticalSizeClass == .regular
let isiPhoneLandscape = newCollection.horizontalSizeClass == .compact && newCollection.verticalSizeClass == .compact
if isiPhonePortrait {
// do something...
}
}
Try this:
df[df['column_name'] == ''].index
and for NaNs you can try:
pd.isna(df['column_name'])
You can also use showdialog
Private Sub Button3_Click(sender As System.Object, e As System.EventArgs) _
Handles Button3.Click
dim mydialogbox as new aboutbox1
aboutbox1.showdialog()
End Sub
Unfortunately SQL Server interprets the quoted comma as a delimiter. This applies to both BCP and bulk insert .
From http://msdn.microsoft.com/en-us/library/ms191485%28v=sql.100%29.aspx
If a terminator character occurs within the data, it is interpreted as a terminator, not as data, and the data after that character is interpreted as belonging to the next field or record. Therefore, choose your terminators carefully to make sure that they never appear in your data.
The simplest solution is to completely disable security - change true
to false
in /var/lib/jenkins/config.xml
file.
<useSecurity>true</useSecurity>
Then just restart Jenkins, by
sudo service jenkins restart
And then go to admin panel and set everything once again.
If you in case are running your Jenkins inside k8s pod from a docker, which is my case and can not run service
command, then you can just restart Jenkins by deleting the pod:
kubectl delete pod <jenkins-pod-name>
Once the command was issued, the k8s will terminate the old pod and start a new one.
Don't use a reg-ex.
Apparently the following is a reg-ex that correctly validates most e-mails addresses that conform to RFC 2822, (and will still fail on things like "[email protected]", as will org.apache.commons.validator.routines.EmailValidator)
(?:[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*|"(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21\x23-\x5b\x5d-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])*")@(?:(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?|\[(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?|[a-z0-9-]*[a-z0-9]:(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21-\x5a\x53-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])+)\])
Possibly the easiest way to validate an e-mail to just send a confirmation e-mail to the address provided and it it bounces then it's not valid.
If you want to perform some basic checks you could just check that it's in the form *@*
If you have some business logic specific validation then you could perform that using a regex, e.g. must be a gmail.com account or something.
This will help you.
debugger;
var today = new Date();
document.getElementById('date').innerHTML = today
use this
$("#tblEntAttributes tbody").append(newRowContent);
There should be one - and preferably only one - obvious way to do it.
Therefore list(dictionary.values())
is the one way.
[*L]
vs. [].extend(L)
vs. list(L)
small_ds = {x: str(x+42) for x in range(10)}
small_df = {x: float(x+42) for x in range(10)}
print('Small Dict(str)')
%timeit [*small_ds.values()]
%timeit [].extend(small_ds.values())
%timeit list(small_ds.values())
print('Small Dict(float)')
%timeit [*small_df.values()]
%timeit [].extend(small_df.values())
%timeit list(small_df.values())
big_ds = {x: str(x+42) for x in range(1000000)}
big_df = {x: float(x+42) for x in range(1000000)}
print('Big Dict(str)')
%timeit [*big_ds.values()]
%timeit [].extend(big_ds.values())
%timeit list(big_ds.values())
print('Big Dict(float)')
%timeit [*big_df.values()]
%timeit [].extend(big_df.values())
%timeit list(big_df.values())
Small Dict(str)
256 ns ± 3.37 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)
338 ns ± 0.807 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)
336 ns ± 1.9 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)
Small Dict(float)
268 ns ± 0.297 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)
343 ns ± 15.2 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)
336 ns ± 0.68 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)
Big Dict(str)
17.5 ms ± 142 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
16.5 ms ± 338 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
16.2 ms ± 19.7 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
Big Dict(float)
13.2 ms ± 41 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
13.1 ms ± 919 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
12.8 ms ± 578 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
Done on Intel(R) Core(TM) i7-8650U CPU @ 1.90GHz.
# Name Version Build
ipython 7.5.0 py37h24bf2e0_0
* operator
is quickerlist()
is maybe slightly quickerjQuery has a method to check if something is a function
if ($.isFunction($.fn.dateJS)) {
//your code using the plugin
}
API reference: https://api.jquery.com/jQuery.isFunction/
Besides subprocess.call
, you can also use subprocess.Popen
. Like the following
subprocess.Popen(['./script', arg1, arg2])
You can try this
SELECT * FROM Buses
WHERE BusID
in (1,2,3,4,...)
Whilst the listed answer is correct, may I suggest that if your column is to hold case sensitive strings you read the documentation and alter your table definition accordingly.
In my case this amounted to defining my column as:
`tag` varchar(255) CHARACTER SET utf8 COLLATE utf8_bin NOT NULL DEFAULT ''
This is in my opinion preferential to adjusting your queries.
Easiest way is to customize bootstrap
find variable:
@grid-float-breakpoint
which is set to @screen-sm, you can change it according to your needs. Hope it helps!
You can use following command if you uninstall globally
npm uninstall -g cordova ionic
option g for global
if you want to uninstall from he drive then you can use following command
npm uninstall cordova ionic
Use MySQL's STR_TO_DATE()
function to parse the string that you're attempting to insert:
INSERT INTO tblInquiry (fldInquiryReceivedDateTime) VALUES
(STR_TO_DATE('5/15/2012 8:06:26 AM', '%c/%e/%Y %r'))
This is one of the scenarios that PHP is a very bad choice for. As previously mentioned, you can tie up all of your Apache workers very quickly doing something like this. PHP is built for start, execute, stop. It's not built for start, wait...execute, stop. You'll bog down your server very quickly and find that you have incredible scaling problems.
That said, you can still do this with PHP and have it not kill your server using the nginx HttpPushStreamModule: http://wiki.nginx.org/HttpPushStreamModule
You setup nginx in front of Apache (or whatever else) and it will take care of holding open the concurrent connections. You just respond with payload by sending data to an internal address which you could do with a background job or just have the messages fired off to people that were waiting whenever the new requests come in. This keeps PHP processes from sitting open during long polling.
This is not exclusive to PHP and can be done using nginx with any backend language. The concurrent open connections load is equal to Node.js so the biggest perk is that it gets you out of NEEDING Node for something like this.
You see a lot of other people mentioning other language libraries for accomplishing long polling and that's with good reason. PHP is just not well built for this type of behavior naturally.
You can also try this pure CSS method:
font-size: calc(100% - 0.3em);
Using delete method is the best way to do that, as per MDN description, the delete operator removes a property from an object. So you can simply write:
delete myObject.regex;
// OR
delete myObject['regex'];
The delete operator removes a given property from an object. On successful deletion, it will return true, else false will be returned. However, it is important to consider the following scenarios:
If the property which you are trying to delete does not exist, delete will not have any effect and will return true
If a property with the same name exists on the object's prototype chain, then, after deletion, the object will use the property from the prototype chain (in other words, delete only has an effect on own properties).
Any property declared with var cannot be deleted from the global scope or from a function's scope.
As such, delete cannot delete any functions in the global scope (whether this is part from a function definition or a function (expression).
Functions which are part of an object (apart from the
global scope) can be deleted with delete.Any property declared with let or const cannot be deleted from the scope within which they were defined. Non-configurable properties cannot be removed. This includes properties of built-in objects like Math, Array, Object and properties that are created as non-configurable with methods like Object.defineProperty().
The following snippet gives another simple example:
var Employee = {_x000D_
age: 28,_x000D_
name: 'Alireza',_x000D_
designation: 'developer'_x000D_
}_x000D_
_x000D_
console.log(delete Employee.name); // returns true_x000D_
console.log(delete Employee.age); // returns true_x000D_
_x000D_
// When trying to delete a property that does _x000D_
// not exist, true is returned _x000D_
console.log(delete Employee.salary); // returns true
_x000D_
For more info about and seeing more example, visit the link below:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/delete
I have written a little helper function to replace text in a file:
function Replace-TextInFile
{
Param(
[string]$FilePath,
[string]$Pattern,
[string]$Replacement
)
[System.IO.File]::WriteAllText(
$FilePath,
([System.IO.File]::ReadAllText($FilePath) -replace $Pattern, $Replacement)
)
}
Example:
Get-ChildItem . *.config -rec | ForEach-Object {
Replace-TextInFile -FilePath $_ -Pattern 'old' -Replacement 'new'
}
use
aria2c -x 10 -i websites.txt >/dev/null 2>/dev/null &
in websites.txt put 1 url per line, example:
https://www.example.com/1.mp4
https://www.example.com/2.mp4
https://www.example.com/3.mp4
https://www.example.com/4.mp4
https://www.example.com/5.mp4
Prefix you literal with 0b
like in
int i = 0b11111111;
See here.
You need to sign your APK with your live certificate. Then install that onto your test device. You can then test InAppBilling. If you are testing your application by direct run via eclipse to device(In debug mode) then you will get this error.
If you are using android.test.purchased
as the SKU, it will work all the way, but you won't have the developerPayload in your final response.
If you are using your own draft in app item you can test all the way but you will be charged and so will have to refund it yourself afterwards.
You cannot buy items with the same gmail account that you use for the google play development console.
Pattern to match at least 1 upper case character, 1 digit and any special characters and the length between 8 to 63.
"^(?=.*[a-z])(?=.*[A-Z])(?=.*\\d)[a-zA-Z\\d\\W]{8,63}$"
This pattern was used for JAVA programming.
current_dir=$PWD;cd /path/to/your/command/dir;special command ARGS;cd $current_dir;
current_dir
equal to your pwd
cd
to where you need to run your commandcd
back to our variable current_dir
Another Solution by @apieceofbart
pushd && YOUR COMMAND && popd
SELECT TOP 1 BILL_AMT Bill_Amt FROM ( SELECT DISTINCT TOP 3 NH_BL_BILL.BILL_AMT FROM NH_BL_BILL ORDER BY BILL_AMT DESC) A
ORDER BY BILL_AMT ASC
First check if the request object have the 'is_private' key parameter. Most of the case's this MultiValueDictKeyError occurred for missing key in the dictionary-like request object. Because dictionary is an unordered key, value pair “associative memories” or “associative arrays”
In another word. request.GET or request.POST is a dictionary-like object containing all request parameters. This is specific to Django.
The method get() returns a value for the given key if key is in the dictionary. If key is not available then returns default value None.
You can handle this error by putting :
is_private = request.POST.get('is_private', False);
Make sure that this element you would like to control with z-index does not have a parent with z-index property, because element is in a lower stacking context due to its parent’s z-index level.
Here's an example:
<section class="content">
<div class="modal"></div>
</section>
<div class="side-tab"></div>
// CSS //
.content {
position: relative;
z-index: 1;
}
.modal {
position: fixed;
z-index: 100;
}
.side-tab {
position: fixed;
z-index: 5;
}
In the example above, the modal has a higher z-index than the content, although the content will appear on top of the modal because "content" is the parent with a z-index property.
Here's an article that explains 4 reasons why z-index might not work: https://coder-coder.com/z-index-isnt-working/
Actually, there are five words commonly used when we talk about layers of reference models (or protocol stacks): data
, segment
, packet
, frame
and bit
. And the term PDU (Protocol Data Unit
) is used to refer to the packets in different layers of the OSI model. Thus PDU gives an abstract idea of the data packets. The PDU has a different meaning in different layers still we can use it as a common term.
When we come to your question, we can call all of them by using the general term PDU
, but if you want to call them specifically at a given layer:
Here is a diagram, since a picture is worth a thousand words:
stripslashes(htmlspecialchars(JSON_DATA))
<div class="post_category">
<?php $category = get_the_category();
$allcategory = get_the_category();
foreach ($allcategory as $category) {
?>
<a class="btn"><?php echo $category->cat_name;; ?></a>
<?php
}
?>
</div>
It's the "frame" or "range" clause of window functions, which are part of the SQL standard and implemented in many databases, including Teradata.
A simple example would be to calculate the average amount in a frame of three days. I'm using PostgreSQL syntax for the example, but it will be the same for Teradata:
WITH data (t, a) AS (
VALUES(1, 1),
(2, 5),
(3, 3),
(4, 5),
(5, 4),
(6, 11)
)
SELECT t, a, avg(a) OVER (ORDER BY t ROWS BETWEEN 1 PRECEDING AND 1 FOLLOWING)
FROM data
ORDER BY t
... which yields:
t a avg
----------
1 1 3.00
2 5 3.00
3 3 4.33
4 5 4.00
5 4 6.67
6 11 7.50
As you can see, each average is calculated "over" an ordered frame consisting of the range between the previous row (1 preceding
) and the subsequent row (1 following
).
When you write ROWS UNBOUNDED PRECEDING
, then the frame's lower bound is simply infinite. This is useful when calculating sums (i.e. "running totals"), for instance:
WITH data (t, a) AS (
VALUES(1, 1),
(2, 5),
(3, 3),
(4, 5),
(5, 4),
(6, 11)
)
SELECT t, a, sum(a) OVER (ORDER BY t ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW)
FROM data
ORDER BY t
yielding...
t a sum
---------
1 1 1
2 5 6
3 3 9
4 5 14
5 4 18
6 11 29
Here's another very good explanations of SQL window functions.
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.waist2height); {
final EditText edit = (EditText)findViewById(R.id.editText);
final RadioButton rb1 = (RadioButton) findViewById(R.id.radioCM);
final RadioButton rb2 = (RadioButton) findViewById(R.id.radioFT);
if(rb1.isChecked()){
edit.setVisibility(View.VISIBLE);
}
else if(rb2.isChecked()){
edit.setVisibility(View.INVISIBLE);
}
}
This is the free version of their flagship product, but it contains a date and time picker native for asp.net.
For windows add the path for meld is like below:
git config --global mergetool.meld.path C:\\Meld_run\\Meld.exe
This is a general rambling on Parallelism in SQL Server, it might not answer your question directly.
From Books Online, on MAXDOP:
Sets the maximum number of processors the query processor can use to execute a single index statement. Fewer processors may be used depending on the current system workload.
See Rickie Lee's blog on parallelism and CXPACKET wait type. It's quite interesting.
Generally, in an OLTP database, my opinion is that if a query is so costly it needs to be executed on several processors, the query needs to be re-written into something more efficient.
Why you get better results adding MAXDOP(1)? Hard to tell without the actual execution plans, but it might be so simple as that the execution plan is totally different that without the OPTION, for instance using a different index (or more likely) JOINing differently, using MERGE or HASH joins.
The basic difference is, like you stated, generating GUI events from the BackgroundWorker
. If the thread does not need to update the display or generate events for the main GUI thread, then it can be a simple thread.
Email link function i use "%0D%0A"
function sendMail() {
var bodydata="Before "+ "%0D%0A";
bodydata+="After"
var MailMSG = "mailto:[email protected]"
+ "[email protected]"
+ "&subject=subject"
+ "&body=" + bodydata;
window.location.href = MailMSG;
}
[HTML]
<a href="#" onClick="sendMail()">Contact Us</a>
The ls
command has a parameter -t
to sort by time. You can then grab the first (newest) with head -1
.
ls -t b2* | head -1
But beware: Why you shouldn't parse the output of ls
My personal opinion: parsing ls
is only dangerous when the filenames can contain funny characters like spaces or newlines. If you can guarantee that the filenames will not contain funny characters then parsing ls
is quite safe.
If you are developing a script which is meant to be run by many people on many systems in many different situations then I very much do recommend to not parse ls
.
Here is how to do it "right": How can I find the latest (newest, earliest, oldest) file in a directory?
unset -v latest
for file in "$dir"/*; do
[[ $file -nt $latest ]] && latest=$file
done
You can get the name that it was defined with using the approach that @Andreas Jung shows, but that may not be the name that the function was called with:
import inspect
def Foo():
print inspect.stack()[0][3]
Foo2 = Foo
>>> Foo()
Foo
>>> Foo2()
Foo
Whether that distinction is important to you or not I can't say.
Try this workaround for the theming problem:
@Override
public void onBackPressed() {
NavUtils.navigateUpTo(this, new Intent(this,
MyNeedToBeRefreshed.class));
}
This will also work and you don't need the extra class:
#navigation li li {}
If you have a third level of LI's you may have to reset/override some of the styles they will inherit from the above selector. You can target the third level like so:
#navigation li li li {}
Here's a bash function which checks all your servers, assuming you're using DNS round-robin. Note that this requires GNU date and won't work on Mac OS
function check_certs () {
if [ -z "$1" ]
then
echo "domain name missing"
exit 1
fi
name="$1"
shift
now_epoch=$( date +%s )
dig +noall +answer $name | while read _ _ _ _ ip;
do
echo -n "$ip:"
expiry_date=$( echo | openssl s_client -showcerts -servername $name -connect $ip:443 2>/dev/null | openssl x509 -inform pem -noout -enddate | cut -d "=" -f 2 )
echo -n " $expiry_date";
expiry_epoch=$( date -d "$expiry_date" +%s )
expiry_days="$(( ($expiry_epoch - $now_epoch) / (3600 * 24) ))"
echo " $expiry_days days"
done
}
Output example:
$ check_certs stackoverflow.com
151.101.1.69: Aug 14 12:00:00 2019 GMT 603 days
151.101.65.69: Aug 14 12:00:00 2019 GMT 603 days
151.101.129.69: Aug 14 12:00:00 2019 GMT 603 days
151.101.193.69: Aug 14 12:00:00 2019 GMT 603 days
These are Unicode property shortcuts (\p{L}
for Unicode letters, \p{N}
for Unicode digits). They are supported by .NET, Perl, Java, PCRE, XML, XPath, JGSoft, Ruby (1.9 and higher) and PHP (since 5.1.0)
At any rate, that's a very strange regex. You should not be using alternation when a character class would suffice:
[\p{L}\p{N}_.-]*
I would suggest two interesting lectures:
1.
The with
statement is used to wrap the execution of a block with methods defined by a context manager. This allows common try...except...finally
usage patterns to be encapsulated for convenient reuse.
2. You could do something like:
with open("foo.txt") as foo_file:
data = foo_file.read()
OR
from contextlib import nested
with nested(A(), B(), C()) as (X, Y, Z):
do_something()
OR (Python 3.1)
with open('data') as input_file, open('result', 'w') as output_file:
for line in input_file:
output_file.write(parse(line))
OR
lock = threading.Lock()
with lock:
# Critical section of code
3.
I don't see any Antipattern here.
Quoting Dive into Python:
try..finally is good. with is better.
4.
I guess it's related to programmers's habit to use try..catch..finally
statement from other languages.