What you are doing will not work for root user. Maybe you are running your services as root and hence you don't get to see the change.
To increase the ulimit for root user you should replace the *
by root. *
does not apply for root user. Rest is the same as you did. I will re-quote it here.
Add the following lines to the file: /etc/security/limits.conf
root soft nofile 40000
root hard nofile 40000
And then add following line in the file: /etc/pam.d/common-session
session required pam_limits.so
This will update the ulimit for root user. As mentioned in comments, you may don't even have to reboot to see the change.
If you have a rooted device you can use kill
command
Connect to your device with adb:
adb shell
Once the session is established, you have to escalade privileges:
su
Then
ps
will list running processes. Note down the PID of the process you want to terminate. Then get rid of it
kill PID
Running chrome.exe --start-fullscreen --app=https://google.com
will not get you Chrome in fullscreen, but in kiosk mode.
However, running chrome --start-fullscreen --app=https://google.com
(notice : it's chrome
instead of chrome.exe
) worked in my case.
On macOS using brew, using librsvg directly works well
brew install librsvg
rsvg-convert test.svg -o test.png
Many options are available via rsvg-convert --help
Start from m2e 0.13.0 (if not earlier than), you can convert a Java project to Maven project from the context menu. Here is how:
Here is the detailed steps with screen shots.
array_walk($v, function(&$value, $key) {
echo $key . '--'. $value;
});
Learn more about array_walk
I realize this is an old question but for those reading, I would recommend against using recursion for problems such as this - lists are much faster and avoid recursion entirely. I would implement this as:
def fibonacci(n):
f = [0,1,1]
for i in xrange(3,n):
f.append(f[i-1] + f[i-2])
return 'The %.0fth fibonacci number is: %.0f' % (n,f[-1])
(Use n+1 in xrange if you start counting your fibonacci sequence from 0 instead of 1.)
You can use the random functionality included within the additions to the standard library (TR1). Or you can use the same old technique that works in plain C:
25 + ( std::rand() % ( 63 - 25 + 1 ) )
I'd recommend using a CLR user defined function, if you already know how to program in C#, then the code would be;
using System.Data.SqlTypes;
using System.Net;
public partial class UserDefinedFunctions
{
[Microsoft.SqlServer.Server.SqlFunction]
public static SqlString http(SqlString url)
{
var wc = new WebClient();
var html = wc.DownloadString(url.Value);
return new SqlString (html);
}
}
And here's installation instructions; https://blog.dotnetframework.org/2019/09/17/make-a-http-request-from-sqlserver-using-a-clr-udf/
You could also capture the function output:
#!/bin/bash
function getSomeString() {
echo "tadaa!"
}
return_var=$(getSomeString)
echo $return_var
# Alternative syntax:
return_var=`getSomeString`
echo $return_var
Looks weird, but is better than using global variables IMHO. Passing parameters works as usual, just put them inside the braces or backticks.
I had the same problem. I am using jquery-validation as an npm module and the fix for me was to require the module at the start of my js file:
require('jquery-validation');
You can also check it by doing.
if(count($array) > 0)
{
echo 'Error';
}
else
{
echo 'No Error';
}
Since I just went though a drag, I'll try to write the answer I'd have wished for two hours ago. This is for people who don't just want the copy&paste solution
First: Do you wonder why copying and pasting paths works for some people while it doesn't work for others?** The main reason, solutions differ are different python versions, 2.x or 3.x. There are actually distinct versions of virtualenv and virtualenvwrapper that work with either python 2 or 3. If you are on python 2 install like so:
sudo pip install virutalenv
sudo pip install virtualenvwrapper
If you are planning to use python 3 install the related python 3 versions
sudo pip3 install virtualenv
sudo pip3 install virtualenvwrapper
You've successfully installed the packages for your python version and are all set, right? Well, try it. Type workon
into your terminal. Your terminal will not be able to find the command (workon
is a command of virtualenvwrapper). Of course it won't. Workon
is an executable that will only be available to you once you load/source the file virtualenvwrapper.sh
. But the official installation guide has you covered on this one, right?. Just open your .bash_profile and insert the following, it says in the documentation:
export WORKON_HOME=$HOME/.virtualenvs
export PROJECT_HOME=$HOME/Devel
source /usr/local/bin/virtualenvwrapper.sh
Especially the command source /usr/local/bin/virtualenvwrapper.sh
seems helpful since the command seems to load/source the desired file virtualenvwrapper.sh
that contains all the commands you want to work with like workon
and mkvirtualenv
. But yeah, no. When following the official installation guide, you are very likely to receive the error from the initial post: mkvirtualenv: command not found
. Still no command is being found and you are still frustrated. So whats the problem here? The problem is that virtualenvwrapper.sh is not were you are looking for it right now. Short reminder ... you are looking here:
source /usr/local/bin/virtualenvwrapper.sh
But there is a pretty straight forward way to finding the desired file. Just type
which virtualenvwrapper
to your terminal. This will search your PATH for the file, since it is very likely to be in some folder that is included in the PATH of your system.
If your system is very exotic, the desired file will hide outside of a PATH folder. In that case you can find the path to virtalenvwrapper.sh
with the shell command find / -name virtualenvwrapper.sh
Your result may look something like this: /Library/Frameworks/Python.framework/Versions/3.7/bin/virtualenvwrapper.sh
Congratulations. You have found your missing file!
. Now all you have to do is changing one command in your .bash_profile. Just change:
source "/usr/local/bin/virtualenvwrapper.sh"
to:
"/Library/Frameworks/Python.framework/Versions/3.7/bin/virtualenvwrapper.sh"
Congratulations. Virtualenvwrapper does now work on your system. But you can do one more thing to enhance your solution. If you've found the file virtualenvwrapper.sh
with the command which virtualenvwrapper.sh
you know that it is inside of a folder of the PATH. So if you just write the filename, your file system will assume the file is inside of a PATH folder. So you you don't have to write out the full path. Just type:
source "virtualenvwrapper.sh"
Thats it. You are no longer frustrated. You have solved your problem. Hopefully.
If you make changes to many tracked files but only want to stage a few of them, doing a
git add .
isn't always favorable (or recommended)- as it stages all the tracked files (some cases where you want to keep changes only to yourself and don't want to stage them to the remote repository).
nor is it ideal doing a bunch of
git add path/to/file1 path/to/file2
if you have a lot of nested directories (which is the case in most projects) - gets annoying
That's when Git GUI is helpful (probably only time I use it). Just open Git GUI, it shows staged and unstaged file sections. Select the files from the staged section that you want to unstage and press
Ctrl+U
(for windows)
to unstage them.
Setting the top and left properties to negative values might not be a good workaround if your problem is simply that you're in quirks mode. This can happen if the page is missing a <!DOCTYPE>
declaration, causing it to be rendered in quirks mode in IE8. In IE8 Developer Tools, make sure that "Quirks Mode" is not selected under "Document Mode". If it is selected, you may need to add the appropriate <!DOCTYPE>
declaration.
This option works only if you can open the DB in a DB Browser like DB Browser for SQLite.
In DB Browser for SQLite:
I was able to do this by using this command:
notepad .gitignore
And it would open the .gitignore file in Notepad.
Run java
with -d64
or -d32
specified, it will give you an error message if it doesn't support 64-bit or 32-bit respectively. Your JVM may support both.
Looking at the dates for which it doesn't work -- those where the day is less than or equal to 12 -- I'm wondering whether it's parsing the dates as being in YYYY-DD-MM format?
since python-daemon has not yet supported python 3.x, and from what can be read on the mailing list, it may never will, i have written a new implementation of PEP 3143: pep3143daemon
pep3143daemon should support at least python 2.6, 2.7 and 3.x
It also contains a PidFile class.
The library only depends on the standard library and on the six module.
It can be used as a drop in replacement for python-daemon.
Here is the documentation.
const express = require('express')
const bodyParser = require('body-parser')
const { usersNdJobs, userByJob, addUser , addUserToCompany } = require ('./db/db.js')
const app = express()
app.set('view engine', 'pug')
app.use(express.static('public'))
app.use(bodyParser.urlencoded({ extended: false }))
app.use(bodyParser.json())
app.get('/', (req, res) => {
usersNdJobs()
.then((users) => {
res.render('users', { users })
})
.catch(console.error)
})
app.get('/api/company/users', (req, res) => {
const companyname = req.query.companyName
console.log(companyname)
userByJob(companyname)
.then((users) => {
res.render('job', { users })
}).catch(console.error)
})
app.post('/api/users/add', (req, res) => {
const userName = req.body.userName
const jobName = req.body.jobName
console.log("user name = "+userName+", job name : "+jobName)
addUser(userName, jobName)
.then((result) => {
res.status(200).json(result)
})
.catch((error) => {
res.status(404).json({ 'message': error.toString() })
})
})
app.post('/users/add', (request, response) => {
const { userName, job } = request.body
addTeam(userName, job)
.then((user) => {
response.status(200).json({
"userName": user.name,
"city": user.job
})
.catch((err) => {
request.status(400).json({"message": err})
})
})
app.post('/api/user/company/add', (req, res) => {
const userName = req.body.userName
const companyName = req.body.companyName
console.log(userName, companyName)
addUserToCompany(userName, companyName)
.then((result) => {
res.json(result)
})
.catch(console.error)
})
app.get('/api/company/user', (req, res) => {
const companyname = req.query.companyName
console.log(companyname)
userByJob(companyname)
.then((users) => {
res.render('jobs', { users })
})
})
app.listen(3000, () =>
console.log('Example app listening on port 3000!')
)
SOAP (Simple Object Access Protocol) is the communication protocol in the web service scenario.
One benefit of SOAP is that it allowas RPC to execute through a firewall. But to pass through a firewall, you will probably want to use 80. it uses port no.8084 To the firewall, a SOAP conversation on 80 looks like a POST to a web page. However, there are extensions in SOAP which are specifically aimed at the firewall. In the future, it may be that firewalls will be configured to filter SOAP messages. But as of today, most firewalls are SOAP ignorant.
so exclusively open SOAP Port in Firewalls
For this you need to run the "tomcat6w" application that is part of the standard Tomcat distribution in the "bin" directory. E.g. for windows the default is "C:\Program Files\Apache Software Foundation\Tomcat 6.0\bin\tomcat6w.exe". The "tomcat6w" application starts a GUI. If you select the "Java" tab you can enter all Java options.
It is also possible to pass JVM options via the command line to tomcat. For this you need to use the command:
<tomcatexecutable> //US//<tomcatservicename> ++JvmOptions="<JVMoptions>"
where "tomcatexecutable" refers to your tomcat application, "tomcatservicename" is the tomcat service name you are using and "JVMoptions" are your JVM options. For instance:
"tomcat6.exe" //US//tomcat6 ++JvmOptions="-XX:MaxPermSize=128m"
This is a simple solution which solved the problem for me:
label
{
/* for firefox */
vertical-align:middle;
/*for internet explorer */
*bottom:3px;
*position:relative;
padding-bottom:7px;
}
You can use ESCAPE
:
WHERE columnName LIKE '%\%%' ESCAPE '\'
Here is a one-liner for Mac/Linux to connect to an Android device over Wi-Fi, but first you must connect to the device via USB.
# sleep 5 is to wait for the device to restart listening.
adb kill-server && adb tcpip 5555 && sleep 5 && adb shell ip route | awk '{print $9}' | xargs adb connect
You need to use something like this:
OracleCommand oraCommand = new OracleCommand("SELECT fullname FROM sup_sys.user_profile
WHERE domain_user_name = :userName", db);
More can be found in this MSDN article: http://msdn.microsoft.com/en-us/library/system.data.oracleclient.oraclecommand.parameters%28v=vs.100%29.aspx
It is advised you use the : character instead of @ for Oracle.
This worked for me. Since I'm storing images on a SQL Server database.
[HttpGet("/image/{uuid}")]
public IActionResult GetImageFile(string uuid) {
ActionResult actionResult = new NotFoundResult();
var fileImage = _db.ImageFiles.Find(uuid);
if (fileImage != null) {
actionResult = new FileContentResult(fileImage.Data,
fileImage.ContentType);
}
return actionResult;
}
In the snippet above _db.ImageFiles.Find(uuid)
is searching for the image file record in the db (EF context). It returns a FileImage object which is just a custom class I made for the model and then uses it as FileContentResult.
public class FileImage {
public string Uuid { get; set; }
public byte[] Data { get; set; }
public string ContentType { get; set; }
}
In order to avoid ORDER BY items must appear in the select list if SELECT DISTINCT
error, the best should be
var results = (
from ta in DBContext.TestAddresses
select ta.Name
)
.Distinct()
.OrderBy( x => 1);
You can do the following (assuming you are checked out on master and want to push to a remote branch master):
Set up the 'remote' if you don't have it already
git remote add origin ssh://...
Now configure master to know to track:
git config branch.master.remote origin
git config branch.master.merge refs/heads/master
And push:
git push origin master
using javascript
<form id="frm1" action="file.php"></form>
<script>document.getElementById('frm1').submit();</script>
To split the difference of opinion
I prefer:
xls.DisplayAlerts = False
wb.SaveAs fullFilePath, AccessMode:=xlExclusive, ConflictResolution:=xlLocalSessionChanges
xls.DisplayAlerts = True
The res
argument in the http.get()
callback is not the body, but rather an http.ClientResponse object. You need to assemble the body:
var url = 'http://graph.facebook.com/517267866/?fields=picture';
http.get(url, function(res){
var body = '';
res.on('data', function(chunk){
body += chunk;
});
res.on('end', function(){
var fbResponse = JSON.parse(body);
console.log("Got a response: ", fbResponse.picture);
});
}).on('error', function(e){
console.log("Got an error: ", e);
});
You might be do that its works 100% .
- (void)viewDidLoad
{
[super viewDidLoad];
// init table view
tableView = [[UITableView alloc] initWithFrame:self.view.bounds style:UITableViewStylePlain];
// must set delegate & dataSource, otherwise the the table will be empty and not responsive
tableView.delegate = self;
tableView.dataSource = self;
tableView.backgroundColor = [UIColor cyanColor];
// add to canvas
[self.view addSubview:tableView];
}
#pragma mark - UITableViewDataSource
// number of section(s), now I assume there is only 1 section
- (NSInteger)numberOfSectionsInTableView:(UITableView *)theTableView
{
return 1;
}
// number of row in the section, I assume there is only 1 row
- (NSInteger)tableView:(UITableView *)theTableView numberOfRowsInSection:(NSInteger)section
{
return 1;
}
// the cell will be returned to the tableView
- (UITableViewCell *)tableView:(UITableView *)theTableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *cellIdentifier = @"HistoryCell";
// Similar to UITableViewCell, but
JSCustomCell *cell = (JSCustomCell *)[theTableView dequeueReusableCellWithIdentifier:cellIdentifier];
if (cell == nil) {
cell = [[JSCustomCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];
}
// Just want to test, so I hardcode the data
cell.descriptionLabel.text = @"Testing";
return cell;
}
#pragma mark - UITableViewDelegate
// when user tap the row, what action you want to perform
- (void)tableView:(UITableView *)theTableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
NSLog(@"selected %d row", indexPath.row);
}
@end
Small devices (landscape phones, 576px and up)
@media (min-width: 576px) {
#my-content{
width:100%;
}
// Medium devices (tablets, 768px and up)
@media (min-width: 768px) {
#my-content{
width:100%;
}
}
// Large devices (desktops, 992px and up)
@media (min-width: 992px) {
display: none;
}
// Extra large devices (large desktops, 1200px and up)
@media (min-width: 1200px) {
// Havent code only get for more informations
}
It works by same principle of anonymous inner class where we can instantiate an interface without actually defining a class :
Ref: https://www.geeksforgeeks.org/anonymous-inner-class-java/
You're trying to do &(2), &(4)
which won't work
#romtest {
.detailed {
th {
&:nth-child(2) {//your styles here}
&:nth-child(4) {//your styles here}
&:nth-child(6) {//your styles here}
}
}
}
A "slug" is a way of generating a valid URL, generally using data already obtained. For instance, a slug uses the title of an article to generate a URL. I advise to generate the slug by means of a function, given the title (or another piece of data), rather than setting it manually.
An example:
<title> The 46 Year Old Virgin </title>
<content> A silly comedy movie </content>
<slug> the-46-year-old-virgin </slug>
Now let's pretend that we have a Django model such as:
class Article(models.Model):
title = models.CharField(max_length=100)
content = models.TextField(max_length=1000)
slug = models.SlugField(max_length=40)
How would you reference this object with a URL and with a meaningful name? You could for instance use Article.id so the URL would look like this:
www.example.com/article/23
Or, you might want to reference the title like this:
www.example.com/article/The 46 Year Old Virgin
Since spaces aren't valid in URLs, they must be replaced by %20
, which results in:
www.example.com/article/The%2046%20Year%20Old%20Virgin
Both attempts are not resulting in very meaningful, easy-to-read URL. This is better:
www.example.com/article/the-46-year-old-virgin
In this example, the-46-year-old-virgin
is a slug: it is created from the title by down-casing all letters, and replacing spaces by hyphens -
.
Also see the URL of this very web page for another example.
This is probably simpler than you're thinking:
int w = WIDTH_PX, h = HEIGHT_PX;
Bitmap.Config conf = Bitmap.Config.ARGB_8888; // see other conf types
Bitmap bmp = Bitmap.createBitmap(w, h, conf); // this creates a MUTABLE bitmap
Canvas canvas = new Canvas(bmp);
// ready to draw on that bitmap through that canvas
Here's a series of tutorials I've found on the topic: Drawing with Canvas Series
Now with new JavaScript version (ECMAScript 6 http://es6-features.org/#ClassDefinition) there is a better way to submit requests using nodejs and Promise request (http://www.wintellect.com/devcenter/nstieglitz/5-great-features-in-es6-harmony)
Using library: https://github.com/request/request-promise
npm install --save request
npm install --save request-promise
client:
//Sequential execution for node.js using ES6 ECMAScript
var rp = require('request-promise');
rp({
method: 'POST',
uri: 'http://localhost:3000/',
body: {
val1 : 1,
val2 : 2
},
json: true // Automatically stringifies the body to JSON
}).then(function (parsedBody) {
console.log(parsedBody);
// POST succeeded...
})
.catch(function (err) {
console.log(parsedBody);
// POST failed...
});
server:
var express = require('express')
, bodyParser = require('body-parser');
var app = express();
app.use(bodyParser.json());
app.post('/', function(request, response){
console.log(request.body); // your JSON
var jsonRequest = request.body;
var jsonResponse = {};
jsonResponse.result = jsonRequest.val1 + jsonRequest.val2;
response.send(jsonResponse);
});
app.listen(3000);
To fully overload it you also need to implement the __setitem__
and __delitem__
methods.
edit
I almost forgot... if you want to completely emulate a list, you also need __getslice__, __setslice__ and __delslice__
.
There are all documented in http://docs.python.org/reference/datamodel.html
In Javascript you can use [^]* to search for zero to infinite characters, including line breaks.
$("#find_and_replace").click(function() {_x000D_
var text = $("#textarea").val();_x000D_
search_term = new RegExp("[^]*<Foobar>", "gi");;_x000D_
replace_term = "Replacement term";_x000D_
var new_text = text.replace(search_term, replace_term);_x000D_
$("#textarea").val(new_text);_x000D_
});
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
<button id="find_and_replace">Find and replace</button>_x000D_
<br>_x000D_
<textarea ID="textarea">abcde_x000D_
fghij<Foobar></textarea>
_x000D_
Why would the first way not work. Canvas object is created and the size is set and the grahpics are set. I always find this strange. Also if a class extends JComponent you can override the
paintComponent(){
super...
}
and then shouldn't you be able to create and instance of the class inside of another class and then just call NewlycreateinstanceOfAnyClass.repaint();
I have tried this approach for some game programming I have been working and it doesn't seem to work the way I think that it should be.
Doug Hauf
I used the url as above: http://translate.google.com/translate_tts?tl=en&q=Hello%20World
And requested with python library..however I'm getting HTTP 403 FORBIDDEN
In the end I had to mock the User-Agent
header with the browser's one to succeed.
You can try below command, which describes the,
ng -> Angular
g -> Generate
c -> Component
-m -> Module
Then your command will be like:
ng g c user/userComponent -m user.module
This is a Pythonic way to do it:
import httplib
import yaml
c = httplib.HTTPConnection(address)
c.request('GET', url_path)
r = c.getresponse()
# get the date into a datetime object
lmd = r.getheader('last-modified')
if lmd != None:
cur_data = { url: datetime.strptime(lmd, '%a, %d %b %Y %H:%M:%S %Z') }
else:
print "Hmmm, no last-modified data was returned from the URL."
print "Returned header:"
print yaml.dump(dict(r.getheaders()), default_flow_style=False)
The rest of the script includes an example of archiving a page and checking for changes against the new version, and alerting someone by email.
Your code can be fixed as follows:
import numpy as np, cv
vis = np.zeros((384, 836), np.float32)
h,w = vis.shape
vis2 = cv.CreateMat(h, w, cv.CV_32FC3)
vis0 = cv.fromarray(vis)
cv.CvtColor(vis0, vis2, cv.CV_GRAY2BGR)
Short explanation:
np.uint32
data type is not supported by OpenCV (it supports uint8
, int8
, uint16
, int16
, int32
, float32
, float64
)cv.CvtColor
can't handle numpy arrays so both arguments has to be converted to OpenCV type. cv.fromarray
do this conversion.cv.CvtColor
must have the same depth. So I've changed source type to 32bit float to match the ddestination.Also I recommend you use newer version of OpenCV python API because it uses numpy arrays as primary data type:
import numpy as np, cv2
vis = np.zeros((384, 836), np.float32)
vis2 = cv2.cvtColor(vis, cv2.COLOR_GRAY2BGR)
It's a great idea to use cURL as suggested by rojoca.
Here is an example. You can monitor text.txt while the script is running in background:
<?php
function doCurl($begin)
{
echo "Do curl<br />\n";
$url = 'http://'.$_SERVER['SERVER_NAME'].$_SERVER['REQUEST_URI'];
$url = preg_replace('/\?.*/', '', $url);
$url .= '?begin='.$begin;
echo 'URL: '.$url.'<br>';
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$result = curl_exec($ch);
echo 'Result: '.$result.'<br>';
curl_close($ch);
}
if (empty($_GET['begin'])) {
doCurl(1);
}
else {
while (ob_get_level())
ob_end_clean();
header('Connection: close');
ignore_user_abort();
ob_start();
echo 'Connection Closed';
$size = ob_get_length();
header("Content-Length: $size");
ob_end_flush();
flush();
$begin = $_GET['begin'];
$fp = fopen("text.txt", "w");
fprintf($fp, "begin: %d\n", $begin);
for ($i = 0; $i < 15; $i++) {
sleep(1);
fprintf($fp, "i: %d\n", $i);
}
fclose($fp);
if ($begin < 10)
doCurl($begin + 1);
}
?>
Just to elaborate on the etymology of the command name rev-parse
, Git consistently uses the term rev
in plumbing commands as short for "revision" and generally meaning the 40-character SHA1 hash for a commit. The command rev-list
for example prints a list of 40-char commit hashes for a branch or whatever.
In this case the name might be expanded to parse-a-commitish-to-a-full-SHA1-hash
. While the command has the several ancillary functions mentioned in Tuxdude's answer, its namesake appears to be the use case of transforming a user-friendly reference like a branch name or abbreviated hash into the unambiguous 40-character SHA1 hash most useful for many programming/plumbing purposes.
I know I was thinking it was "reverse-parse" something for quite a while before I figured it out and had the same trouble making sense of the terms "massaging" and "manipulation" :)
Anyway, I find this "parse-to-a-revision" notion a satisfying way to think of it, and a reliable concept for bringing this command to mind when I need that sort of thing. Frequently in scripting Git you take a user-friendly commit reference as user input and generally want to get it resolved to a validated and unambiguous working reference as soon after receiving it as possible. Otherwise input translation and validation tends to proliferate through the script.
You can use insert
:
a = [1,2,3]
a.insert(0,'x')
=> ['x',1,2,3]
Where the first argument is the index to insert at and the second is the value.
I think you are confused with the printf(String format, Object... args)
method. The first argument is the format string, which is mandatory, rest you can pass an arbitrary number of Object
s.
There is no such overload for both the print()
and println()
methods.
i have same issue and resolved by
data: "Id1=" + id1 + "&Id2=" + id2
Those steps should be able to be shortened down to:
hg pull
hg update -r MY_BRANCH -C
The -C
flag tells the update command to discard all local changes before updating.
However, this might still leave untracked files in your repository. It sounds like you want to get rid of those as well, so I would use the purge
extension for that:
hg pull
hg update -r MY_BRANCH -C
hg purge
In any case, there is no single one command you can ask Mercurial to perform that will do everything you want here, except if you change the process to that "full clone" method that you say you can't do.
You can use the following steps:
Step 1: Create a requirements.txt with list of packages to be installed. If you want to copy packages in a particular environment, do this
pip freeze >> requirements.txt
else store package names in a file named requirements.txt
Step 2: Execute pip command with this file
pip install -r requirements.txt
Actually the answer is yes. Here is an example how you can do this: http://html5doctor.com/introducing-web-sql-databases/
The bad thing is that it's with very limited support by the browsers.
More information here HTML5 IndexedDB, Web SQL Database and browser wars
PS: As @Christoph said Web SQL is no longer in active maintenance and the Web Applications Working Group does not intend to maintain it further so look here https://developer.mozilla.org/en-US/docs/IndexedDB.
EDIT
As @clentfort said, you can access SQLite database with client-side JavaScript by using SQL.js.
I'm always write in the first style.
Even if a compiler is smart enough to optimize it for arrays, but still it smart if we are using DOMNodeList here or some complicated object with calculated length?
I know what the question is about arrays, but i think it is a good practice to write all your loops in one style.
I now found solution by using mysqli
instead of mysql
.
<?php
// enable error reporting
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
//connect to database
$connection = mysqli_connect("hostname", "user", "password", "db", "port");
//run the store proc
$result = mysqli_query($connection, "CALL StoreProcName");
//loop the result set
while ($row = mysqli_fetch_array($result)){
echo $row[0] . " - " . + $row[1];
}
I found that many people seem to have a problem with using mysql_connect, mysql_query and mysql_fetch_array
.
Here's a compact version swaps value at i1 with i2 in arr
arr.slice(0,i1).concat(arr[i2],arr.slice(i1+1,i2),arr[i1],arr.slice(i2+1))
In recent versions of major browsers you can use backdrop-filter property.
HTML
<div>backdrop blur</div>
CSS
div {
-webkit-backdrop-filter: blur(10px);
backdrop-filter: blur(10px);
}
or if you need different background color for browsers without support:
div {
background-color: rgba(255, 255, 255, 0.9);
}
@supports (-webkit-backdrop-filter: none) or (backdrop-filter: none) {
div {
-webkit-backdrop-filter: blur(10px);
backdrop-filter: blur(10px);
background-color: rgba(255, 255, 255, 0.5);
}
}
Demo: JSFiddle
Docs: Mozilla Developer: backdrop-filter
Is it for me?: CanIUse
I created a category for UIApplication
with visibleViewControllers
property. The main idea is pretty simple. I swizzled viewDidAppear
and viewDidDisappear
methods in UIViewController
. In viewDidAppear
method viewController is added to stack. In viewDidDisappear
method viewController is removed from stack. NSPointerArray
is used instead of NSArray
to store weak UIViewController
’s references . This approach works for any viewControllers hierarchy.
UIApplication+VisibleViewControllers.h
#import <UIKit/UIKit.h>
@interface UIApplication (VisibleViewControllers)
@property (nonatomic, readonly) NSArray<__kindof UIViewController *> *visibleViewControllers;
@end
UIApplication+VisibleViewControllers.m
#import "UIApplication+VisibleViewControllers.h"
#import <objc/runtime.h>
@interface UIApplication ()
@property (nonatomic, readonly) NSPointerArray *visibleViewControllersPointers;
@end
@implementation UIApplication (VisibleViewControllers)
- (NSArray<__kindof UIViewController *> *)visibleViewControllers {
return self.visibleViewControllersPointers.allObjects;
}
- (NSPointerArray *)visibleViewControllersPointers {
NSPointerArray *pointers = objc_getAssociatedObject(self, @selector(visibleViewControllersPointers));
if (!pointers) {
pointers = [NSPointerArray weakObjectsPointerArray];
objc_setAssociatedObject(self, @selector(visibleViewControllersPointers), pointers, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}
return pointers;
}
@end
@implementation UIViewController (UIApplication_VisibleViewControllers)
+ (void)swizzleMethodWithOriginalSelector:(SEL)originalSelector swizzledSelector:(SEL)swizzledSelector {
Method originalMethod = class_getInstanceMethod(self, originalSelector);
Method swizzledMethod = class_getInstanceMethod(self, swizzledSelector);
BOOL didAddMethod = class_addMethod(self, originalSelector, method_getImplementation(swizzledMethod), method_getTypeEncoding(swizzledMethod));
if (didAddMethod) {
class_replaceMethod(self, swizzledSelector, method_getImplementation(originalMethod), method_getTypeEncoding(originalMethod));
} else {
method_exchangeImplementations(originalMethod, swizzledMethod);
}
}
+ (void)load {
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
[self swizzleMethodWithOriginalSelector:@selector(viewDidAppear:)
swizzledSelector:@selector(uiapplication_visibleviewcontrollers_viewDidAppear:)];
[self swizzleMethodWithOriginalSelector:@selector(viewDidDisappear:)
swizzledSelector:@selector(uiapplication_visibleviewcontrollers_viewDidDisappear:)];
});
}
- (void)uiapplication_visibleviewcontrollers_viewDidAppear:(BOOL)animated {
[[UIApplication sharedApplication].visibleViewControllersPointers addPointer:(__bridge void * _Nullable)self];
[self uiapplication_visibleviewcontrollers_viewDidAppear:animated];
}
- (void)uiapplication_visibleviewcontrollers_viewDidDisappear:(BOOL)animated {
NSPointerArray *pointers = [UIApplication sharedApplication].visibleViewControllersPointers;
for (int i = 0; i < pointers.count; i++) {
UIViewController *viewController = [pointers pointerAtIndex:i];
if ([viewController isEqual:self]) {
[pointers removePointerAtIndex:i];
break;
}
}
[self uiapplication_visibleviewcontrollers_viewDidDisappear:animated];
}
@end
https://gist.github.com/medvedzzz/e6287b99011f2437ac0beb5a72a897f0
Swift 3 version
UIApplication+VisibleViewControllers.swift
import UIKit
extension UIApplication {
private struct AssociatedObjectsKeys {
static var visibleViewControllersPointers = "UIApplication_visibleViewControllersPointers"
}
fileprivate var visibleViewControllersPointers: NSPointerArray {
var pointers = objc_getAssociatedObject(self, &AssociatedObjectsKeys.visibleViewControllersPointers) as! NSPointerArray?
if (pointers == nil) {
pointers = NSPointerArray.weakObjects()
objc_setAssociatedObject(self, &AssociatedObjectsKeys.visibleViewControllersPointers, pointers, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC)
}
return pointers!
}
var visibleViewControllers: [UIViewController] {
return visibleViewControllersPointers.allObjects as! [UIViewController]
}
}
extension UIViewController {
private static func swizzleFunc(withOriginalSelector originalSelector: Selector, swizzledSelector: Selector) {
let originalMethod = class_getInstanceMethod(self, originalSelector)
let swizzledMethod = class_getInstanceMethod(self, swizzledSelector)
let didAddMethod = class_addMethod(self, originalSelector, method_getImplementation(swizzledMethod), method_getTypeEncoding(swizzledMethod))
if didAddMethod {
class_replaceMethod(self, swizzledSelector, method_getImplementation(originalMethod), method_getTypeEncoding(originalMethod))
} else {
method_exchangeImplementations(originalMethod, swizzledMethod);
}
}
override open class func initialize() {
if self != UIViewController.self {
return
}
let swizzlingClosure: () = {
UIViewController.swizzleFunc(withOriginalSelector: #selector(UIViewController.viewDidAppear(_:)),
swizzledSelector: #selector(uiapplication_visibleviewcontrollers_viewDidAppear(_:)))
UIViewController.swizzleFunc(withOriginalSelector: #selector(UIViewController.viewDidDisappear(_:)),
swizzledSelector: #selector(uiapplication_visibleviewcontrollers_viewDidDisappear(_:)))
}()
swizzlingClosure
}
@objc private func uiapplication_visibleviewcontrollers_viewDidAppear(_ animated: Bool) {
UIApplication.shared.visibleViewControllersPointers.addPointer(Unmanaged.passUnretained(self).toOpaque())
uiapplication_visibleviewcontrollers_viewDidAppear(animated)
}
@objc private func uiapplication_visibleviewcontrollers_viewDidDisappear(_ animated: Bool) {
let pointers = UIApplication.shared.visibleViewControllersPointers
for i in 0..<pointers.count {
if let pointer = pointers.pointer(at: i) {
let viewController = Unmanaged<AnyObject>.fromOpaque(pointer).takeUnretainedValue() as? UIViewController
if viewController.isEqual(self) {
pointers.removePointer(at: i)
break
}
}
}
uiapplication_visibleviewcontrollers_viewDidDisappear(animated)
}
}
https://gist.github.com/medvedzzz/ee6f4071639d987793977dba04e11399
There are two things that worked for me inside Javascript:
'{{context_variable|escapejs }}'
and other: In views.py
from json import dumps as jdumps
def func(request):
context={'message': jdumps('hello there')}
return render(request,'index.html',context)
and in the html:
{{ message|safe }}
I found an easy way using the new callback refs. You can just pass a callback as a prop to the child component. Like this:
class Container extends React.Component {
constructor(props) {
super(props)
this.setRef = this.setRef.bind(this)
}
setRef(node) {
this.childRef = node
}
render() {
return <Child setRef={ this.setRef }/>
}
}
const Child = ({ setRef }) => (
<div ref={ setRef }>
</div>
)
Here's an example of doing this with a modal:
class Container extends React.Component {
constructor(props) {
super(props)
this.state = {
modalOpen: false
}
this.open = this.open.bind(this)
this.close = this.close.bind(this)
this.setModal = this.setModal.bind(this)
}
open() {
this.setState({ open: true })
}
close(event) {
if (!this.modal.contains(event.target)) {
this.setState({ open: false })
}
}
setModal(node) {
this.modal = node
}
render() {
let { modalOpen } = this.state
return (
<div>
<button onClick={ this.open }>Open</button>
{
modalOpen ? <Modal close={ this.close } setModal={ this.setModal }/> : null
}
</div>
)
}
}
const Modal = ({ close, setModal }) => (
<div className='modal' onClick={ close }>
<div className='modal-window' ref={ setModal }>
</div>
</div>
)
As someone who has worked with ASP.NET API for about 3 years, I'd recommend returning an HttpResponseMessage instead. Don't use the ActionResult or IEnumerable!
ActionResult is bad because as you've discovered.
Return IEnumerable<> is bad because you may want to extend it later and add some headers, etc.
Using JsonResult is bad because you should allow your service to be extendable and support other response formats as well just in case in the future; if you seriously want to limit it you can do so using Action Attributes, not in the action body.
public HttpResponseMessage GetAllNotificationSettings()
{
var result = new List<ListItems>();
// Filling the list with data here...
// Then I return the list
return Request.CreateResponse(HttpStatusCode.OK, result);
}
In my tests, I usually use the below helper method to extract my objects from the HttpResponseMessage:
public class ResponseResultExtractor
{
public T Extract<T>(HttpResponseMessage response)
{
return response.Content.ReadAsAsync<T>().Result;
}
}
var actual = ResponseResultExtractor.Extract<List<ListItems>>(response);
In this way, you've achieved the below:
Look at this: http://www.asp.net/web-api/overview/formats-and-model-binding/content-negotiation
When you malloc(sizeof(struct_name))
it automatically allocates memory for the full size of the struct, you don't need to malloc each element inside.
Use -fsanitize=address
flag to check how you used your program memory.
I did this in my project and it works like a charm
Date now = new Date();
System.out.println(now);
TimeZone.setDefault(TimeZone.getTimeZone("UTC")); // The magic is here
System.out.println(now);
You can use CSS white-space
property for \n
. You can also preserve the tabs as in \t
.
For line break \n
:
white-space: pre-line;
For line break \n
and tabs \t
:
white-space: pre-wrap;
document.getElementById('just-line-break').innerHTML = 'Testing 1\nTesting 2\n\tNo tab';_x000D_
_x000D_
document.getElementById('line-break-and-tab').innerHTML = 'Testing 1\nTesting 2\n\tWith tab';
_x000D_
#just-line-break {_x000D_
white-space: pre-line;_x000D_
}_x000D_
_x000D_
#line-break-and-tab {_x000D_
white-space: pre-wrap;_x000D_
}
_x000D_
<div id="just-line-break"></div>_x000D_
_x000D_
<br/>_x000D_
_x000D_
<div id="line-break-and-tab"></div>
_x000D_
COPY description_f (id, name) FROM 'absolutepath\test.txt' WITH (FORMAT csv, HEADER true, DELIMITER ' ');
Example
COPY description_f (id, name) FROM 'D:\HIVEWORX\COMMON\TermServerAssets\Snomed2021\SnomedCT\Full\Terminology\sct2_Description_Full_INT_20210131.txt' WITH (FORMAT csv, HEADER true, DELIMITER ' ');
You need to use "\n"
not '\n'
in your gsub. The different quote marks behave differently.
Double quotes "
allow character expansion and expression interpolation ie. they let you use escaped control chars like \n
to represent their true value, in this case, newline, and allow the use of #{expression}
so you can weave variables and, well, pretty much any ruby expression you like into the text.
While on the other hand, single quotes '
treat the string literally, so there's no expansion, replacement, interpolation or what have you.
In this particular case, it's better to use either the .delete
or .tr
String method to delete the newlines.
This should work for all PHP versions. It determines the PHP version, then checks to see if the session is started based on the PHP version. Then if the session is not started it starts it.
function start_session() {
if(version_compare(phpversion(), "5.4.0") != -1){
if (session_status() == PHP_SESSION_NONE) {
session_start();
}
} else {
if(session_id() == '') {
session_start();
}
}
}
You just need to specify which columns you're inserting directly into:
INSERT INTO [dbo].[rLicenses] ([Name]) VALUES ('test')
Views can be picky like that.
If the output of MAX(CreationDate) is not wanted - like in the example of the original question - the only answer is the second statement of Prashant Gupta's answer:
SELECT [Category] FROM [MonitoringJob]
GROUP BY [Category] ORDER BY MAX([CreationDate]) DESC
Explanation: you can't use the ORDER BY clause in an inline function, so the statement in the answer of Prutswonder is not useable in this case, you can't put an outer select around it and discard the MAX(CreationDate) part.
import ImageGrab
img = ImageGrab.grab()
img.save('test.jpg','JPEG')
this requires Python Imaging Library
You can inject dependencies in attributes like AuthorizeAttribute in this way
var someservice = (ISomeService)context.HttpContext.RequestServices.GetService(typeof(ISomeService));
You can use the Window object and access it everwhere. example window.defaultTitle = "my title"; then you can access window.defaultTitle without importing anything.
I am on Ubuntu 18.04 and got the same error, was worried for weeks too. Finally realized that gpg2 is not pointing towards anything. So simply run
git config --global gpg.program gpg
And tada, it works like charm.
Your commits will now have verified tag with them.
Try this one.
ALTER TABLE tb_TableName
ALTER COLUMN Record_Status VARCHAR(20) NOT NULL
ALTER TABLE tb_TableName
ADD CONSTRAINT DEF_Name DEFAULT '' FOR Record_Status
The correct form, based on the original syntax, and correctly normalized is:
def gaussian(x, mu, sig):
return 1./(np.sqrt(2.*np.pi)*sig)*np.exp(-np.power((x - mu)/sig, 2.)/2)
Its a late answer, but as I can see most of the people mentioned about "refresh" method to redirect a webpage. As per W3C, we should not use "refresh" to redirect. Because it could break the "back" button. Imagine that the user presses the "back" button, the refresh would work again, and the user would bounce forward. The user will most likely get very annoyed, and close the window, which is probably not what you, as the author of this page, want.
Use HTTP redirects instead. One can refer the complete documentation here: W3C document
i always use this cheap word for vertical spaces.
<p>Q1</p>
<br>
<p>Q2</p>
if you are running on Apple MacBook OSX
then:
my.cnf
. (For me it was placed @
/Applications/XAMPP/xamppfiles/etc
. You can just search if you
can't find it).my.cnf
file in any text editor."skip-grant-tables"
(without quotes) at the end of [mysqld]
section and save the file.skip-grant-tables
option.Do what you want now!!
PS: Please remove skip-grant-tables
from my.cnf
file once you are done with whatsoever you want to do ELSE MySQL server will always run without access grants.
I have used the code of Oliver Crow (link given by Andrew Hare) and adapted it a bit to tailor Python 2.7.3. (by using timeit package). I ran on my personal computer, Lenovo T61, 6GB RAM, Debian GNU/Linux 6.0.6 (squeeze).
Here is the result for 10,000 iterations:
method1: 0.0538418292999 secs process size 4800 kb method2: 0.22602891922 secs process size 4960 kb method3: 0.0605459213257 secs process size 4980 kb method4: 0.0544030666351 secs process size 5536 kb method5: 0.0551080703735 secs process size 5272 kb method6: 0.0542731285095 secs process size 5512 kb
and for 5,000,000 iterations (method 2 was ignored because it ran tooo slowly, like forever):
method1: 5.88603997231 secs process size 37976 kb method3: 8.40748500824 secs process size 38024 kb method4: 7.96380496025 secs process size 321968 kb method5: 8.03666186333 secs process size 71720 kb method6: 6.68192911148 secs process size 38240 kb
It is quite obvious that Python guys have done pretty great job to optimize string concatenation, and as Hoare said: "premature optimization is the root of all evil" :-)
I faced the problem with my Jenkins. When I have renewed the certificate I started facing this error.
stderr fatal: unable to access server certificate verification failed. CAfile: /etc/ssl/certs/ca-certificates.crt
So I have added my new certificate in the following file:
/etc/ssl/certs/ca-certificates.crt
The content of that file looks like this:
-----BEGIN CERTIFICATE-----
blahblha
-----END CERTIFICATE-----
-----BEGIN CERTIFICATE-----
blahblha
-----END CERTIFICATE-----
-----BEGIN CERTIFICATE-----
blahblha
-----END CERTIFICATE-----
Just append your certificate in the bottom:
-----BEGIN CERTIFICATE-----
blahblha
-----END CERTIFICATE-----
This is simple solution, which is using range function to pick alternative elements from a list of elements.
Note: This is only valid for an even numbered list.
a_list = [1, 2, 3, 4, 5, 6]
empty_list = []
for i in range(0, len(a_list), 2):
empty_list.append(a_list[i] + a_list[i + 1])
print(empty_list)
# [3, 7, 11]
Found a similar way to fix this issue (at least it did for me).
First check where the CLI php.ini
is located:
php -i | grep "php.ini"
In my case I ended up with : Configuration File (php.ini) Path => /etc
Then cd ..
all the way back and cd
into /etc
, do ls
in my case php.ini didn't show up, only a php.ini.default
Now, copy the php.ini.default file named as php.ini:
sudo cp php.ini.default php.ini
In order to edit, change the permissions of the file:
sudo chmod ug+w php.ini
sudo chgrp staff php.ini
Open directory and edit the php.ini file:
open .
Tip: If you are not able to edit the php.ini due to some permissions issue then copy 'php.ini.default' and paste it on your desktop and rename it to 'php.ini' then open it and edit it following step 7. Then move (copy+paste) it in /etc folder. Issue will be resolved.
Search for [Date] and make sure the following line is in the correct format:
date.timezone = "Europe/Amsterdam"
I hope this could help you out.
If you are fine using a graphical tool this works very well:
gitk <file>
gitk now shows all commits where the file has been updated. Marking a commit will show you the diff against the previous commit in the list. This also works for directories, but then you also get to select the file to diff for the selected commit. Super useful!
Use -e
option, then you can print new line character with \n
in the string.
Sample (but not sure whether a good one or not)
The fun thing is that -e
option is not documented in MacOS's man page while still usable. It is documented in the man page of Linux.
My understanding is that Oracle JDK can't be used in production, therefore I cannot legally use it (without paying), for the web application I am building for my company. I have to use OpenJDK. Please correct me if I am wrong! From this article.
Starting with Java 11, the Oracle JDK is restricted to development and testing environments. Oracle JDKs may only be used in production if you buy the commercial support. Instead, Oracle will provide Java builds based on OpenJDK for free which can be used in production. But for the official Oracle JDK the real roadmap will look like this:
UPDATE: I'm wrong. I can use Oracle JDK for free but won't get security updates after 6 mos and we'll have to assume the risk. Look at the above linked article section "What does the new release train mean to my company?".
Here are my findings:
JavaScript: The Definitive Guide, written by David Flanagan provides a very concise explanation:
JavaScript was created at Netscape in the early days of the Web, and technically, "JavaScript" is a trademark licensed from Sun Microsystems (now Oracle) used to describe Netscape's (now Mozilla's) implementation of the language. Netscape submitted the language for standardization to ECMA and because of trademark issues, the standardized version of the language was stuck with the awkward name "ECMAScript". For the same trademark reasons, Microsoft's version of the language is formally known as "JScript". In practice, just about everyone calls the language JavaScript.
A blog post by Microsoft seems to agree with what Flanagan explains by saying..
ECMAScript is the official name for the JavaScript language we all know and love.
.. which makes me think all occurrences of JavaScript
in this reference post (by Microsoft again) must be replaced by ECMASCript
. They actually seem to be careful with using ECMAScript
only in this, more recent and more technical documentation page.
w3schools.com seems to agree with the definitions above:
JavaScript was invented by Brendan Eich in 1995, and became an ECMA standard in 1997. ECMA-262 is the official name of the standard. ECMAScript is the official name of the language.
The key here is: the official name of the language.
If you check Mozilla 's JavaScript version pages, you will encounter the following statement:
Deprecated. The explicit versioning and opt-in of language features was Mozilla-specific and are in process of being removed. Firefox 4 was the last version which referred to a JavaScript version (1.8.5). With new ECMA standards, JavaScript language features are now often mentioned with their initial definition in ECMA-262 Editions such as ECMAScript 2015.
and when you see the recent release notes, you will always see reference to ECMAScript standards, such as:
The ES2015 Symbol.toStringTag property has been implemented (bug 1114580).
The ES2015 TypedArray.prototype.toString() and TypedArray.prototype.toLocaleString() methods have been implemented (bug 1121938).
Mozilla Web Docs also has a page that explains the difference between ECMAScript and JavaScript:
However, the umbrella term "JavaScript" as understood in a web browser context contains several very different elements. One of them is the core language (ECMAScript), another is the collection of the Web APIs, including the DOM (Document Object Model).
Conclusion
To my understanding, people use the word JavaScript somewhat liberally to refer to the core ECMAScript specification.
I would say, all the modern JavaScript implementations (or JavaScript Engines) are in fact ECMAScript implementations. Check the definition of the V8 Engine from Google, for example:
V8 is Google’s open source high-performance JavaScript engine, written in C++ and used in Google Chrome, the open source browser from Google, and in Node.js, among others. It implements ECMAScript as specified in ECMA-262.
They seem to use the word JavaScript and ECMAScript interchangeably, and I would say it is actually an ECMAScript engine?
So most JavaScript Engines are actually implementing the ECMAScript standard, but instead of calling them ECMAScript engines, they call themselves JavaScript Engines. This answer also supports the way I see the situation.
REASON WHY THIS HAPPENS (EXPLANATION)
suppose we have 2 tables users and subscription.
1 user has 1 subscription
IN USER MODEL, we have
public function subscription()
{
return $this->hasOne('App\Subscription','user_id');
}
we can access subscription details as follows
$users = User:all();
foreach($users as $user){
echo $user->subscription;
}
if any of the user does not have a subscription, which can be a case. we cannot use arrow function further after subscription like below
$user->subscription->abc [this will not work]
$user->subscription['abc'] [this will work]
but if the user has a subscription
$user->subscription->abc [this will work]
NOTE: try putting a if condition like this
if($user->subscription){
return $user->subscription->abc;
}
Mystring[0]
should be enough
The simplest code I could get to is:
#for attachment email
from django.core.mail import EmailMessage
def attachment_email(request):
email = EmailMessage(
'Hello', #subject
'Body goes here', #body
'[email protected]', #from
['[email protected]'], #to
['[email protected]'], #bcc
reply_to=['[email protected]'],
headers={'Message-ID': 'foo'},
)
email.attach_file('/my/path/file')
email.send()
It was based on the official Django documentation
Specifically how do I tell spring-data-jpa that users that have the same username and firstname are actually EQUAL and that it is supposed to update the entity. Overriding equals did not work.
For this particular purpose one can introduce a composite key like this:
CREATE TABLE IF NOT EXISTS `test`.`user` (
`username` VARCHAR(45) NOT NULL,
`firstname` VARCHAR(45) NOT NULL,
`description` VARCHAR(45) NOT NULL,
PRIMARY KEY (`username`, `firstname`))
Mapping:
@Embeddable
public class UserKey implements Serializable {
protected String username;
protected String firstname;
public UserKey() {}
public UserKey(String username, String firstname) {
this.username = username;
this.firstname = firstname;
}
// equals, hashCode
}
Here is how to use it:
@Entity
public class UserEntity implements Serializable {
@EmbeddedId
private UserKey primaryKey;
private String description;
//...
}
JpaRepository would look like this:
public interface UserEntityRepository extends JpaRepository<UserEntity, UserKey>
Then, you could use the following idiom: accept DTO with user info, extract name and firstname and create UserKey, then create a UserEntity with this composite key and then invoke Spring Data save() which should sort everything out for you.
I doubt I'd use it in a mission-critical system, but Derby has always been very interesting to me.
site-packages
directory where pip is installing your packages.psycopg2
directory).pip install YOUR-PACKAGE
Just had to delete all inputs within a div & using the colon in front of the input when targeting gets most everything.
$('#divId').find(':input').val('');
If you are utilizing arrays too much then you should include cstring.h
because it has too many functions including finding substrings.
For displaying short, formatted text that doesn't need to be editable, Core Text is the way to go. There are several open-source projects for labels that use NSAttributedString
and Core Text for rendering. See CoreTextAttributedLabel or OHAttributedLabel for example.
Try this:
private void Button1_Click(Object sender, EventArgs e )
{
var myForm = new Form1();
myForm.Show();
}
If you have access to the code that creates the canvas - simply call the function right there after the canvas is created.
If you have no access to that code (eg. If it is a 3rd party code such as google maps) then what you could do is test for the existence in an interval:
var checkExist = setInterval(function() {
if ($('#the-canvas').length) {
console.log("Exists!");
clearInterval(checkExist);
}
}, 100); // check every 100ms
But note - many times 3rd party code has an option to activate your code (by callback or event triggering) when it finishes to load. That may be where you can put your function. The interval solution is really a bad solution and should be used only if nothing else works.
My issue was, i am unable to create a view with my "scott" user in oracle 11g edition. So here is my solution for this
Error in my case
SQL>create view v1 as select * from books where id=10;
insufficient privileges.
Solution
1)open your cmd and change your directory to where you install your oracle database. in my case i was downloaded in E drive so my location is E:\app\B_Amar\product\11.2.0\dbhome_1\BIN> after reaching in the position you have to type sqlplus sys as sysdba
E:\app\B_Amar\product\11.2.0\dbhome_1\BIN>sqlplus sys as sysdba
2) Enter password: here you have to type that password that you give at the time of installation of oracle software.
3) Here in this step if you want create a new user then you can create otherwise give all the privileges to existing user.
for creating new user
SQL> create user abc identified by xyz;
here abc is user and xyz is password.
giving all the privileges to abc user
SQL> grant all privileges to abc;
grant succeeded.
if you are seen this message then all the privileges are giving to the abc user.
4) Now exit from cmd, go to your SQL PLUS and connect to the user i.e enter your username & password.Now you can happily create view.
In My case
in cmd E:\app\B_Amar\product\11.2.0\dbhome_1\BIN>sqlplus sys as sysdba
SQL> grant all privileges to SCOTT;
grant succeeded.
Now I can create views.
git branch --set-upstream <remote-branch>
sets the default remote branch for the current local branch.
Any future git pull
command (with the current local branch checked-out),
will attempt to bring in commits from the <remote-branch>
into the current local branch.
One way to avoid having to explicitly type --set-upstream
is to use its shorthand flag -u
as follows:
git push -u origin local-branch
This sets the upstream association for any future push/pull attempts automatically.
For more details, checkout this detailed explanation about upstream branches and tracking.
To avoid confusion, recent versions of
git
deprecate this somewhat ambiguous--set-upstream
option in favour of a more verbose--set-upstream-to
option with identical syntax and behaviourgit branch --set-upstream-to <origin/remote-branch>
what you could do is take the name with you in the class and make a dictionairy:
class A:
def __init__(self, name):
self.name=name
def kill(self)
del dict[self.name]
dict={}
dict["a"]=A("a")
dict["a"].kill()
Given
volumes:
- /dir/on/host:/var/www/html
if /dir/on/host
doesn't exist, it is created on the host and the empty content is mounted in the container at /var/www/html
. Whatever content you had before in /var/www/html
inside the container is inaccessible, until you unmount the volume; the new mount is hiding the old content.
Nothing quite worked for me (I think it was because my input .mp4 video didn't had any audio) so I found this worked for me:
ffmpeg -i input_video.mp4 -i balipraiavid.wav -map 0:v:0 -map 1:a:0 output.mp4
As Distdev alluded to, you still need to differentiate the input type. That is to say,
$(this).prev().prop('tagName');
will tell you input
, but that doesn't differentiate between checkbox/text/radio. If it's an input, you can then use
$('#elementId').attr('type');
to tell you checkbox/text/radio, so you know what kind of control it is.
I had this problem a couple hours ago when I exported my projects from Eclipse to Android Studio. Unfortunately, the top answers here didn't work for me.
Anyway, creating a new project instead of opening an old one did the trick for me as what Thomas Kaliakos mentioned on his comment here
I had to mess around with the project..and at some point it worked. I don't know how though. My guess would be that creating a new project and adding your source code would work every time. Sorry for not being very clear, but honestly I was surprized even myself that it worked. – Thomas Kaliakos Oct 15 '13 at 4:08
I tested this code and Works
Javascript
<script>
$(document).ready(function() {
$('#summernote').summernote({
height: 200,
onImageUpload: function(files, editor, welEditable) {
sendFile(files[0], editor, welEditable);
}
});
function sendFile(file, editor, welEditable) {
data = new FormData();
data.append("file", file);
$.ajax({
data: data,
type: "POST",
url: "Your URL POST (php)",
cache: false,
contentType: false,
processData: false,
success: function(url) {
editor.insertImage(welEditable, url);
}
});
}
});
</script>
PHP
if ($_FILES['file']['name']) {
if (!$_FILES['file']['error']) {
$name = md5(rand(100, 200));
$ext = pathinfo($_FILES['file']['name'], PATHINFO_EXTENSION);
$filename = $name.
'.'.$ext;
$destination = '/assets/images/'.$filename; //change this directory
$location = $_FILES["file"]["tmp_name"];
move_uploaded_file($location, $destination);
echo 'http://test.yourdomain.al/images/'.$filename; //change this URL
} else {
echo $message = 'Ooops! Your upload triggered the following error: '.$_FILES['file']['error'];
}
}
Update:
After 0.7.0 onImageUpload
should be inside callbacks
option as mentioned by @tugberk
$('#summernote').summernote({
height: 200,
callbacks: {
onImageUpload: function(files, editor, welEditable) {
sendFile(files[0], editor, welEditable);
}
}
});
tools:replace="android:supportsRtl,android:allowBackup,icon,label">
GRANT ALL ON *.* to user@'%' IDENTIFIED BY 'password';
Will allow a specific user to log on from anywhere.
It's bad because it removes some security control, i.e. if an account is compromised.
Go to view and press "Switch to scale mode" which will adjust the virtual screen when you adjust the application.
You could use a semaphore.
While the condition is not met, another thread acquires the semaphore.
Your thread would try to acquire it with acquireUninterruptibly()
or tryAcquire(int permits, long timeout, TimeUnit unit)
and would be blocked.
When the condition is met, the semaphore is also released and your thread would acquire it.
You could also try using a SynchronousQueue
or a CountDownLatch
.
As others have answered, scatter()
or plot()
will generate the plot you want. I suggest two refinements to answers that are already here:
Use numpy to create the x-coordinate list and y-coordinate list. Working with large data sets is faster in numpy than using the iteration in Python suggested in other answers.
Use pyplot to apply the logarithmic scale rather than operating directly on the data, unless you actually want to have the logs.
import matplotlib.pyplot as plt
import numpy as np
data = [(2, 10), (3, 100), (4, 1000), (5, 100000)]
data_in_array = np.array(data)
'''
That looks like array([[ 2, 10],
[ 3, 100],
[ 4, 1000],
[ 5, 100000]])
'''
transposed = data_in_array.T
'''
That looks like array([[ 2, 3, 4, 5],
[ 10, 100, 1000, 100000]])
'''
x, y = transposed
# Here is the OO method
# You could also the state-based methods of pyplot
fig, ax = plt.subplots(1,1) # gets a handle for the AxesSubplot object
ax.plot(x, y, 'ro')
ax.plot(x, y, 'b-')
ax.set_yscale('log')
fig.show()
I've also used ax.set_xlim(1, 6)
and ax.set_ylim(.1, 1e6)
to make it pretty.
I've used the object-oriented interface to matplotlib. Because it offers greater flexibility and explicit clarity by using names of the objects created, the OO interface is preferred over the interactive state-based interface.
JS provides the tools to do this the right way. Try the demo snippet.
var doc = document;_x000D_
var buttons = doc.getElementsByTagName('button');_x000D_
var button = buttons[0];_x000D_
_x000D_
button.addEventListener("mouseover", function(){_x000D_
this.classList.add('mouse-over');_x000D_
});_x000D_
_x000D_
button.addEventListener("mouseout", function(){_x000D_
this.classList.remove('mouse-over');_x000D_
});_x000D_
_x000D_
button.addEventListener("mousedown", function(){_x000D_
this.classList.add('mouse-down');_x000D_
});_x000D_
_x000D_
button.addEventListener("mouseup", function(){_x000D_
this.classList.remove('mouse-down');_x000D_
alert('Button Clicked!');_x000D_
});_x000D_
_x000D_
//this is unrelated to button styling. It centers the button._x000D_
var box = doc.getElementById('box');_x000D_
var boxHeight = window.innerHeight;_x000D_
box.style.height = boxHeight + 'px';
_x000D_
button{_x000D_
text-transform: uppercase;_x000D_
background-color:rgba(66, 66, 66,0.3);_x000D_
border:none;_x000D_
font-size:4em;_x000D_
color:white;_x000D_
-webkit-box-shadow: 0px 10px 5px -4px rgba(0,0,0,0.33);_x000D_
-moz-box-shadow: 0px 10px 5px -4px rgba(0,0,0,0.33);_x000D_
box-shadow: 0px 10px 5px -4px rgba(0,0,0,0.33);_x000D_
}_x000D_
button:focus {_x000D_
outline:0;_x000D_
}_x000D_
.mouse-over{_x000D_
background-color:rgba(66, 66, 66,0.34);_x000D_
}_x000D_
.mouse-down{_x000D_
-webkit-box-shadow: 0px 6px 5px -4px rgba(0,0,0,0.52);_x000D_
-moz-box-shadow: 0px 6px 5px -4px rgba(0,0,0,0.52);_x000D_
box-shadow: 0px 6px 5px -4px rgba(0,0,0,0.52); _x000D_
}_x000D_
_x000D_
/* unrelated to button styling */_x000D_
#box {_x000D_
display: flex;_x000D_
flex-flow: row nowrap ;_x000D_
justify-content: center;_x000D_
align-content: center;_x000D_
align-items: center;_x000D_
width:100%;_x000D_
}_x000D_
_x000D_
button {_x000D_
order:1;_x000D_
flex: 0 1 auto;_x000D_
align-self: auto;_x000D_
min-width: 0;_x000D_
min-height: auto;_x000D_
} _x000D_
_x000D_
_x000D_
_x000D_
<!DOCTYPE html>_x000D_
<html lang="en">_x000D_
<head>_x000D_
<meta charset=utf-8 />_x000D_
<meta name="description" content="3d Button Configuration" />_x000D_
</head>_x000D_
_x000D_
<body>_x000D_
<section id="box">_x000D_
<button>_x000D_
Submit_x000D_
</button>_x000D_
</section>_x000D_
</body>_x000D_
</html>
_x000D_
Here is a very good way to handle this (found on ozgrid):
Let's say your list is on Sheet2
and you wish to use the Validation List with AutoComplete on Sheet1
.
On Sheet1
A1
Enter =Sheet2!A1
and copy down including as many spare rows as needed (say 300 rows total). Hide these rows and use this formula in the Refers to: for a dynamic named range called MyList:
=OFFSET(Sheet1!$A$1,0,0,MATCH("*",Sheet1!$A$1:$A$300,-1),1)
Now in the cell immediately below the last hidden row use Data Validation and for the List Source use =MyList
[EDIT] Adapted version for Excel 2007+ (couldn't test on 2010 though but AFAIK, there is nothing really specific to a version).
Let's say your data source is on Sheet2!A1:A300
and let's assume your validation list (aka autocomplete) is on cell Sheet1!A1
.
Create a dynamic named range MyList
that will depend on the value of the cell where you put the validation
=OFFSET(Sheet2!$A$1,MATCH(Sheet1!$A$1&"*",Sheet2!$A$1:$A$300,0)-1,0,COUNTA(Sheet2!$A:$A))
Add the validation list on cell Sheet1!A1
that will refert to the list =MyList
Caveats
This is not a real autocomplete as you have to type first and then click on the validation arrow : the list will then begin at the first matching element of your list
The list will go till the end of your data. If you want to be more precise (keep in the list only the matching elements), you can change the COUNTA
with a SUMLPRODUCT
that will calculate the number of matching elements
Your source list must be sorted
Here are the selectors used in BS3, if you want to stay consistent:
@media(max-width:767px){}
@media(min-width:768px){}
@media(min-width:992px){}
@media(min-width:1200px){}
Note: FYI, this may be useful for debugging:
<span class="visible-xs">SIZE XS</span>
<span class="visible-sm">SIZE SM</span>
<span class="visible-md">SIZE MD</span>
<span class="visible-lg">SIZE LG</span>
Here are the selectors used in BS4. There is no "lowest" setting in BS4 because "extra small" is the default. I.e. you would first code the XS size and then have these media overrides afterwards.
@media(min-width:576px){}
@media(min-width:768px){}
@media(min-width:992px){}
@media(min-width:1200px){}
Update 2019-02-11: BS3 info is still accurate as of version 3.4.0, updated BS4 for new grid, accurate as of 4.3.0.
To get it into a variable, the easiest way is:
export GIT_REV_COUNT=`git rev-list --all --count`
Somewhere in your project, typically main.js or router.js
import Router from 'vue-router'
Router.prototype.open = function (routeObject) {
const {href} = this.resolve(routeObject)
window.open(href, '_blank')
}
In your component:
<div @click="$router.open({name: 'User', params: {ID: 123}})">Open in new tab</div>
It can't parse that string because "UTC" is not a valid time zone designator.
UTC time is denoted by adding a 'Z' to the end of the time string, so your parsing code should look like this:
DateTime.Parse("Tue, 1 Jan 2008 00:00:00Z");
From the Wikipedia article on ISO 8601
If the time is in UTC, add a 'Z' directly after the time without a space. 'Z' is the zone designator for the zero UTC offset. "09:30 UTC" is therefore represented as "09:30Z" or "0930Z". "14:45:15 UTC" would be "14:45:15Z" or "144515Z".
UTC time is also known as 'Zulu' time, since 'Zulu' is the NATO phonetic alphabet word for 'Z'.
It depends on what you're doing.
After Python 2.5, string concatenation with the + operator is pretty fast. If you're just concatenating a couple of values, using the + operator works best:
>>> x = timeit.Timer(stmt="'a' + 'b'")
>>> x.timeit()
0.039999961853027344
>>> x = timeit.Timer(stmt="''.join(['a', 'b'])")
>>> x.timeit()
0.76200008392333984
However, if you're putting together a string in a loop, you're better off using the list joining method:
>>> join_stmt = """
... joined_str = ''
... for i in xrange(100000):
... joined_str += str(i)
... """
>>> x = timeit.Timer(join_stmt)
>>> x.timeit(100)
13.278000116348267
>>> list_stmt = """
... str_list = []
... for i in xrange(100000):
... str_list.append(str(i))
... ''.join(str_list)
... """
>>> x = timeit.Timer(list_stmt)
>>> x.timeit(100)
12.401000022888184
...but notice that you have to be putting together a relatively high number of strings before the difference becomes noticeable.
As string data types have variable length, it is by default stored as object type. I faced this problem after treating missing values too. Converting all those columns to type 'category' before label encoding worked in my case.
df[cat]=df[cat].astype('category')
And then check df.dtypes and perform label encoding.
I've found this absolutely invaluable when unable to grab something in a custom class or changing id's:
driver.find_element_by_xpath("//*[contains(text(), 'Show Next Date Available')]").click()
driver.find_element_by_xpath("//*[contains(text(), 'Show Next Date Available')]").text
driver.find_element_by_xpath("//*[contains(text(), 'Available')]").text
driver.find_element_by_xpath("//*[contains(text(), 'Avail')]").text
use dynamic sql
BEGIN
DECLARE
maxId NUMBER;
BEGIN
SELECT MAX(id)+1
INTO maxId
FROM table_name;
execute immediate('CREATE SEQUENCE sequane_name MINVALUE '||maxId||' START WITH '||maxId||' INCREMENT BY 1 NOCACHE NOCYCLE');
END;
END;
You explained the difference correctly. It just depends on if you want x to increment before every run through a loop, or after that. It depends on your program logic, what is appropriate.
An important difference when dealing with STL-Iterators (which also implement these operators) is, that it++ creates a copy of the object the iterator points to, then increments, and then returns the copy. ++it on the other hand does the increment first and then returns a reference to the object the iterator now points to. This is mostly just relevant when every bit of performance counts or when you implement your own STL-iterator.
Edit: fixed the mixup of prefix and suffix notation
There are two things
Disable firewall if any or add exception or check if u have correct driver file. Disable any antivirus if any
and also make sure your driver type is mysql.jdbc.driver
.
If we have:
enum Gender
{
M = 0,
F = 1,
U = 2
}
and
enum Gender2
{
Male = 0,
Female = 1,
Unknown = 2
}
We can safely do
var gender = Gender.M;
var gender2 = (Gender2)(int)gender;
Or even
var enumOfGender2Type = (Gender2)0;
If you want to cover the case where an enum on the right side of the '=' sign has more values than the enum on the left side - you will have to write your own method/dictionary to cover that as others suggested.
For me the main difference was the declaration of the function....
INSTEAD OF
function initMap() {
...
}
THIS WORKED
window.initMap = function () {
...
}
You could use the stopifnot()
function if you want the program to produce an error:
foo <- function(x) {
stopifnot(x > 500)
# rest of program
}
It depends how much you want to customize the alert dialog. I have different steps in order to customize the alert dialog. Please visit: https://stackoverflow.com/a/33439849/5475941
Googled "Permission denied (publickey). fatal: The remote end hung up unexpectedly", first result an exact SO dupe:
GitHub: Permission denied (publickey). fatal: The remote end hung up unexpectedly which links here in the accepted answer (from the original poster, no less): http://help.github.com/linux-set-up-git/
EDIT
I want to add the reason that your IF
statement seems to not work. When you do an EXISTS
on an aggregate, it's always going to be true
. It returns a value even if the ID
doesn't exist. Sure, it's NULL
, but its returning it. Instead, do this:
if exists(select 1 from table where id = 4)
and you'll get to the ELSE
portion of your IF
statement.
Now, here's a better, set-based solution:
update b
set code = isnull(a.value, 123)
from #b b
left join (select id, max(value) from #a group by id) a
on b.id = a.id
where
b.id = yourid
This has the benefit of being able to run on the entire table rather than individual ids.
Use the input()
built-in function to get a input line from the user.
You can read the help here.
You can use the following code to get several line at once (finishing by an empty one):
while input() != '':
do_thing
For each document, the update operator $set
can set multiple values, so rather than replacing the entire object in the items
array, you can set the name
and value
fields of the object individually.
{'$set': {'items.$.name': update.name , 'items.$.value': update.value}}
Here is the short sweet answer using HtmlAgilityPack. You can run this in LinqPad.
var html = "<div>..whatever html</div>";
var doc = new HtmlAgilityPack.HtmlDocument();
doc.LoadHtml(html);
var plainText = doc.DocumentNode.InnerText;
I simply use HtmlAgilityPack in any .NET project that needs HTML parsing. It's simple, reliable, and fast.
for i in iterator:
try:
# Do something.
pass
except:
# Continue to next iteration.
continue
Max length will not work with <input type="number"
the best way i know is to use oninput
event to limit the maxlength. Please see the below code for simple implementation.
<input name="somename"
oninput="javascript: if (this.value.length > this.maxLength) this.value = this.value.slice(0, this.maxLength);"
type = "number"
maxlength = "6"
/>
Let me clarify two points here :
(a = 'b',c)
in function.
The correct order of defining parameter in function are :(a,b,c)
(a = 'b',r= 'j')
(*args)
(**kwargs)
def example(a, b, c=None, r="w" , d=[], *ae, **ab):
(a,b)
are positional parameter
(c=none)
is optional parameter
(r="w")
is keyword parameter
(d=[])
is list parameter
(*ae)
is keyword-only
(*ab)
is var-keyword parameter
so first re-arrange your parameters
so second remove this "len1 = hgt"
it's not allowed in python.
keep in mind the difference between argument and parameters.
from eclipse, you can select on the project, right click->team->upgrade
.do comes from the Struts framework. See this question: Why do Java webapps use .do extension? Where did it come from? Also you can change what your urls look like using mod_rewrite (on Apache).
This is the solution that worked for me
https://gist.github.com/elidickinson/5525752#gistcomment-1649300, thanks to @philipp-klinz
<table cellpadding="0" cellspacing="0" border="0" style="padding:0px;margin:0px;width:100%;">
<tr><td colspan="3" style="padding:0px;margin:0px;font-size:20px;height:20px;" height="20"> </td></tr>
<tr>
<td style="padding:0px;margin:0px;"> </td>
<td style="padding:0px;margin:0px;" width="560"><!-- max width goes here -->
<!-- PLACE CONTENT HERE -->
</td>
<td style="padding:0px;margin:0px;"> </td>
</tr>
<tr><td colspan="3" style="padding:0px;margin:0px;font-size:20px;height:20px;" height="20"> </td></tr>
</table>
The prefix "Local" in JSR-310 (aka java.time-package in Java-8) does not indicate that there is a timezone information in internal state of that class (here: LocalDateTime
). Despite the often misleading name such classes like LocalDateTime
or LocalTime
have NO timezone information or offset.
You tried to format such a temporal type (which does not contain any offset) with offset information (indicated by pattern symbol Z). So the formatter tries to access an unavailable information and has to throw the exception you observed.
Solution:
Use a type which has such an offset or timezone information. In JSR-310 this is either OffsetDateTime
(which contains an offset but not a timezone including DST-rules) or ZonedDateTime
. You can watch out all supported fields of such a type by look-up on the method isSupported(TemporalField).. The field OffsetSeconds
is supported in OffsetDateTime
and ZonedDateTime
, but not in LocalDateTime
.
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMdd HH:mm:ss.SSSSSS Z");
String s = ZonedDateTime.now().format(formatter);
If you want a simple regex then it won't be accurate. https://www.freeformatter.com/java-regex-tester.html#ad-output offers a tool to test your Java regex. Also, at the bottom you can find some suggested regexes for validating a date.
ISO date format (yyyy-mm-dd):
^[0-9]{4}-(((0[13578]|(10|12))-(0[1-9]|[1-2][0-9]|3[0-1]))|(02-(0[1-9]|[1-2][0-9]))|((0[469]|11)-(0[1-9]|[1-2][0-9]|30)))$
ISO date format (yyyy-mm-dd) with separators '-' or '/' or '.' or ' '. Forces usage of same separator accross date.
^[0-9]{4}([- /.])(((0[13578]|(10|12))\1(0[1-9]|[1-2][0-9]|3[0-1]))|(02\1(0[1-9]|[1-2][0-9]))|((0[469]|11)\1(0[1-9]|[1-2][0-9]|30)))$
United States date format (mm/dd/yyyy)
^(((0[13578]|(10|12))/(0[1-9]|[1-2][0-9]|3[0-1]))|(02/(0[1-9]|[1-2][0-9]))|((0[469]|11)/(0[1-9]|[1-2][0-9]|30)))/[0-9]{4}$
Hours and minutes, 24 hours format (HH:MM):
^(20|21|22|23|[01]\d|\d)((:[0-5]\d){1,2})$
Good luck
This error can be because of too much reasons. Try first with testAds ca-app-pub id to avoid admob account issues.
Check that you extends AppCompatActivity in your mainActivity, in my case that was the issue
Also check all this steps again https://developers.google.com/admob/android/quick-start?hl=en-419#import_the_mobile_ads_sdk
Your include paths indicate that you should be compiling against the system's OpenSSL installation. You shouldn't have the .h
files in your package directory - it should be picking them up from /usr/include/openssl
.
The plain OpenSSL package (libssl
) doesn't include the .h
files - you need to install the development package as well. This is named libssl-dev
on Debian, Ubuntu and similar distributions, and libssl-devel
on CentOS, Fedora, Red Hat and similar.
It creates an interpolated string.
From MSDN
Used to construct strings. An interpolated string expression looks like a template string that contains expressions. An interpolated string expression creates a string by replacing the contained expressions with the ToString represenations of the expressions’ results.
ex :
var name = "Sam";
var msg = $"hello, {name}";
Console.WriteLine(msg); // hello, Sam
You can use expressions within the interpolated string
var msg = $"hello, {name.ToLower()}";
Console.WriteLine(msg); // hello, sam
The nice thing about it is that you don't need to worry about the order of parameters as you do with String.Format
.
var s = String.Format("{0},{1},{2}...{88}",p0,p1,..,p88);
Now if you want to remove some parameters you have to go and update all the counts, which is not the case anymore.
Note that the good old string.format
is still relevant if you want to specify cultural info in your formatting.
Well, for one thing, non-static inner classes have an extra, hidden field that points to the instance of the outer class. So if the Entry class weren't static, then besides having access that it doesn't need, it would carry around four pointers instead of three.
As a rule, I would say, if you define a class that's basically there to act as a collection of data members, like a "struct" in C, consider making it static.
If you have a valid dtd file for the xml then you can easily transform json to xml and xml to json using the eclipselink jar binary.
Refer this: http://www.cubicrace.com/2015/06/How-to-convert-XML-to-JSON-format.html
The article also has a sample project (including the supporting third party jars) as a zip file which can be downloaded for reference purpose.
You could use
options(warn=-1)
But note that turning off warning messages globally might not be a good idea.
To turn warnings back on, use
options(warn=0)
(or whatever your default is for warn
, see this answer)
Check out this way:
delete this.arrayName[this.arrayName.indexOf(value)];
Reference: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/delete
req.params
contains route parameters (in the path portion of the URL), and req.query
contains the URL query parameters (after the ?
in the URL).
You can also use req.param(name)
to look up a parameter in both places (as well as req.body
), but this method is now deprecated.
The copy
command is a SQL*Plus command (not a SQL Developer command). If you have your tnsname entries setup for SID1 and SID2 (e.g. try a tnsping), you should be able to execute your command.
Another assumption is that table1 has the same columns as the message_table (and the columns have only the following data types: CHAR, DATE, LONG, NUMBER or VARCHAR2). Also, with an insert command, you would need to be concerned about primary keys (e.g. that you are not inserting duplicate records).
I tried a variation of your command as follows in SQL*Plus (with no errors):
copy from scott/tiger@db1 to scott/tiger@db2 create new_emp using select * from emp;
After I executed the above statement, I also truncate the new_emp table and executed this command:
copy from scott/tiger@db1 to scott/tiger@db2 insert new_emp using select * from emp;
With SQL Developer, you could do the following to perform a similar approach to copying objects:
On the tool bar, select Tools>Database copy.
Identify source and destination connections with the copy options you would like.
For object type, select table(s).
The copy command approach is old and its features are not being updated with the release of new data types. There are a number of more current approaches to this like Oracle's data pump (even for tables).
I have found the EXECUTE command as suggested here T-SQL - function with default parameters to work well. With this approach there is no 'DEFAULT' needed when calling the function, you just omit the parameter as you would with a stored procedure.
You could use cat file.txt | head -1
, but it would probably be better to use head directly, as in head -1 file.txt
.
This is a cool function
function array_push_assoc($array, $key, $value){
$array[$key] = $value;
return $array;
}
Just use
$myarray = array_push_assoc($myarray, 'h', 'hello');
ACE.oledb.16.0 dosen't work in the 64-bit os
download patch from https://www.microsoft.com/en-us/download/details.aspx?id=13255
If you use Oracle 10 or higher you can use regexp functions as codaddict suggested. In earlier versions translate
function will help you:
select * from tablename where translate(x, '.1234567890', '.') is null;
More info about Oracle translate function can be found here or in official documentation "SQL Reference"
UPD: If you have signs or spaces in your numbers you can add "+-
" characters to the second parameter of translate
function.
I've a same problem. After move machine from restore of Time Machine, on another host. There problem it's that ssh key for vagrant it's not your key, it's a key on Homestead directory.
Solution for me:
run on terminal
vagrant ssh-config
Host default
HostName 127.0.0.1
User vagrant
Port 2222
UserKnownHostsFile /dev/null
StrictHostKeyChecking no
PasswordAuthentication no
IdentityFile "/Users/MYUSER/.vagrant.d/insecure_private_key"
IdentitiesOnly yes
LogLevel FATAL
ForwardAgent yes
Create a new pair of SSH keys
ssh-keygen -f /Users/MYUSER/.vagrant.d/insecure_private_key
Copy content of public key
cat /Users/MYUSER/.vagrant.d/insecure_private_key.pub
On other shell in Homestead VM Machine copy into authorized_keys
vagrant@homestad:~$ echo 'CONTENT_PASTE_OF_PRIVATE_KEY' >> ~/.ssh/authorized_keys
Now can access with vagrant ssh
Try this code:
For Each aSheet In Worksheets
Select Case aSheet.Name
Case "ID Sheet", "Summary"
Application.DisplayAlerts = False
aSheet.Delete
Application.DisplayAlerts = True
End Select
Next aSheet
It looks like you're trying to use an image to submit a form... in that case use
<input type="image" src="...">
If you really want to use an anchor then you have to use javascript:
<a href="#" onclick="document.forms['myFormName'].submit(); return false;">...</a>
A complete example for someone who may want to use this to monitor a mount point on a server. This example will check if /var/spool is under 5G and email the person :
#!/bin/bash
# -----------------------------------------------------------------------------------------
# SUMMARY: Check if MOUNT is under certain quota, mail us if this is the case
# DETAILS: If under 5G we have it alert us via email. blah blah
# -----------------------------------------------------------------------------------------
# CRON: 0 0,4,8,12,16 * * * /var/www/httpd-config/server_scripts/clear_root_spool_log.bash
MOUNTP=/var/spool # mount drive to check
LIMITSIZE=5485760 # 5G = 10*1024*1024k # limit size in GB (FLOOR QUOTA)
FREE=$(df -k --output=avail "$MOUNTP" | tail -n1) # df -k not df -h
LOG=/tmp/log-$(basename ${0}).log
MAILCMD=mail
EMAILIDS="[email protected]"
MAILMESSAGE=/tmp/tmp-$(basename ${0})
# -----------------------------------------------------------------------------------------
function email_on_failure(){
sMess="$1"
echo "" >$MAILMESSAGE
echo "Hostname: $(hostname)" >>$MAILMESSAGE
echo "Date & Time: $(date)" >>$MAILMESSAGE
# Email letter formation here:
echo -e "\n[ $(date +%Y%m%d_%H%M%S%Z) ] Current Status:\n\n" >>$MAILMESSAGE
cat $sMess >>$MAILMESSAGE
echo "" >>$MAILMESSAGE
echo "*** This email generated by $(basename $0) shell script ***" >>$MAILMESSAGE
echo "*** Please don't reply this email, this is just notification email ***" >>$MAILMESSAGE
# sending email (need to have an email client set up or sendmail)
$MAILCMD -s "Urgent MAIL Alert For $(hostname) AWS Server" "$EMAILIDS" < $MAILMESSAGE
[[ -f $MAILMESSAGE ]] && rm -f $MAILMESSAGE
}
# -----------------------------------------------------------------------------------------
if [[ $FREE -lt $LIMITSIZE ]]; then
echo "Writing to $LOG"
echo "MAIL ERROR: Less than $((($FREE/1000))) MB free (QUOTA) on $MOUNTP!" | tee ${LOG}
echo -e "\nPotential Files To Delete:" | tee -a ${LOG}
find $MOUNTP -xdev -type f -size +500M -exec du -sh {} ';' | sort -rh | head -n20 | tee -a ${LOG}
email_on_failure ${LOG}
else
echo "Currently $(((($FREE-$LIMITSIZE)/1000))) MB of QUOTA available of on $MOUNTP. "
fi
For hiding the toolbar you can just do :
getSupportActionBar().hide();
So you just have to had a scroll listener and hide the toolbar when the user scroll !
To add to Reed Copsey's answer about using Task.FromResult
, you can improve performance even more if you cache the already completed task since all instances of completed tasks are the same:
public static class TaskExtensions
{
public static readonly Task CompletedTask = Task.FromResult(false);
}
With TaskExtensions.CompletedTask
you can use the same instance throughout the entire app domain.
The latest version of the .Net Framework (v4.6) adds just that with the Task.CompletedTask
static property
Task completedTask = Task.CompletedTask;
Visual C# Express 2005 ISO File does not require registration
My issue was I was instatiating the player completely from start but I used an iframe instead of a wrapper div.
Many possibilities...
You know how to generate randomly an integer right? You can thus generate a char from it... (ex 65 -> A)
It depends what you need, the level of randomness, the security involved... but for a school project i guess getting UUID substring would fit :)
The best way is probably to use:
:%s/phrase//gc
c
asks for confirmation before each deletion. g
allows multiple replacements to occur on the same line.
You can also just search using /phrase
, select the next match with gn
, and delete it with d
.
Use curly brackets and put all the attributes you want to add inside
Example:
$('#objId').attr({
target: 'nw',
title: 'Opens in a new window'
});
If you really want to achieve that you can use a file watcher like inotifywait.
You watch a directory and you save information about file creations in separate file outside that directory.
while true; do
change=$(inotifywait -e close_write,moved_to,create .)
change=${change#./ * }
if [ "$change" = ".*" ]; then ./scriptToStoreInfoAboutFile; fi
done
As no creation time is stored, you can build your own system based on inotify.
Just remove all the folders named AndroidStudioPreview
On Windows:
Go to your User Folder - on Windows 7/8 this would be:
[SYSDRIVE]:\Users[your username] (ex. C:\Users\JohnDoe)
In this folder there should be a folder called .AndroidStudioPreview
On Mac OS X
Remove these files:
~/Library/Application Support/AndroidStudioPreview
~/Library/Caches/AndroidStudioPreview
~/Library/Logs/AndroidStudioPreview
~/Library/Preferences/AndroidStudioPreview
I'm using this one (using StringUtils from commons-lang):
Double qty = 1.01;
String res = String.format(Locale.GERMANY, "%.2f", qty);
String fmt = StringUtils.removeEnd(res, ",00");
You must only take care of the locale and the corresponding String to chop.
If you just want to pass some data from one screen to the next, you can pass them with the navigation.navigate
method like this:
<Button onPress={()=> {this.props.navigation.navigate('NextScreen',{foo:bar)} />
and in 'NextScreen' you can access them with the navigation.getParam()
method:
let foo=this.props.navigation.getParam(foo);
But it can get really "messy" if you have more than a couple of variables to pass..
Go to File> Project Structure (or press Ctrl+Alt+Shift+S), A popup will open now go to SDK Location Tab you will find JDK Location there refer this image to be more clear.
I've been using something like this. Just set up a simple HTML page with an textinput. Make sure that the textinput always has focus. When you scan a barcode with your barcode scanner you will receive the code and after that a 'enter'. Realy simple then; just capture the incoming keystrokes and when the 'enter' comes in you can use AJAX to handle your code.
There are two different ways to implement inserting data from one table to another table.
This method is used when the table is already created in the database earlier and the data is to be inserted into this table from another table. If columns listed in insert clause and select clause are same, they are not required to list them. It is good practice to always list them for readability and scalability purpose.
----Create testable
CREATE TABLE TestTable (FirstName VARCHAR(100), LastName VARCHAR(100))
----INSERT INTO TestTable using SELECT
INSERT INTO TestTable (FirstName, LastName)
SELECT FirstName, LastName
FROM Person.Contact
WHERE EmailPromotion = 2
----Verify that Data in TestTable
SELECT FirstName, LastName
FROM TestTable
----Clean Up Database
DROP TABLE TestTable
This method is used when the table is not created earlier and needs to be created when data from one table is to be inserted into the newly created table from another table. The new table is created with the same data types as selected columns.
----Create a new table and insert into table using SELECT INSERT
SELECT FirstName, LastName
INTO TestTable
FROM Person.Contact
WHERE EmailPromotion = 2
----Verify that Data in TestTable
SELECT FirstName, LastName
FROM TestTable
----Clean Up Database
DROP TABLE TestTable
Not the most elegant solution, and only works 90% of the time:
def vardict(*args):
ns = inspect.stack()[1][0].f_locals
retval = {}
for a in args:
found = False
for k, v in ns.items():
if a is v:
retval[k] = v
if found:
raise ValueError("Value found in more than one local variable: " + str(a))
found = True
if found:
continue
if 'self' in ns:
for k, v in ns['self'].__dict__.items():
if a is v:
retval[k] = v
if found:
raise ValueError("Value found in more than one instance attribute: " + str(a))
found = True
if found:
continue
for k, v in globals().items():
if a is v:
retval[k] = v
if found:
raise ValueError("Value found in more than one global variable: " + str(a))
found = True
assert found, "Couldn't find one of the parameters."
return retval
You'll run into problems if you store the same reference in multiple variables, but also if multiple variables store the same small int, since these get interned.
You actually can't do what you want with Bash aliases, since aliases are static. Instead, use the function you have created.
Look here for more information: http://www.mactips.org/archives/2008/01/01/increase-productivity-with-bash-aliases-and-functions/. (Yes I know it's mactips.org, but it's about Bash, so don't worry.)
A JSON string must be double-quoted, according to the specs, so you don't need to escape '
.
If you have to use special character in your JSON string, you can escape it using \
character.
See this list of special character used in JSON :
\b Backspace (ascii code 08)
\f Form feed (ascii code 0C)
\n New line
\r Carriage return
\t Tab
\" Double quote
\\ Backslash character
However, even if it is totally contrary to the spec, the author could use \'
.
This is bad because :
But it works, as you want it or not.
For new readers, always use a double quotes for your json strings.
git pull --rebase origin master
$value = ( array_key_exists($key, $array) && !empty($array[$key]) )
? $array[$key]
: 'non-existant or empty value key';
See this answer: there is in Ruby 1.9.2, but not in earlier versions. Personally I think rand(8) + 3 is fine, but if you're interested check out the Random class described in the link.
You can use the -l
option in the she-bang header:
#!/usr/bin/perl -l
$text = "hello";
print $text;
print $text;
Output:
hello
hello
with lombak 1.8.12, this worked for me
@Getter(value = lombok.AccessLevel.NONE)
@Setter(value = lombok.AccessLevel.NONE)
private int password;
You can test for the presence of a key in a dictionary, using the in keyword:
d = {'a': 1, 'b': 2}
'a' in d # <== evaluates to True
'c' in d # <== evaluates to False
A common use for checking the existence of a key in a dictionary before mutating it is to default-initialize the value (e.g. if your values are lists, for example, and you want to ensure that there is an empty list to which you can append when inserting the first value for a key). In cases such as those, you may find the collections.defaultdict()
type to be of interest.
In older code, you may also find some uses of has_key()
, a deprecated method for checking the existence of keys in dictionaries (just use key_name in dict_name
, instead).
Recently it became possible (but with an odd workaround).
To do this you must first create text with the desired hyperlink in an editor that supports rich text formatting. This can be an advanced text editor, web browser, email client, web-development IDE, etc.). Then copypaste the text from the editor or rendered HTML from browser (or other). E.g. in the example below I copypasted the head of this StackOverflow page. As you may see, the hyperlink have been copied correctly and is clickable in the message (checked on Mac Desktop, browser, and iOS apps).
On Mac
I was able to compose the desired link in the native Pages app as shown below. When you are done, copypaste your text into Slack app. This is the probably easiest way on Mac OS.
On Windows
I have a strong suspicion that MS Word will do the same trick, but unfortunately I don't have an installed instance to check.
Universal
Create text in an online editor, such as Google Documents. Use Insert -> Link, modify the text and web URL, then copypaste into Slack.
jww is right — you're referencing the wrong intermediate certificate.
As you have been issued with a SHA256 certificate, you will need the SHA256 intermediate. You can grab it from here: http://secure2.alphassl.com/cacert/gsalphasha2g2r1.crt
You should use the notification to solve this problem,because the other method will listen to the input box not the actually input,especially when you use the Chinese input method. In viewDidload
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(textFiledEditChanged:)
name:@"UITextFieldTextDidChangeNotification"
object:youTarget];
then
- (void)textFiledEditChanged:(NSNotification *)obj {
UITextField *textField = (UITextField *)obj.object;
NSString *toBestring = textField.text;
NSArray *currentar = [UITextInputMode activeInputModes];
UITextInputMode *currentMode = [currentar firstObject];
if ([currentMode.primaryLanguage isEqualToString:@"zh-Hans"]) {
UITextRange *selectedRange = [textField markedTextRange];
UITextPosition *position = [textField positionFromPosition:selectedRange.start offset:0];
if (!position) {
if (toBestring.length > kMaxLength)
textField.text = toBestring;
}
}
finally,you run,will done.
Another alternative
Just check the class in the Abstract class and Assert or Exception, whatever you fancy.
@implementation Orange
- (instancetype)init
{
self = [super init];
NSAssert([self class] != [Orange class], @"This is an abstract class");
if (self) {
}
return self;
}
@end
This removes the necessity to override init
Embed is not a standard tag, though object is. Here's an article that looks like it will help you, since it seems the situation is not so simple. An example for PDF is included.
Witch ;)
/*
This code is for example. In real life you have plugins like :
https://code.google.com/p/jquery-utils/wiki/JqueryUtils
https://github.com/jeresig/jquery.hotkeys/blob/master/jquery.hotkeys.js
https://github.com/madrobby/keymaster
http://dmauro.github.io/Keypress/
http://api.jquery.com/keydown/
http://api.jquery.com/keypress/
*/
var event2key = {'97':'a', '98':'b', '99':'c', '100':'d', '101':'e', '102':'f', '103':'g', '104':'h', '105':'i', '106':'j', '107':'k', '108':'l', '109':'m', '110':'n', '111':'o', '112':'p', '113':'q', '114':'r', '115':'s', '116':'t', '117':'u', '118':'v', '119':'w', '120':'x', '121':'y', '122':'z', '37':'left', '39':'right', '38':'up', '40':'down', '13':'enter'};
var documentKeys = function(event) {
console.log(event.type, event.which, event.keyCode);
var keycode = event.which || event.keyCode; // par exemple : 112
var myKey = event2key[keycode]; // par exemple : 'p'
switch (myKey) {
case 'a':
$('div').css({
left: '+=50'
});
break;
case 'z':
$('div').css({
left: '-=50'
});
break;
default:
//console.log('keycode', keycode);
}
};
$(document).on('keydown keyup keypress', documentKeys);
I do no expect that multiple div's is a good solution.
I also think you can replace .visible-sm-block
with .hidden-xs-down
and .hidden-md-up
(or .hidden-sm-down
and .hidden-lg-up
to act on the same media queries).
hidden-sm-up
compiles into:
.visible-sm-block {
display: none !important;
}
@media (min-width: 768px) and (max-width: 991px) {
.visible-sm-block {
display: block !important;
}
}
.hidden-sm-down
and .hidden-lg-up
compiles into:
@media (max-width: 768px) {
.hidden-xs-down {
display: none !important;
}
}
@media (min-width: 991px) {
.hidden-lg-up {
display: none !important;
}
}
Both situation should act the same.
You situation become different when you try to replace .visible-sm-block
and .visible-lg-block
. Bootstrap v4 docs tell you:
These classes don’t attempt to accommodate less common cases where an element’s visibility can’t be expressed as a single contiguous range of viewport breakpoint sizes; you will instead need to use custom CSS in such cases.
.visible-sm-and-lg {
display: none !important;
}
@media (min-width: 768px) and (max-width: 991px) {
.visible-sm-and-lg {
display: block !important;
}
}
@media (min-width: 1200px) {
.visible-sm-and-lg {
display: block !important;
}
}
Note that the TIMEDIFF()
solution only works when the datetimes
are less than 35 days apart!
TIMEDIFF()
returns a TIME
datatype, and the max value for TIME is 838:59:59 hours (=34,96 days)
Creating an array or tuple of keys from an interface with safety compile-time checks requires a bit of creativity. Types are erased at run-time and object types (unordered, named) cannot be converted to tuple types (ordered, unnamed) without resorting to non-supported techniques.
The here proposed variants all consider/trigger a compile error in case of duplicate or missing tuple items given a reference object type like IMyTable
. For example declaring an array type of (keyof IMyTable)[]
cannot catch these errors.
In addition, they don't require a specific library (last variant uses ts-morph
, which I would consider a generic compiler wrapper), emit a tuple type as opposed to an object (only first solution creates an array) or wide array type (compare to these answers) and lastly don't need classes.
// Record type ensures, we have no double or missing keys, values can be neglected
function createKeys(keyRecord: Record<keyof IMyTable, any>): (keyof IMyTable)[] {
return Object.keys(keyRecord) as any
}
const keys = createKeys({ isDeleted: 1, createdAt: 1, title: 1, id: 1 })
// const keys: ("id" | "title" | "createdAt" | "isDeleted")[]
+
easiest +-
manual with auto-completion -
array, no tuple
If you don't like creating a record, take a look at this alternative with Set
and assertion types.
function createKeys<T extends readonly (keyof IMyTable)[] | [keyof IMyTable]>(
t: T & CheckMissing<T, IMyTable> & CheckDuplicate<T>): T {
return t
}
+
tuple +-
manual with auto-completion +-
more advanced, complex types
createKeys
does compile-time checks by merging the function parameter type with additional assertion types, that emit an error for not suitable input. (keyof IMyTable)[] | [keyof IMyTable]
is a "black magic" way to force inference of a tuple instead of an array from the callee side. Alternatively, you can use const assertions / as const
from caller side.
CheckMissing
checks, if T
misses keys from U
:
type CheckMissing<T extends readonly any[], U extends Record<string, any>> = {
[K in keyof U]: K extends T[number] ? never : K
}[keyof U] extends never ? T : T & "Error: missing keys"
type T1 = CheckMissing<["p1"], {p1:any, p2:any}> //["p1"] & "Error: missing keys"
type T2 = CheckMissing<["p1", "p2"], { p1: any, p2: any }> // ["p1", "p2"]
Note: T & "Error: missing keys"
is just for nice IDE errors. You could also write never
. CheckDuplicates
checks double tuple items:
type CheckDuplicate<T extends readonly any[]> = {
[P1 in keyof T]: "_flag_" extends
{ [P2 in keyof T]: P2 extends P1 ? never :
T[P2] extends T[P1] ? "_flag_" : never }[keyof T] ?
[T[P1], "Error: duplicate"] : T[P1]
}
type T3 = CheckDuplicate<[1, 2, 3]> // [1, 2, 3]
type T4 = CheckDuplicate<[1, 2, 1]>
// [[1, "Error: duplicate"], 2, [1, "Error: duplicate"]]
Note: More infos on unique item checks in tuples are in this post. With TS 4.1, we also can name missing keys in the error string - take a look at this Playground.
With version 4.1, TypeScript officially supports conditional recursive types, which can be potentially used here as well. Though, the type computation is expensive due to combinatory complexity - performance degrades massively for more than 5-6 items. I list this alternative for completeness (Playground):
type Prepend<T, U extends any[]> = [T, ...U] // TS 4.0 variadic tuples
type Keys<T extends Record<string, any>> = Keys_<T, []>
type Keys_<T extends Record<string, any>, U extends PropertyKey[]> =
{
[P in keyof T]: {} extends Omit<T, P> ? [P] : Prepend<P, Keys_<Omit<T, P>, U>>
}[keyof T]
const t1: Keys<IMyTable> = ["createdAt", "isDeleted", "id", "title"] // ?
+
tuple +-
manual with auto-completion +
no helper function --
performance
ts-morph is chosen here, as it is a tad simpler wrapper alternative to the original TS compiler API. Of course, you can also use the compiler API directly. Let's look at the generator code:
// ./src/mybuildstep.ts
import {Project, VariableDeclarationKind, InterfaceDeclaration } from "ts-morph";
const project = new Project();
// source file with IMyTable interface
const sourceFile = project.addSourceFileAtPath("./src/IMyTable.ts");
// target file to write the keys string array to
const destFile = project.createSourceFile("./src/generated/IMyTable-keys.ts", "", {
overwrite: true // overwrite if exists
});
function createKeys(node: InterfaceDeclaration) {
const allKeys = node.getProperties().map(p => p.getName());
destFile.addVariableStatement({
declarationKind: VariableDeclarationKind.Const,
declarations: [{
name: "keys",
initializer: writer =>
writer.write(`${JSON.stringify(allKeys)} as const`)
}]
});
}
createKeys(sourceFile.getInterface("IMyTable")!);
destFile.saveSync(); // flush all changes and write to disk
After we compile and run this file with tsc && node dist/mybuildstep.js
, a file ./src/generated/IMyTable-keys.ts
with following content is generated:
// ./src/generated/IMyTable-keys.ts
const keys = ["id","title","createdAt","isDeleted"] as const;
+
auto-generating solution +
scalable for multiple properties +
no helper function +
tuple -
extra build-step -
needs familiarity with compiler API
Here is the notes (from Brian Goetz book) I made, that might be of help to you
AtomicXXX classes
provide Non-blocking Compare-And-Swap implementation
Takes advantage of the support provide by hardware (the CMPXCHG instruction on Intel) When lots of threads are running through your code that uses these atomic concurrency API, they will scale much better than code which uses Object level monitors/synchronization. Since, Java's synchronization mechanisms makes code wait, when there are lots of threads running through your critical sections, a substantial amount of CPU time is spent in managing the synchronization mechanism itself (waiting, notifying, etc). Since the new API uses hardware level constructs (atomic variables) and wait and lock free algorithms to implement thread-safety, a lot more of CPU time is spent "doing stuff" rather than in managing synchronization.
not only offer better throughput, but they also provide greater resistance to liveness problems such as deadlock and priority inversion.
You're using the ajax function incorrectly. Since it's synchronous it'll return the data inline like so:
var remote = $.ajax({
type: "GET",
url: remote_url,
async: false
}).responseText;
rs
comes with BSDs and macOS, but it is available from package managers on other platforms. It is named after the "reshape" function in APL.
Use sequences of spaces and tabs as column separator:
rs -T
Use tab as column separator:
rs -c -C -T
Use comma as column separator:
rs -c, -C, -T
-c
changes the input column separator and -C
changes the output column separator. -c
or -C
alone sets the separator to tab. -T
transposes rows and columns.
Do not use -t
instead of -T
, because it uses an automatically selected number of columns that is usually incorrect, because the number of columns is selected so that the output rows fill the width of the display (which is 80 characters by default but which can be changed with -w
).
One caveat is that when an output column separator is specified using -C
, an extra column separator character is added to the end of each row, but you can remove the extra character using something like sed 's/.$//'
:
$ seq 4|paste -d, - -|rs -c, -C, -T
1,3,
2,4,
$ seq 4|paste -d, - -|rs -c, -C, -T|sed 's/.$//'
1,3
2,4
A second caveat is that this fails with tables where the first line contains one or more empty columns at the end, because the number of columns is determined based on the number of columns on the first row:
$ rs -C, -c, -T<<<$'1,\n3,4'
1,3,4,
$ ruby -e'puts readlines.map{|x|x.chomp.split(",",-1)}.transpose.map{|x|x*","}'<<<$'1,\n3,4'
1,3
,4
The -1
argument to split
doesn't discard empty fields at the end:
$ ruby -e'p"a,,".split(",")'
["a"]
$ ruby -e'p"a,,".split(",",-1)'
["a", "", ""]
Function form:
$ tp(){ ruby -e'puts STDIN.read.split("\n").map{|x|x.split(ARGV[0],-1)}.transpose.map{|x|x*ARGV[0]}' -- "${1-$'\t'}";}
$ seq 4|paste - -|tp|sed -n l
1\t3$
2\t4$
jq -R .|jq -sr 'map(./"\t")|transpose|map(join("\t"))[]'
jq -R .
prints each input line as a JSON string literal, -s
(--slurp
) creates an array for the input lines after parsing each line as JSON, and -r
(--raw-output
) outputs the contents of strings instead of JSON string literals. The /
operator is overloaded to split strings.
Function form:
tp(){ jq -R .|jq --arg x "${1-$'\t'}" -sr 'map(./$x)|transpose|map(join($x))[]';}
See the documentation on ?merge
, which states:
By default the data frames are merged on the columns with names they both have,
but separate specifications of the columns can be given by by.x and by.y.
This clearly implies that merge
will merge data frames based on more than one column. From the final example given in the documentation:
x <- data.frame(k1=c(NA,NA,3,4,5), k2=c(1,NA,NA,4,5), data=1:5)
y <- data.frame(k1=c(NA,2,NA,4,5), k2=c(NA,NA,3,4,5), data=1:5)
merge(x, y, by=c("k1","k2")) # NA's match
This example was meant to demonstrate the use of incomparables
, but it illustrates merging using multiple columns as well. You can also specify separate columns in each of x
and y
using by.x
and by.y
.
Just wondering why you are using 2 directives?
It seems like, in this case it would be more straightforward to have a controller as the parent - handle adding the data from your service to its $scope, and pass the model you need from there into your warrantyDirective.
Or for that matter, you could use 0 directives to achieve the same result. (ie. move all functionality out of the separate directives and into a single controller).
It doesn't look like you're doing any explicit DOM transformation here, so in this case, perhaps using 2 directives is overcomplicating things.
Alternatively, have a look at the Angular documentation for directives: http://docs.angularjs.org/guide/directive The very last example at the bottom of the page explains how to wire up dependent directives.
For this task you can use already available plugins and bootstrap extensions. Or you can make your own confirmation popup with just 3 lines of code. Check it out.
Say we have this links (note data-href
instead of href
) or buttons that we want to have delete confirmation for:
<a href="#" data-href="delete.php?id=23" data-toggle="modal" data-target="#confirm-delete">Delete record #23</a>
<button class="btn btn-default" data-href="/delete.php?id=54" data-toggle="modal" data-target="#confirm-delete">
Delete record #54
</button>
Here #confirm-delete
points to a modal popup div in your HTML. It should have an "OK" button configured like this:
<div class="modal fade" id="confirm-delete" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
...
</div>
<div class="modal-body">
...
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Cancel</button>
<a class="btn btn-danger btn-ok">Delete</a>
</div>
</div>
</div>
</div>
Now you only need this little javascript to make a delete action confirmable:
$('#confirm-delete').on('show.bs.modal', function(e) {
$(this).find('.btn-ok').attr('href', $(e.relatedTarget).data('href'));
});
So on show.bs.modal
event delete button href
is set to URL with corresponding record id.
Demo: http://plnkr.co/edit/NePR0BQf3VmKtuMmhVR7?p=preview
I realize that in some cases there might be needed to perform POST or DELETE request rather then GET. It it still pretty simple without too much code. Take a look at the demo below with this approach:
// Bind click to OK button within popup
$('#confirm-delete').on('click', '.btn-ok', function(e) {
var $modalDiv = $(e.delegateTarget);
var id = $(this).data('recordId');
$modalDiv.addClass('loading');
$.post('/api/record/' + id).then(function() {
$modalDiv.modal('hide').removeClass('loading');
});
});
// Bind to modal opening to set necessary data properties to be used to make request
$('#confirm-delete').on('show.bs.modal', function(e) {
var data = $(e.relatedTarget).data();
$('.title', this).text(data.recordTitle);
$('.btn-ok', this).data('recordId', data.recordId);
});
// Bind click to OK button within popup_x000D_
$('#confirm-delete').on('click', '.btn-ok', function(e) {_x000D_
_x000D_
var $modalDiv = $(e.delegateTarget);_x000D_
var id = $(this).data('recordId');_x000D_
_x000D_
$modalDiv.addClass('loading');_x000D_
setTimeout(function() {_x000D_
$modalDiv.modal('hide').removeClass('loading');_x000D_
}, 1000);_x000D_
_x000D_
// In reality would be something like this_x000D_
// $modalDiv.addClass('loading');_x000D_
// $.post('/api/record/' + id).then(function() {_x000D_
// $modalDiv.modal('hide').removeClass('loading');_x000D_
// });_x000D_
});_x000D_
_x000D_
// Bind to modal opening to set necessary data properties to be used to make request_x000D_
$('#confirm-delete').on('show.bs.modal', function(e) {_x000D_
var data = $(e.relatedTarget).data();_x000D_
$('.title', this).text(data.recordTitle);_x000D_
$('.btn-ok', this).data('recordId', data.recordId);_x000D_
});
_x000D_
.modal.loading .modal-content:before {_x000D_
content: 'Loading...';_x000D_
text-align: center;_x000D_
line-height: 155px;_x000D_
font-size: 20px;_x000D_
background: rgba(0, 0, 0, .8);_x000D_
position: absolute;_x000D_
top: 55px;_x000D_
bottom: 0;_x000D_
left: 0;_x000D_
right: 0;_x000D_
color: #EEE;_x000D_
z-index: 1000;_x000D_
}
_x000D_
<script data-require="jquery@*" data-semver="2.0.3" src="//code.jquery.com/jquery-2.0.3.min.js"></script>_x000D_
<script data-require="bootstrap@*" data-semver="3.1.1" src="//netdna.bootstrapcdn.com/bootstrap/3.1.1/js/bootstrap.min.js"></script>_x000D_
<link data-require="[email protected]" data-semver="3.1.1" rel="stylesheet" href="//netdna.bootstrapcdn.com/bootstrap/3.1.1/css/bootstrap.min.css" />_x000D_
_x000D_
<div class="modal fade" id="confirm-delete" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">_x000D_
<div class="modal-dialog">_x000D_
<div class="modal-content">_x000D_
<div class="modal-header">_x000D_
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>_x000D_
<h4 class="modal-title" id="myModalLabel">Confirm Delete</h4>_x000D_
</div>_x000D_
<div class="modal-body">_x000D_
<p>You are about to delete <b><i class="title"></i></b> record, this procedure is irreversible.</p>_x000D_
<p>Do you want to proceed?</p>_x000D_
</div>_x000D_
<div class="modal-footer">_x000D_
<button type="button" class="btn btn-default" data-dismiss="modal">Cancel</button>_x000D_
<button type="button" class="btn btn-danger btn-ok">Delete</button>_x000D_
</div>_x000D_
</div>_x000D_
</div>_x000D_
</div>_x000D_
<a href="#" data-record-id="23" data-record-title="The first one" data-toggle="modal" data-target="#confirm-delete">_x000D_
Delete "The first one", #23_x000D_
</a>_x000D_
<br />_x000D_
<button class="btn btn-default" data-record-id="54" data-record-title="Something cool" data-toggle="modal" data-target="#confirm-delete">_x000D_
Delete "Something cool", #54_x000D_
</button>
_x000D_
Demo: http://plnkr.co/edit/V4GUuSueuuxiGr4L9LmG?p=preview
Here is an original version of the code I made when I was answering this question for Bootstrap 2.3 modal.
$('#modal').on('show', function() {
var id = $(this).data('id'),
removeBtn = $(this).find('.danger');
removeBtn.attr('href', removeBtn.attr('href').replace(/(&|\?)ref=\d*/, '$1ref=' + id));
});
<div class="preload">
<img src="http://i.imgur.com/KUJoe.gif">
</div>
<div class="content">
I would like to display a loading bar before the entire page is loaded.
</div>
$(function() {
$(".preload").fadeOut(2000, function() {
$(".content").fadeIn(1000);
});
});?
.content {display:none;}
.preload {
width:100px;
height: 100px;
position: fixed;
top: 50%;
left: 50%;
}
?
The most likely reason why the Java Runtime Environment JRE or Java Development Kit JDK is that it's owned by Oracle not Google and they would need a redistribution agreement which if you know there is some history between the two companies.
Lucky for us that Sun Microsystems before it was bought by Oracle open sourced Java and MySQL a win for us little guys.... Thank you Sun!
Google should probably have a caveat saying you may also need JRE OR JDK
grep -rl $oldstring . | xargs sed -i "s/$oldstring/$newstring/g"
For people still looking a couple of years later, things have changed a bit. You can now use the queue
for .fadeIn()
as well so that it will work like this:
$('.tooltip').fadeIn({queue: false, duration: 'slow'});
$('.tooltip').animate({ top: "-10px" }, 'slow');
This has the benefit of working on display: none
elements so you don't need the extra two lines of code.