I don't think anyone has mentioned this: Use of alloca in a function will hinder or disable some optimizations that could otherwise be applied in the function, since the compiler cannot know the size of the function's stack frame.
For instance, a common optimization by C compilers is to eliminate use of the frame pointer within a function, frame accesses are made relative to the stack pointer instead; so there's one more register for general use. But if alloca is called within the function, the difference between sp and fp will be unknown for part of the function, so this optimization cannot be done.
Given the rarity of its use, and its shady status as a standard function, compiler designers quite possibly disable any optimization that might cause trouble with alloca, if would take more than a little effort to make it work with alloca.
UPDATE: Since variable-length local arrays have been added to C, and since these present very similar code-generation issues to the compiler as alloca, I see that 'rarity of use and shady status' does not apply to the underlying mechanism; but I would still suspect that use of either alloca or VLA tends to compromise code generation within a function that uses them. I would welcome any feedback from compiler designers.
I do so
<input id="relacionac" name="relacionac" type="number" min="0.4" max="0.7" placeholder="0,40-0,70" class="form-control input-md" step="0.01">
then, I define min in 0.4 and max in 0.7 with step 0.01: 0.4, 0.41, 0,42 ... 0.7
Not exactly what the user asked, but an easy way to just count unique values:
Google introduced a new function to count unique values in just one step, and you can use this as an input for other formulas:
=COUNTUNIQUE(A1:B10)
There are two methods you can use. Both require creating a user and a database.
Using createuser and createdb,
$ sudo -u postgres createuser --superuser $USER
$ createdb mydatabase
$ psql -d mydatabase
Using the SQL administration commands, and connecting with a password over TCP
$ sudo -u postgres psql postgres
And, then in the psql shell
CREATE ROLE myuser LOGIN PASSWORD 'mypass';
CREATE DATABASE mydatabase WITH OWNER = myuser;
Then you can login,
$ psql -h localhost -d mydatabase -U myuser -p <port>
If you don't know the port, you can always get it by running the following, as the postgres
user,
SHOW port;
Or,
$ grep "port =" /etc/postgresql/*/main/postgresql.conf
postgres
userI suggest NOT modifying the postgres
user.
postgres
. You're supposed to have root to get to authenticate as postgres
.postgres
which is the PostgreSQL equivalent of SQL Server's SA
, you have to have write-access to the underlying data files. And, that means that you could normally wreck havoc anyway.One way to do it would be:
//
and before the Code text. Notice the vertical blue line in the below image( that will appear once the selection is made, then you can insert any number of characters in between them)
I couldn't find a direct way to do that. The interesting thing is that it is mentioned in the C# Coding Conventions (C# Programming Guide) under Commenting Conventions.
Insert one space between the comment delimiter (//) and the comment text
But the default implementation of commenting in visual studio doesn't insert any space
With async actions (timers, ajax) you can override the property isDefaultPrevented
like this:
$('a').click(function(evt){
e.preventDefault();
// in async handler (ajax/timer) do these actions:
setTimeout(function(){
// override prevented flag to prevent jquery from discarding event
evt.isDefaultPrevented = function(){ return false; }
// retrigger with the exactly same event data
$(this).trigger(evt);
}, 1000);
}
This is most complete way of retriggering the event with the exactly same data.
This post may help http://bavotasan.com/2011/style-select-box-using-only-css/
He is using a outside div with a class for resolving this issue.
<div class="styled-select">
<select>
<option>Here is the first option</option>
<option>The second option</option>
</select>
</div>
If you prefer using bash script, this worked for me: (5Gb file, publicly available)
#!/bin/bash
if [ $# != 2 ]; then
echo "Usage: googledown.sh ID save_name"
exit 0
fi
confirm=$(wget --quiet --save-cookies /tmp/cookies.txt --keep-session-cookies --no-check-certificate 'https://docs.google.com/uc?export=download&id='$1 -O- | sed -rn 's/.*confirm=([0-9A-Za-z_]+).*/\1\n/p')
echo $confirm
wget --load-cookies /tmp/cookies.txt "https://docs.google.com/uc?export=download&confirm=$confirm&id=$1" -O $2 && rm -rf /tmp/cookies.txt
For readability, I restructured the query... starting with the apparent top-most level being Table1, which then ties to Table3, and then table3 ties to table2. Much easier to follow if you follow the chain of relationships.
Now, to answer your question. You are getting a large count as the result of a Cartesian product. For each record in Table1 that matches in Table3 you will have X * Y. Then, for each match between table3 and Table2 will have the same impact... Y * Z... So your result for just one possible ID in table 1 can have X * Y * Z records.
This is based on not knowing how the normalization or content is for your tables... if the key is a PRIMARY key or not..
Ex:
Table 1
DiffKey Other Val
1 X
1 Y
1 Z
Table 3
DiffKey Key Key2 Tbl3 Other
1 2 6 V
1 2 6 X
1 2 6 Y
1 2 6 Z
Table 2
Key Key2 Other Val
2 6 a
2 6 b
2 6 c
2 6 d
2 6 e
So, Table 1 joining to Table 3 will result (in this scenario) with 12 records (each in 1 joined with each in 3). Then, all that again times each matched record in table 2 (5 records)... total of 60 ( 3 tbl1 * 4 tbl3 * 5 tbl2 )count would be returned.
So, now, take that and expand based on your 1000's of records and you see how a messed-up structure could choke a cow (so-to-speak) and kill performance.
SELECT
COUNT(*)
FROM
Table1
INNER JOIN Table3
ON Table1.DifferentKey = Table3.DifferentKey
INNER JOIN Table2
ON Table3.Key =Table2.Key
AND Table3.Key2 = Table2.Key2
If this is from a SQL Server datebase you could issue this kind of query...
Select Top 1 DepartureTime From TrainSchedule where DepartureTime >
GetUTCDate()
Order By DepartureTime ASC
GetDate()
could also be used, not sure how dates are being stored.
I am not sure how the data is being stored and/or read.
Met this problem when I created a branch based on branch A by
git checkout -b a
and then I set the up stream of branch a to origin branch B by
git branch -u origin/B
Then I got the error message above.
One way to solve this problem for me was,
git checkout -b b origin/B
Here's what I don't like about git:
First of all, I think the distributed idea flies in the face of reality. Everybody who's actually using git is doing so in a centralised way, even Linus Torvalds. If the kernel was managed in a distributed way, that would mean I couldn't actually download the "official" kernel sources - there wouldn't be one - I'd have to decide whether I want Linus' version, or Joe's version, or Bill's version. That would obviously be ridiculous, and that's why there is an official definition which Linus controls using a centralised workflow.
If you accept that you want a centralised definition of your stuff, then it becomes clear that the server and client roles are completely different, so the dogma that the client and server softwares should be the same becomes purely limiting. The dogma that the client and server data should be the same becomes patently ridiculous, especially in a codebase that's got fifteen years of history that nobody cares about but everybody would have to clone.
What we actually want to do with all that old stuff is bung it in a cupboard and forget that it's there, just like any normal VCS does. The fact that git hauls it all back and forth over the network every day is very dangerous, because it nags you to prune it. That pruning involves a lot of tedious decisions and it can go wrong. So people will probably keep a whole series of snapshot repos from various points in history, but wasn't that what source control was for in the first place? This problem didn't exist until somebody invented the distributed model.
Git actively encourages people to rewrite history, and the above is probably one reason for that. Every normal VCS makes rewriting history impossible for all but the admins, and makes sure the admins have no reason to consider it. Correct me if I'm wrong, but as far as I know, git provides no way to grant normal users write access but ban them from rewriting history. That means any developer with a grudge (or who was still struggling with the learning curve) could trash the whole codebase. How do we tighten that one? Well, either you make regular backups of the entire history, i.e. you keep history squared, or you ban write access to all except some poor sod who would receive all the diffs by email and merge them by hand.
Let's take an example of a well-funded, large project and see how git is working for them: Android. I once decided to have a play with the android system itself. I found out that I was supposed to use a bunch of scripts called repo to get at their git. Some of repo runs on the client and some on the server, but both, by their very existence, are illustrating the fact that git is incomplete in either capacity. What happened is that I was unable to pull the sources for about a week and then gave up altogether. I would have had to pull a truly vast amount of data from several different repositories, but the server was completely overloaded with people like me. Repo was timing out and was unable to resume from where it had timed out. If git is so distributable, you'd have thought that they'd have done some kind of peer-to-peer thing to relieve the load on that one server. Git is distributable, but it's not a server. Git+repo is a server, but repo is not distributable cos it's just an ad-hoc collection of hacks.
A similar illustration of git's inadequacy is gitolite (and its ancestor which apparently didn't work out so well.) Gitolite describes its job as easing the deployment of a git server. Again, the very existence of this thing proves that git is not a server, any more than it is a client. What's more, it never will be, because if it grew into either it would be betraying it's founding principles.
Even if you did believe in the distributed thing, git would still be a mess. What, for instance, is a branch? They say that you implicitly make a branch every time you clone a repository, but that can't be the same thing as a branch in a single repository. So that's at least two different things being referred to as branches. But then, you can also rewind in a repo and just start editing. Is that like the second type of branch, or something different again? Maybe it depends what type of repo you've got - oh yes - apparently the repo is not a very clear concept either. There are normal ones and bare ones. You can't push to a normal one because the bare part might get out of sync with its source tree. But you can't cvsimport to a bare one cos they didn't think of that. So you have to cvsimport to a normal one, clone that to a bare one which developers hit, and cvsexport that to a cvs working copy which still has to be checked into cvs. Who can be bothered? Where did all these complications come from? From the distributed idea itself. I ditched gitolite in the end because it was imposing even more of these restrictions on me.
Git says that branching should be light, but many companies already have a serious rogue branch problem so I'd have thought that branching should be a momentous decision with strict policing. This is where perforce really shines...
In perforce you rarely need branches because you can juggle changesets in a very agile way. For instance, the usual workflow is that you sync to the last known good version on mainline, then write your feature. Whenever you attempt to modify a file, the diff of that file gets added to your "default changeset". When you attempt to check in the changeset, it automatically tries to merge the news from mainline into your changeset (effectively rebasing it) and then commits. This workflow is enforced without you even needing to understand it. Mainline thus collects a history of changes which you can quite easily cherry pick your way through later. For instance, suppose you want to revert an old one, say, the one before the one before last. You sync to the moment before the offending change, mark the affected files as part of the changeset, sync to the moment after and merge with "always mine". (There was something very interesting there: syncing doesn't mean having the same thing - if a file is editable (i.e. in an active changeset) it won't be clobbered by the sync but marked as due for resolving.) Now you have a changelist that undoes the offending one. Merge in the subsequent news and you have a changelist that you can plop on top of mainline to have the desired effect. At no point did we rewrite any history.
Now, supposing half way through this process, somebody runs up to you and tells you to drop everything and fix some bug. You just give your default changelist a name (a number actually) then "suspend" it, fix the bug in the now empty default changelist, commit it, and resume the named changelist. It's typical to have several changelists suspended at a time where you try different things out. It's easy and private. You get what you really want from a branch regime without the temptation to procrastinate or chicken out of merging to mainline.
I suppose it would be theoretically possible to do something similar in git, but git makes practically anything possible rather than asserting a workflow we approve of. The centralised model is a bunch of valid simplifications relative to the distributed model which is an invalid generalisation. It's so overgeneralised that it basically expects you to implement source control on top of it, as repo does.
The other thing is replication. In git, anything is possible so you have to figure it out for yourself. In perforce, you get an effectively stateless cache. The only configuration it needs to know is where the master is, and the clients can point at either the master or the cache at their discretion. That's a five minute job and it can't go wrong.
You've also got triggers and customisable forms for asserting code reviews, bugzilla references etc, and of course, you have branches for when you actually need them. It's not clearcase, but it's close, and it's dead easy to set up and maintain.
All in all, I think that if you know you're going to work in a centralised way, which everybody does, you might as well use a tool that was designed with that in mind. Git is overrated because of Linus' fearsome wit together with peoples' tendency to follow each other around like sheep, but its main raison d'etre doesn't actually stand up to common sense, and by following it, git ties its own hands with the two huge dogmas that (a) the software and (b) the data have to be the same at both client and server, and that will always make it complicated and lame at the centralised job.
Follow TOOLS->OPTIONS->Text Editor->CSS->Formatting Choose "Compact Rules" and uncheck "Hiearerchical indentation"
This happened to me as well. For me, Postfix was located at the same server as the PHP script, and the error was happening when I would be using SMTP authentication and smtp.domain.com instead of localhost.
So when I commented out these lines:
$mail->SMTPAuth = true;
$mail->SMTPSecure = "tls";
and set the host to
$mail->Host = "localhost";
instead
$mail->Host = 'smtp.mydomainiuse.com'
and it worked :)
At run time every loaded class has an instance of a Class
object. That is the object that is used as the shared lock object by static synchronized
methods. (Any synchronized method or block has to lock on some shared object.)
You can also synchronize on this object manually if wanted (whether in a static method or not). These three methods behave the same, allowing only one thread at a time into the inner block:
class Foo {
static synchronized void methodA() {
// ...
}
static void methodB() {
synchronized (Foo.class) {
// ...
}
}
static void methodC() {
Object lock = Foo.class;
synchronized (lock) {
// ...
}
}
}
The intended purpose of static synchronized
methods is when you want to allow only one thread at a time to use some mutable state stored in static
variables of a class.
Nowadays, Java has more powerful concurrency features, in java.util.concurrent
and its subpackages, but the core Java 1.0 constructs such as synchronized
methods are still valid and usable.
string input = "it's worth a lot of money, if you can find a buyer.";
for (dynamic i = 0, repl = new string[,] { { "'", "''" }, { "money", "$" }, { "find", "locate" } }; i < repl.Length / 2; i++) {
input = input.Replace(repl[i, 0], repl[i, 1]);
}
This should do:
Assembly assem = Assembly.GetExecutingAssembly();
AssemblyName aName = assem.GetName();
return aName.Version.ToString();
Using CentOS Linux I found that the easiest syntax would be:
wget "link" -O file.ext
where "link"
is the web address you want to save and "file.ext"
is the filename and extension of your choice.
Anthony
try the below one. it will give ur expected output
select c.name as Fields from
tempdb.sys.columns c
inner join tempdb.sys.tables t
ON c.object_id = t.object_id
where t.name like '#MyTempTable%'
VAR=$VAR"$VARTOADD(STRING)"
echo $VAR
I made an update of the actual answer.
This seems to be working on firefox and chrome: http://jsfiddle.net/gatsbimantico/QJeB7/1/embedded/result/
.x{
columns: 5em;
-webkit-columns: 5em; /* Safari and Chrome */
-moz-columns: 5em; /* Firefox */
}
.x li{
float:left;
break-inside: avoid-column;
-webkit-column-break-inside: avoid; /* Safari and Chrome */
}
Note: The float property seems to be the one making the block behaviour.
file='test.xlsx'
if file.endswith('.csv'):
print('file is CSV')
elif file.endswith('.xlsx'):
print('file is excel')
else:
print('none of them')
I created a function:
CREATE FUNCTION [dbo].[fnPadLeft](@int int, @Length tinyint)
RETURNS varchar(255)
AS
BEGIN
DECLARE @strInt varchar(255)
SET @strInt = CAST(@int as varchar(255))
RETURN (REPLICATE('0', (@Length - LEN(@strInt))) + @strInt);
END;
Use: select dbo.fnPadLeft(123, 10)
Returns: 0000000123
Someone give Luciano these points :) I just tested his answer -had a similar question- and worked perfectly...
I even add my 50 cents:
.error(function(jqXHR, textStatus, errorThrown) {
console.log("error " + textStatus);
console.log("incoming Text " + jqXHR.responseText);
})
<?php
$thumbs_dir = 'E:/xampp/htdocs/uploads/thumbs/';
$videos = array();
if (isset($_POST["name"])) {
if (!preg_match('/data:([^;]*);base64,(.*)/', $_POST['data'], $matches)) {
die("error");
}
$data = $matches[2];
$data = str_replace(' ', '+', $data);
$data = base64_decode($data);
$file = 'text.jpg';
$dataname = file_put_contents($thumbs_dir . $file, $data);
}
?>
//jscode
<script type="text/javascript">
var videos = <?= json_encode($videos); ?>;
var video = document.getElementById('video');
video.addEventListener('canplay', function () {
this.currentTime = this.duration / 2;
}, false);
var seek = true;
video.addEventListener('seeked', function () {
if (seek) {
getThumb();
}
}, false);
function getThumb() {
seek = false;
var filename = video.src;
var w = video.videoWidth;//video.videoWidth * scaleFactor;
var h = video.videoHeight;//video.videoHeight * scaleFactor;
var canvas = document.createElement('canvas');
canvas.width = w;
canvas.height = h;
var ctx = canvas.getContext('2d');
ctx.drawImage(video, 0, 0, w, h);
var data = canvas.toDataURL("image/jpg");
var xmlhttp = new XMLHttpRequest;
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
}
}
xmlhttp.open("POST", location.href, true);
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.send('name=' + encodeURIComponent(filename) + '&data=' + data);
}
function failed(e) {
// video playback failed - show a message saying why
switch (e.target.error.code) {
case e.target.error.MEDIA_ERR_ABORTED:
console.log('You aborted the video playback.');
break;
case e.target.error.MEDIA_ERR_NETWORK:
console.log('A network error caused the video download to fail part-way.');
break;
case e.target.error.MEDIA_ERR_DECODE:
console.log('The video playback was aborted due to a corruption problem or because the video used features your browser did not support.');
break;
case e.target.error.MEDIA_ERR_SRC_NOT_SUPPORTED:
console.log('The video could not be loaded, either because the server or network failed or because the format is not supported.');
break;
default:
console.log('An unknown error occurred.');
break;
}
}
</script>
//Html
<div>
<video id="video" src="1499752288.mp4" autoplay="true" onerror="failed(event)" controls="controls" preload="none"></video>
</div>
I solved my problem simply using ng-init
for default selection instead of ng-checked
<div ng-init="person.billing=FALSE"></div>
<input id="billing-no" type="radio" name="billing" ng-model="person.billing" ng-value="FALSE" />
<input id="billing-yes" type="radio" name="billing" ng-model="person.billing" ng-value="TRUE" />
One classic root cause for this message is:
git init lis4368/assignments
),Ie, if you don't have added and committed at least once, there won't be a local master
branch to push to.
Try first to create a commit:
git add .
) then git commit -m "first commit"
git commit --allow-empty -m "Initial empty commit"
And then try git push -u origin master
again.
See "Why do I need to explicitly push a new branch?" for more.
In Python 3.9, a new removeprefix
method is being added:
>>> 'TestHook'.removeprefix('Test')
'Hook'
>>> 'BaseTestCase'.removeprefix('Test')
'BaseTestCase'
It also works if you change the content type
<form method="POST"
action="http://localhost:8080/cms/customer/create_customer"
id="frmRegister" name="frmRegister"
enctype="application/x-www-form-urlencoded">
In the controller also add the header value as follows:
@RequestMapping(value = "/create_customer", method = RequestMethod.POST, headers = "Content-Type=application/x-www-form-urlencoded")
v-el:el:uniquename
has been replaced by ref="uniqueName"
. The element is then accessed through this.$refs.uniqueName
.
This generator yields bytes from a file, reading the file in chunks:
def bytes_from_file(filename, chunksize=8192):
with open(filename, "rb") as f:
while True:
chunk = f.read(chunksize)
if chunk:
for b in chunk:
yield b
else:
break
# example:
for b in bytes_from_file('filename'):
do_stuff_with(b)
See the Python documentation for information on iterators and generators.
Another solution, using Array#reduce
.
var myObject = {_x000D_
"ircEvent": "PRIVMSG",_x000D_
"method": "newURI",_x000D_
"regex": "^http://.*"_x000D_
};_x000D_
_x000D_
myObject = Object.keys(myObject).reduce(function(obj, key) {_x000D_
if (key != "regex") { //key you want to remove_x000D_
obj[key] = myObject[key];_x000D_
}_x000D_
return obj;_x000D_
}, {});_x000D_
_x000D_
console.log(myObject);
_x000D_
However, it will mutate the original object. If you want to create a new object without the specified key, just assign the reduce function to a new variable, e.g.:
(ES6)
const myObject = {_x000D_
ircEvent: 'PRIVMSG',_x000D_
method: 'newURI',_x000D_
regex: '^http://.*',_x000D_
};_x000D_
_x000D_
const myNewObject = Object.keys(myObject).reduce((obj, key) => {_x000D_
key !== 'regex' ? obj[key] = myObject[key] : null;_x000D_
return obj;_x000D_
}, {});_x000D_
_x000D_
console.log(myNewObject);
_x000D_
To start it right after installation, I generate a batch file with installutil followed by sc start
It's not ideal, but it works....
I solved this error using the bellow i get it from here
ionic cordova run browser
will load those native plugins that support browser
platform.
Firstly you make sure you have add permission in manifest file.
<uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW"/>
Check if the application has draw over other apps permission or not? This permission is by default available for API<23. But for API > 23 you have to ask for the permission in runtime.
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && !Settings.canDrawOverlays(this)) {
Intent intent = new Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION,
Uri.parse("package:" + getPackageName()));
startActivityForResult(intent, 1);
}
Use This code:
public class ChatHeadService extends Service {
private WindowManager mWindowManager;
private View mChatHeadView;
WindowManager.LayoutParams params;
public ChatHeadService() {
}
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public void onCreate() {
super.onCreate();
Language language = new Language();
//Inflate the chat head layout we created
mChatHeadView = LayoutInflater.from(this).inflate(R.layout.dialog_incoming_call, null);
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.O) {
params = new WindowManager.LayoutParams(
WindowManager.LayoutParams.WRAP_CONTENT,
WindowManager.LayoutParams.WRAP_CONTENT,
WindowManager.LayoutParams.TYPE_PHONE,
WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE
| WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL
| WindowManager.LayoutParams.FLAG_WATCH_OUTSIDE_TOUCH
| WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS,
PixelFormat.TRANSLUCENT);
params.gravity = Gravity.CENTER_HORIZONTAL | Gravity.TOP;
params.x = 0;
params.y = 100;
mWindowManager = (WindowManager) getSystemService(WINDOW_SERVICE);
mWindowManager.addView(mChatHeadView, params);
} else {
params = new WindowManager.LayoutParams(
WindowManager.LayoutParams.WRAP_CONTENT,
WindowManager.LayoutParams.WRAP_CONTENT,
WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY,
WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE
| WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL
| WindowManager.LayoutParams.FLAG_WATCH_OUTSIDE_TOUCH
| WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS,
PixelFormat.TRANSLUCENT);
params.gravity = Gravity.CENTER_HORIZONTAL | Gravity.TOP;
params.x = 0;
params.y = 100;
mWindowManager = (WindowManager) getSystemService(WINDOW_SERVICE);
mWindowManager.addView(mChatHeadView, params);
}
TextView tvTitle=mChatHeadView.findViewById(R.id.tvTitle);
tvTitle.setText("Incoming Call");
//Set the close button.
Button btnReject = (Button) mChatHeadView.findViewById(R.id.btnReject);
btnReject.setText(language.getText(R.string.reject));
btnReject.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//close the service and remove the chat head from the window
stopSelf();
}
});
//Drag and move chat head using user's touch action.
final Button btnAccept = (Button) mChatHeadView.findViewById(R.id.btnAccept);
btnAccept.setText(language.getText(R.string.accept));
LinearLayout linearLayoutMain=mChatHeadView.findViewById(R.id.linearLayoutMain);
linearLayoutMain.setOnTouchListener(new View.OnTouchListener() {
private int lastAction;
private int initialX;
private int initialY;
private float initialTouchX;
private float initialTouchY;
@Override
public boolean onTouch(View v, MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
//remember the initial position.
initialX = params.x;
initialY = params.y;
//get the touch location
initialTouchX = event.getRawX();
initialTouchY = event.getRawY();
lastAction = event.getAction();
return true;
case MotionEvent.ACTION_UP:
//As we implemented on touch listener with ACTION_MOVE,
//we have to check if the previous action was ACTION_DOWN
//to identify if the user clicked the view or not.
if (lastAction == MotionEvent.ACTION_DOWN) {
//Open the chat conversation click.
Intent intent = new Intent(ChatHeadService.this, HomeActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
//close the service and remove the chat heads
stopSelf();
}
lastAction = event.getAction();
return true;
case MotionEvent.ACTION_MOVE:
//Calculate the X and Y coordinates of the view.
params.x = initialX + (int) (event.getRawX() - initialTouchX);
params.y = initialY + (int) (event.getRawY() - initialTouchY);
//Update the layout with new X & Y coordinate
mWindowManager.updateViewLayout(mChatHeadView, params);
lastAction = event.getAction();
return true;
}
return false;
}
});
}
@Override
public void onDestroy() {
super.onDestroy();
if (mChatHeadView != null) mWindowManager.removeView(mChatHeadView);
}
}
@Wayne Burkett's answer is good. If you wanted to also extract the alpha value to get an rgba color, we could do this:
var r = p[0], g = p[1], b = p[2], a = p[3] / 255;
var rgba = "rgb(" + r + "," + g + "," + b + "," + a + ")";
I divided the alpha value by 255 because the ImageData object stores it as an integer between 0 - 255, but most applications (for example, CanvasRenderingContext2D.fillRect()
) require colors to be in valid CSS format, where the alpha value is between 0 and 1.
(Also remember that if you extract a transparent color and then draw it back onto the canvas, it will overlay whatever color is there previously. So if you drew the color rgba(0,0,0,0.1)
over the same spot 10 times, it would be black.)
Don't forget that Eclipse Platform was started by IBM. There are few platforms out there.
The advantage with Eclipse is that it can be customized to your development pleasure, plugins can be written for Eclipse to conform to your needs (e.g. The Eclipse "Easy Explorer" plugin for browsing the directory of your source in Windows Explorer). Eclipse allows you to also incorporate other languages/SDK's, such as C++, Silverlight projects, Android Projects for development. You can also easily manage resources in Eclipse.
In my experience NetBeans are resource intensive. Oracle JDeveloper and IntelliJ aren't free though. Oh yes, If you have issues or bugs with Eclipse, Eclipse has the ability to restart and submit the crash to Eclipse servers.
before you send the email you can press <ESC> f
(Escape followed by f) to change the From:
Address.
Constraint: This only works if you use mutt in curses mode and do not wan't to script it or if you want to change the address permanent. Then the other solutions are way better!
This link contains relevant information on detecting versions of Internet Explorer:
http://tanalin.com/en/articles/ie-version-js/
Example:
if (document.all && !document.addEventListener) {
alert('IE8 or older.');
}
no its not like that,here is Example for the support of my answer ---->the clear difference is visible ,when you go for HTTP Compression,which allows you to compress the data while travelling from Server to Client and the Type of this data automatically becomes as "gzip" which Tells browser that bowser got a zipped data and it has to upzip it,this is a example where Type really matters at Bowser.
A perl-solution:
perl -nE 'say $1 if /id=(\d+)/' filename
imho: Apache HTTP Client
usage example:
import org.apache.commons.httpclient.*;
import org.apache.commons.httpclient.methods.*;
import org.apache.commons.httpclient.params.HttpMethodParams;
import java.io.*;
public class HttpClientTutorial {
private static String url = "http://www.apache.org/";
public static void main(String[] args) {
// Create an instance of HttpClient.
HttpClient client = new HttpClient();
// Create a method instance.
GetMethod method = new GetMethod(url);
// Provide custom retry handler is necessary
method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,
new DefaultHttpMethodRetryHandler(3, false));
try {
// Execute the method.
int statusCode = client.executeMethod(method);
if (statusCode != HttpStatus.SC_OK) {
System.err.println("Method failed: " + method.getStatusLine());
}
// Read the response body.
byte[] responseBody = method.getResponseBody();
// Deal with the response.
// Use caution: ensure correct character encoding and is not binary data
System.out.println(new String(responseBody));
} catch (HttpException e) {
System.err.println("Fatal protocol violation: " + e.getMessage());
e.printStackTrace();
} catch (IOException e) {
System.err.println("Fatal transport error: " + e.getMessage());
e.printStackTrace();
} finally {
// Release the connection.
method.releaseConnection();
}
}
}
some highlight features:
git diff --name-only --diff-filter=U
For anyone having issues with this on https://forge.laravel.com, I managed to get this to work using a compilation of SO answers;
You will need the sudo password.
sudo nano /etc/nginx/conf.d/uploads.conf
Replace contents with the following;
fastcgi_buffers 8 16k;
fastcgi_buffer_size 32k;
client_max_body_size 24M;
client_body_buffer_size 128k;
client_header_buffer_size 5120k;
large_client_header_buffers 16 5120k;
This can happen if you have a newline (or other control character) in a JSON string literal.
{"foo": "bar
baz"}
If you are the one producing the data, replace actual newlines with escaped ones "\\n"
when creating your string literals.
{"foo": "bar\nbaz"}
ls | xargs -I{} git -C {} pull
To do it in parallel:
ls | xargs -P10 -I{} git -C {} pull
according to me this answer is useful for you:
def casear(a,key):
str=""
if key>26:
key%=26
for i in range(0,len(a)):
if a[i].isalpha():
b=ord(a[i])
b+=key
#if b>90: #if upper case letter ppear in your string
# c=b-90 #if upper case letter ppear in your string
# str+=chr(64+c) #if upper case letter ppear in your string
if b>122:
c=b-122
str+=chr(96+c)
else:
str+=chr(b)
else:
str+=a[i]
print str
a=raw_input()
key=int(input())
casear(a,key)
This function shifts all letter to right according to given key.
if the problem is to call. you can call it using this method.
yourController obj= new yourController();
obj.yourAction();
Your web pages are served by an application pool. If you disable/stop the application pool, and anyone tries to browse the application, you will get a Service Unavailable. It can happen due to multiple reasons...
Your application may have crashed [check the event viewer and see if you can find event logs in your Application/System log]
Your application may be crashing very frequently. If an app pool crashes for 5 times in 5 minutes [check your application pool settings for rapid fail], your application pool is disabled by IIS and you will end up getting this message.
In either case, the issue is that your worker process is failing and you should troubleshoot it from crash perspective.
What is a Crash (technically)... in ASP.NET and what to do if it happens?
now i got it finally! make sure that there are no spaces before and after the path and put the semi-colon on both sides without spaces
A (partial) practical work-around is to put things into a throw-away function.
Pasting
x = 1
x += 1
print(x)
results in
>>> x = 1
x += 1
print(x)
File "<stdin>", line 1
x += 1
print(x)
^
SyntaxError: multiple statements found while compiling a single statement
>>>
However, pasting
def abc():
x = 1
x += 1
print(x)
works:
>>> def abc():
x = 1
x += 1
print(x)
>>> abc()
2
>>>
Of course, this is OK for a quick one-off, won't work for everything you might want to do, etc. But then, going to ipython
/ jupyter qtconsole
is probably the next simplest option.
$.fn.blink = function (delay) {
delay = delay || 500;
return this.each(function () {
var element = $(this);
var interval = setInterval(function () {
element.fadeOut((delay / 3), function() {
element.fadeIn(delay / 3);
})
}, delay);
element.data('blinkInterval', interval);
});
};
$.fn.stopBlinking = function() {
return this.each(function() {
var element = $(this);
element.stop(true, true);
clearInterval(element.data('blinkInterval'));
});
};
No, static methods aren't associated with an instance; they belong to the class. Static methods are your second example; instance methods are the first.
<body onbeforeunload="ConfirmClose()" onunload="HandleOnClose()">
var myclose = false;
function ConfirmClose()
{
if (event.clientY < 0)
{
event.returnValue = 'You have closed the browser. Do you want to logout from your application?';
setTimeout('myclose=false',10);
myclose=true;
}
}
function HandleOnClose()
{
if (myclose==true)
{
//the url of your logout page which invalidate session on logout
location.replace('/contextpath/j_spring_security_logout') ;
}
}
//This is working in IE7, if you are closing tab or browser with only one tab
I found out why this happening.
After looking at my settings on my wamp, i did not check http headers, since activated this, it now works.
Thank you everyone for trying to solve this. :)
Under Configuration Manager and Network Configuration and Protocols for your instance is TCP/IP Enabled? That could be the problem.
You cannot compare date-strings. It is good habit to use PHP's DateTime
object instead:
$paymentDate = new DateTime(); // Today
echo $paymentDate->format('d/m/Y'); // echos today!
$contractDateBegin = new DateTime('2001-01-01');
$contractDateEnd = new DateTime('2015-01-01');
if (
$paymentDate->getTimestamp() > $contractDateBegin->getTimestamp() &&
$paymentDate->getTimestamp() < $contractDateEnd->getTimestamp()){
echo "is between";
}else{
echo "NO GO!";
}
Maybe not on Laravel 4 this time, but on L5.2* I had similar issue:
I simply changed the ownership of the storage/logs
directory to www-data
with:
# chown -R www-data:www-data logs
PS: This is on Ubuntu 15 and with apache.
My logs
directory now looks like:
drwxrwxr-x 2 www-data www-data 4096 jaan 23 09:39 logs/
Yes, should try reinstall mysql, but use the --reinstall
flag to force a package reconfiguration. So the operating system service configuration is not skipped:
sudo apt --reinstall install mysql-server
For your case, and 99.9% of all others elclanrs
answer is correct.
But because undefined
is a valid value, if someone were to test for an uninitialized variable
var pagetype; //== undefined
if (typeof pagetype === 'undefined') //true
the only 100% reliable way to determine if a var exists is to catch the exception;
var exists = false;
try { pagetype; exists = true;} catch(e) {}
if (exists && ...) {}
But I would never write it this way
shift
can be used in places where you want to get the first element (index=0
) of an array and chain with other array methods.
example:
const comps = [{}, {}, {}]
const specComp = comps
.map(fn1)
.filter(fn2)
.shift()
Remember shift
mutates the array, which is very different from accessing via an indexer.
I have the complete shortcuts list:
First, to find your socket file:
mysqladmin variables | grep socket
For me, this gives:
| socket | /tmp/mysql.sock |
Then, add a line to your config/database.yml
:
development:
adapter: mysql2
host: localhost
username: root
password: xxxx
database: xxxx
socket: /tmp/mysql.sock
sh -x script [arg1 ...]
bash -x script [arg1 ...]
These give you a trace of what is being executed. (See also 'Clarification' near the bottom of the answer.)
Sometimes, you need to control the debugging within the script. In that case, as Cheeto reminded me, you can use:
set -x
This turns debugging on. You can then turn it off again with:
set +x
(You can find out the current tracing state by analyzing $-
, the current flags, for x
.)
Also, shells generally provide options '-n
' for 'no execution' and '-v
' for 'verbose' mode; you can use these in combination to see whether the shell thinks it could execute your script — occasionally useful if you have an unbalanced quote somewhere.
There is contention that the '-x
' option in Bash is different from other shells (see the comments). The Bash Manual says:
-x
Print a trace of simple commands, for
commands, case
commands, select
commands, and arithmetic for
commands and their arguments or associated word lists after they are expanded and before they are executed. The value of the PS4
variable is expanded and the resultant value is printed before the command and its expanded arguments.
That much does not seem to indicate different behaviour at all. I don't see any other relevant references to '-x
' in the manual. It does not describe differences in the startup sequence.
Clarification: On systems such as a typical Linux box, where '/bin/sh
' is a symlink to '/bin/bash
' (or wherever the Bash executable is found), the two command lines achieve the equivalent effect of running the script with execution trace on. On other systems (for example, Solaris, and some more modern variants of Linux), /bin/sh
is not Bash, and the two command lines would give (slightly) different results. Most notably, '/bin/sh
' would be confused by constructs in Bash that it does not recognize at all. (On Solaris, /bin/sh
is a Bourne shell; on modern Linux, it is sometimes Dash — a smaller, more strictly POSIX-only shell.) When invoked by name like this, the 'shebang' line ('#!/bin/bash
' vs '#!/bin/sh
') at the start of the file has no effect on how the contents are interpreted.
The Bash manual has a section on Bash POSIX mode which, contrary to a long-standing but erroneous version of this answer (see also the comments below), does describe in extensive detail the difference between 'Bash invoked as sh
' and 'Bash invoked as bash
'.
When debugging a (Bash) shell script, it will be sensible and sane — necessary even — to use the shell named in the shebang line with the -x
option. Otherwise, you may (will?) get different behaviour when debugging from when running the script.
I believe the kernel raises SIGBUS when an application exhibits data misalignment on the data bus. I think that since most[?] modern compilers for most processors pad / align the data for the programmers, the alignment troubles of yore (at least) mitigated, and hence one does not see SIGBUS too often these days (AFAIK).
From: Here
If you want to use the font to draw with graphics2d or similar, this works:
InputStream stream = ClassLoader.getSystemClassLoader().getResourceAsStream("roboto-bold.ttf")
Font font = Font.createFont(Font.TRUETYPE_FONT, stream).deriveFont(48f)
In eclipse, you must be careful to create a "source folder" (File->New->Source Folder). This way, it's automatically on your classpath, and, more importantly, Eclipse knows that these are compilable files. It's picky that way.
Make a png image with same name (favicon.png
) and change the name in these files:
index.html
:
<link rel="icon" type="image/x-icon" href="favicon.png" />
angular-cli.json
:
"assets": [
"assets",
"favicon.png"
],
And you will never see the angular default icon again.
Size should be 32x32, if more than this it will not display.
NOTE: This will not work with Angular 9
For angular 9 you have to put favicon inside assets then give path like
<link rel="icon" type="image/x-icon" href="assets/favicon.png">
_x000D_
I ran into a similar issue. Sometimes, you wont find xdebug.so in php.ini. In which case, execute phpinfo()
in a php file and check for Additional .ini files parsed
. Here you'll see more ini files. One of these will be xdebug's ini file. Just remove (or rename) this file, restart apache, and this extension will be removed.
You need to stringify the json, not calling toString
var buf = Buffer.from(JSON.stringify(obj));
And for converting string to json obj :
var temp = JSON.parse(buf.toString());
In Swift 3.0 :
var imageView : UIImageView
imageView = UIImageView(frame:CGRect(x:10, y:50, width:100, height:300));
imageView.image = UIImage(named:"Test.jpeg")
self.view.addSubview(imageView)
Here is a code example which may help:
using System;
using System.Collections.Generic;
using System.Text;
namespace Event_Example
{
// First we have to define a delegate that acts as a signature for the
// function that is ultimately called when the event is triggered.
// You will notice that the second parameter is of MyEventArgs type.
// This object will contain information about the triggered event.
public delegate void MyEventHandler(object source, MyEventArgs e);
// This is a class which describes the event to the class that receives it.
// An EventArgs class must always derive from System.EventArgs.
public class MyEventArgs : EventArgs
{
private string EventInfo;
public MyEventArgs(string Text) {
EventInfo = Text;
}
public string GetInfo() {
return EventInfo;
}
}
// This next class is the one which contains an event and triggers it
// once an action is performed. For example, lets trigger this event
// once a variable is incremented over a particular value. Notice the
// event uses the MyEventHandler delegate to create a signature
// for the called function.
public class MyClass
{
public event MyEventHandler OnMaximum;
private int i;
private int Maximum = 10;
public int MyValue
{
get { return i; }
set
{
if(value <= Maximum) {
i = value;
}
else
{
// To make sure we only trigger the event if a handler is present
// we check the event to make sure it's not null.
if(OnMaximum != null) {
OnMaximum(this, new MyEventArgs("You've entered " +
value.ToString() +
", but the maximum is " +
Maximum.ToString()));
}
}
}
}
}
class Program
{
// This is the actual method that will be assigned to the event handler
// within the above class. This is where we perform an action once the
// event has been triggered.
static void MaximumReached(object source, MyEventArgs e) {
Console.WriteLine(e.GetInfo());
}
static void Main(string[] args) {
// Now lets test the event contained in the above class.
MyClass MyObject = new MyClass();
MyObject.OnMaximum += new MyEventHandler(MaximumReached);
for(int x = 0; x <= 15; x++) {
MyObject.MyValue = x;
}
Console.ReadLine();
}
}
}
as of AS 1.2+ there is an auto-check for updates which will let you choose between the stable, dev, canary, and beta channels. However it is just a check instead of a full update script. It does require that you click to install and restart your install ( A problem for a remote server situation)
In build.gradle(Module:app) add this code
dependencies {
……..
compile 'com.google.android.gms:play-services:10.0.1’
……
}
If you still have a problem after that, then add this code in build.gradle(Module:app)
defaultConfig {
….
…...
multiDexEnabled true
}
dependencies {
…..
compile 'com.google.android.gms:play-services:10.0.1'
compile 'com.android.support:multidex:1.0.1'
}
var appBanners = document.getElementsByClassName('appBanner');
for (var i = 0; i < appBanners.length; i ++) {
appBanners[i].style.display = 'none';
}
There is always the easy way.
import numpy as np
print(np.matrix(A))
The Python reference manual includes several string literals that can be used in a string. These special sequences of characters are replaced by the intended meaning of the escape sequence.
Here is a table of some of the more useful escape sequences and a description of the output from them.
Escape Sequence Meaning
\t Tab
\\ Inserts a back slash (\)
\' Inserts a single quote (')
\" Inserts a double quote (")
\n Inserts a ASCII Linefeed (a new line)
Basic Example
If i wanted to print some data points separated by a tab space I could print this string.
DataString = "0\t12\t24"
print (DataString)
Returns
0 12 24
Example for Lists
Here is another example where we are printing the items of list and we want to sperate the items by a TAB.
DataPoints = [0,12,24]
print (str(DataPoints[0]) + "\t" + str(DataPoints[1]) + "\t" + str(DataPoints[2]))
Returns
0 12 24
Raw Strings
Note that raw strings (a string which include a prefix "r"), string literals will be ignored. This allows these special sequences of characters to be included in strings without being changed.
DataString = r"0\t12\t24"
print (DataString)
Returns
0\t12\t24
Which maybe an undesired output
String Lengths
It should also be noted that string literals are only one character in length.
DataString = "0\t12\t24"
print (len(DataString))
Returns
7
The raw string has a length of 9.
Note: You may also want to run
git clean -fd
as
git reset --hard
will not remove untracked files, where as git-clean will remove any files from the tracked root directory that are not under git tracking. WARNING - BE CAREFUL WITH THIS! It is helpful to run a dry-run with git-clean first, to see what it will delete.
This is also especially useful when you get the error message
~"performing this command will cause an un-tracked file to be overwritten"
Which can occur when doing several things, one being updating a working copy when you and your friend have both added a new file of the same name, but he's committed it into source control first, and you don't care about deleting your untracked copy.
In this situation, doing a dry run will also help show you a list of files that would be overwritten.
Dim sql As String = "
SELECT ID, Description
FROM inventory
ORDER BY DateAdded
"
You can combine them with string interpolation to maximize usefullness:
Dim primaryKey As String = "ID"
Dim inventoryTable As String = "inventory"
Dim sql As String = $"
SELECT {primaryKey}, Description
FROM {inventoryTable}
ORDER BY DateAdded
"
Note that interpolated strings begin with $
and you need to take care of "
, {
and }
contained inside – convert them into ""
, {{
or }}
respectively.
Here you can see actual syntax highlighting of interpolated parts of the above code example:
If you wonder if their recognition by the Visual Studio editor also works with refactoring (e.g. mass-renaming the variables), then you are right, code refactoring works with these. Not mentioning that they also support IntelliSense, reference counting or code analysis.
To plot text on a ggplot
you use the geom_text
. But I find it helpful to summarise the data first using ddply
dfl <- ddply(df, .(x), summarize, y=length(x))
str(dfl)
Since the data is pre-summarized, you need to remember to change add the stat="identity"
parameter to geom_bar
:
ggplot(dfl, aes(x, y=y, fill=x)) + geom_bar(stat="identity") +
geom_text(aes(label=y), vjust=0) +
opts(axis.text.x=theme_blank(),
axis.ticks=theme_blank(),
axis.title.x=theme_blank(),
legend.title=theme_blank(),
axis.title.y=theme_blank()
)
This is how you Delete From a slice the idiomatic way. You don't need to build a function it is built into the append. Try it here https://play.golang.org/p/QMXn9-6gU5P
z := []int{9, 8, 7, 6, 5, 3, 2, 1, 0}
fmt.Println(z) //will print Answer [9 8 7 6 5 3 2 1 0]
z = append(z[:2], z[4:]...)
fmt.Println(z) //will print Answer [9 8 5 3 2 1 0]
this work for me, just prevent the event, add the url to an <a>
tag
then trigger the click event on that tag
.
Js
$('.myBtn').on('click', function(event) {
event.preventDefault();
$(this).attr('href',"http://someurl.com");
$(this).trigger('click');
});
HTML
<a href="#" class="myBtn" target="_blank">Go</a>
Here is a trick for getting automatic keyboard dismissal behavior with no code at all. In the nib, edit the First Responder proxy object in the Identity inspector, adding a new first responder action; let's call it dummy:
. Now hook the Did End on Exit event of the text field to the dummy:
action of the First Responder proxy object. That's it! Since the text field's Did End on Exit event now has an action–target pair, the text field automatically dismisses its keyboard when the user taps Return; and since there is no penalty for not finding a handler for a message sent up the responder chain, the app doesn't crash even though there is no implementation of dummy:
anywhere.
This will do the job too:
echo "$pid"|awk '{print $2}'
You can set the click handler in xml with these attribute:
android:onClick="onClick"
android:clickable="true"
Don't forget the clickable attribute, without it, the click handler isn't called.
main.xml
...
<TextView
android:id="@+id/click"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Click Me"
android:textSize="55sp"
android:onClick="onClick"
android:clickable="true"/>
...
MyActivity.java
public class MyActivity extends Activity {
public void onClick(View v) {
...
}
}
Travis-ci and Jenkins, while both are tools for continuous integration are very different.
Travis is a hosted service (free for open source) while you have to host, install and configure Jenkins.
Travis does not have jobs as in Jenkins. The commands to run to test the code are taken from a file named .travis.yml
which sits along your project code. This makes it easy to have different test code per branch since each branch can have its own version of the .travis.yml file.
You can have a similar feature with Jenkins if you use one of the following plugins:
.jervis.yml
file found at the root of project code. If .jervis.yml
does not exist, it will fall back to using .travis.yml
file instead.There are other hosted services you might also consider for continuous integration (non exhaustive list):
You might want to stay with Jenkins because you are familiar with it or don't want to depend on 3rd party for your continuous integration system. Else I would drop Jenkins and go with one of the free hosted CI services as they save you a lot of trouble (host, install, configure, prepare jobs)
Depending on where your code repository is hosted I would make the following choices:
To setup Travis-CI on a github project, all you have to do is:
The features you get are:
If you use the load balancer & Nginx, config them without modify code.
Nginx:
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
Tomcat's server.xml Engine:
<Valve className="org.apache.catalina.valves.RemoteIpValve"
remoteIpHeader="X-Forwarded-For"
protocolHeader="X-Forwarded-Proto"
protocolHeaderHttpsValue="https"/>
If only modify Nginx config file, the java code should be:
String XForwardedProto = request.getHeader("X-Forwarded-Proto");
Try this:
class JSONListView(ListView):
queryset = Users.objects.all()
def get(self, request, *args, **kwargs):
data = {}
data["users"] = get_json_list(queryset)
return JSONResponse(data)
def get_json_list(query_set):
list_objects = []
for obj in query_set:
dict_obj = {}
for field in obj._meta.get_fields():
try:
if field.many_to_many:
dict_obj[field.name] = get_json_list(getattr(obj, field.name).all())
continue
dict_obj[field.name] = getattr(obj, field.name)
except AttributeError:
continue
list_objects.append(dict_obj)
return list_objects
Just add: word-break: break-word;
to you table class.
Use vim. ^-^ (gVim, to be precise)
You'll have it all (with some plugins).
Btw, snippetsEmu is a nice tool for coding with useful snippets (like in TextMate). You can use (or modify) a pre-made package or make your own.
Building on @shabunc's answer, this would allow enforcing either the key or the value — or both — to be anything you want to enforce.
type IdentifierKeys = 'my.valid.key.1' | 'my.valid.key.2';
type IdentifierValues = 'my.valid.value.1' | 'my.valid.value.2';
let stuff = new Map<IdentifierKeys, IdentifierValues>();
Should also work using enum
instead of a type
definition.
Installing the mysql gem on OSX
in a terminal.. First do a ‘locate mysql_config’ and then replace the path in the following command with where that file is.
$ sudo gem install mysql -- —–with-mysql-config=/usr/local/mysql/bin/mysql_config
Building native extensions. This could take a while…
Successfully installed mysql-2.7
1 gem installed
@font-face {
font-family: Kaffeesatz;
src: url(YanoneKaffeesatz-Thin.otf);
font-weight: 200;
}
@font-face {
font-family: Kaffeesatz;
src: url(YanoneKaffeesatz-Light.otf);
font-weight: 300;
}
@font-face {
font-family: Kaffeesatz;
src: url(YanoneKaffeesatz-Regular.otf);
font-weight: normal;
}
@font-face {
font-family: Kaffeesatz;
src: url(YanoneKaffeesatz-Bold.otf);
font-weight: bold;
}
h3, h4, h5, h6 {
font-size:2em;
margin:0;
padding:0;
font-family:Kaffeesatz;
font-weight:normal;
}
h6 { font-weight:200; }
h5 { font-weight:300; }
h4 { font-weight:normal; }
h3 { font-weight:bold; }
Have you taken a look at ExpandoObject?
From MSDN:
The ExpandoObject class enables you to add and delete members of its instances at run time and also to set and get values of these members. This class supports dynamic binding, which enables you to use standard syntax like sampleObject.sampleMember instead of more complex syntax like sampleObject.GetAttribute("sampleMember").
Allowing you to do cool things like:
dynamic dynObject = new ExpandoObject();
dynObject.SomeDynamicProperty = "Hello!";
dynObject.SomeDynamicAction = (msg) =>
{
Console.WriteLine(msg);
};
dynObject.SomeDynamicAction(dynObject.SomeDynamicProperty);
Based on your actual code you may be more interested in:
public static dynamic GetDynamicObject(Dictionary<string, object> properties)
{
return new MyDynObject(properties);
}
public sealed class MyDynObject : DynamicObject
{
private readonly Dictionary<string, object> _properties;
public MyDynObject(Dictionary<string, object> properties)
{
_properties = properties;
}
public override IEnumerable<string> GetDynamicMemberNames()
{
return _properties.Keys;
}
public override bool TryGetMember(GetMemberBinder binder, out object result)
{
if (_properties.ContainsKey(binder.Name))
{
result = _properties[binder.Name];
return true;
}
else
{
result = null;
return false;
}
}
public override bool TrySetMember(SetMemberBinder binder, object value)
{
if (_properties.ContainsKey(binder.Name))
{
_properties[binder.Name] = value;
return true;
}
else
{
return false;
}
}
}
That way you just need:
var dyn = GetDynamicObject(new Dictionary<string, object>()
{
{"prop1", 12},
});
Console.WriteLine(dyn.prop1);
dyn.prop1 = 150;
Deriving from DynamicObject allows you to come up with your own strategy for handling these dynamic member requests, beware there be monsters here: the compiler will not be able to verify a lot of your dynamic calls and you won't get intellisense, so just keep that in mind.
CMD
+ f
To search the (word) you want to change.Option
+ Enter
To select all word you search for.Just update the first word and it will update all the selected.
U may do as I have written from my deleted account (ban for new posts :( there was). Its rather simple and nice looking.
Im using 3-rd one of these 3 ones usually, also I wasny checking 1 and 2 version.
from matplotlib.pyplot import cm
import numpy as np
#variable n should be number of curves to plot (I skipped this earlier thinking that it is obvious when looking at picture - sorry my bad mistake xD): n=len(array_of_curves_to_plot)
#version 1:
color=cm.rainbow(np.linspace(0,1,n))
for i,c in zip(range(n),color):
ax1.plot(x, y,c=c)
#or version 2: - faster and better:
color=iter(cm.rainbow(np.linspace(0,1,n)))
c=next(color)
plt.plot(x,y,c=c)
#or version 3:
color=iter(cm.rainbow(np.linspace(0,1,n)))
for i in range(n):
c=next(color)
ax1.plot(x, y,c=c)
example of 3:
Ship RAO of Roll vs Ikeda damping in function of Roll amplitude A44
This worked for me:
//Button method example
@IBAction func LogOutPressed(_ sender: UIBarButtonItem) {
do {
try Auth.auth().signOut()
navigationController?.popToRootViewController(animated: true)
} catch let signOutError as NSError {
print ("Error signing out: %@", signOutError)
}
}
In addition to Jon Skeet's answer, you can also use the group by expressions to get the unique groups along w/ a count for each groups iterations:
var query = from e in doc.Elements("whatever")
group e by new { id = e.Key, val = e.Value } into g
select new { id = g.Key.id, val = g.Key.val, count = g.Count() };
First of all install nodejs:
sudo apt-get install nodejs
Then install npm:
sudo apt-get install npm
Then install bower:
npm install -g bower
For any of the npm package tutorial visit: https://www.npmjs.com/
Here just search the package and you can find how to install, documentation and tutorials as well.
P.S. This is just a very common solution. If your problem still exists you can try the advanced one.
Created a stored procedure to list indexes for a table in database in SQL Server
create procedure _ListIndexes(@tableName nvarchar(200))
as
begin
/*
exec _ListIndexes '<YOUR TABLE NAME>'
*/
SELECT DB_NAME(DB_ID()) as DBName,SCH.name + '.' + TBL.name AS TableName,IDX.name as IndexName, IDX.type_desc AS IndexType,COL.Name as ColumnName,IC.*
FROM sys.tables AS TBL
INNER JOIN sys.schemas AS SCH ON TBL.schema_id = SCH.schema_id
INNER JOIN sys.indexes AS IDX ON TBL.object_id = IDX.object_id
INNER JOIN sys.index_columns IC ON IDX.object_id = IC.object_id and IDX.index_id = IC.index_id
INNER JOIN sys.columns COL ON ic.object_id = COL.object_id and IC.column_id = COL.column_id
where TBL.name = @tableName
ORDER BY TableName,IDX.name
end
You can escape (this is how this principle is called) the double quotes by prefixing them with another double quote. You can put them in a string as follows:
Dim MyVar as string = "some text ""hello"" "
This will give the MyVar
variable a value of some text "hello"
.
var values = new int[] {5,7,3};
var sortedValues = values.OrderBy(v => v).ToList(); // result 3,5,7
With Python 2, this doesn't work for non-English words in UTF-8. In this case decode('utf-8')
can help:
>>> s='????????'
>>> print s.lower()
????????
>>> print s.decode('utf-8').lower()
????????
Edit - This answer is a solution, but a much simpler and proper approach would be setting the tabindex
attribute on the canvas element (as suggested by hobberwickey).
You can't focus a canvas element. A simple work around this, would be to make your "own" focus.
var lastDownTarget, canvas;
window.onload = function() {
canvas = document.getElementById('canvas');
document.addEventListener('mousedown', function(event) {
lastDownTarget = event.target;
alert('mousedown');
}, false);
document.addEventListener('keydown', function(event) {
if(lastDownTarget == canvas) {
alert('keydown');
}
}, false);
}
If you are using 11G XE with Windows, along with tns listener restart, make sure Windows Event Log service is started.
From here I see the method setCompoundDrawablesWithIntrinsicBounds(int,int,int,int) can be used to do this.
One more solution to use this Unicode black circle >>
Start >> All Programs >> Accessories >> System Tools >> Character Map
Then select Arial font
and choose the Black circle
copy it and paste it into PasswordChar
property of the textbox.
That's it....
I'm not sure if this is related, but I had a similar problem which was fixed by copying these files from Anaconda3/Library/bin to Anaconda3/DLLs :
libcrypto-1_1-x64.dll
libssl-1_1-x64.dll
The shortest in terms of lines of code i can think of is for the first question.
>>> import numpy as np
>>> p = np.array([[1,2],[3,4]])
>>> p = np.append(p, [[5,6]], 0)
>>> p = np.append(p, [[7],[8],[9]],1)
>>> p
array([[1, 2, 7],
[3, 4, 8],
[5, 6, 9]])
And the for the second question
p = np.array(range(20))
>>> p.shape = (4,5)
>>> p
array([[ 0, 1, 2, 3, 4],
[ 5, 6, 7, 8, 9],
[10, 11, 12, 13, 14],
[15, 16, 17, 18, 19]])
>>> n = 2
>>> p = np.append(p[:n],p[n+1:],0)
>>> p = np.append(p[...,:n],p[...,n+1:],1)
>>> p
array([[ 0, 1, 3, 4],
[ 5, 6, 8, 9],
[15, 16, 18, 19]])
None of the above solutions seem to work if the width/height is less than the line resolution of quality you select. For example, the following doesn't work for me in Chrome:
<iframe width="720" height="480" src="//youtube.com/embed/hUezoHa1ZF4?autoplay=true&rel=0&vq=hd720" frameborder="0" allowfullscreen></iframe>
I want to show the high quality video, but not use up 1280 x 720 pixels on the webpage.
When I go to youtube itself, playing 720p video in a 720x480 window looks better than 480p at the same size. I want to play 720p in a 720x480 window (downsampled better quality). There is no good solution yet afaik.
you show fragment in a container (with id= fragmentcontainer) so you remove fragment with:
Fragment fragment = getSupportFragmentManager().findFragmentById(R.id.fragmentContainer);
fragmentTransaction.remove(fragment);
fragmentTransaction.addToBackStack(null);
fragmentTransaction.commit();
Couldn't add this as a comment, but in case anyone is interested in using the accepted answer with subplots, the divider should be formed on specific axes object (rather than on the numpy.ndarray returned from plt.subplots)
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.axes_grid1 import make_axes_locatable
data = np.arange(100, 0, -1).reshape(10, 10)
fig, ax = plt.subplots(ncols=2, nrows=2)
for row in ax:
for col in row:
im = col.imshow(data, cmap='bone')
divider = make_axes_locatable(col)
cax = divider.append_axes('right', size='5%', pad=0.05)
fig.colorbar(im, cax=cax, orientation='vertical')
plt.show()
@HostBinding
: This decorator binds a class property to a property of the host element.@HostListener
: This decorator binds a class method to an event of the host element.import { Component, HostListener, HostBinding } from '@angular/core';
@Component({
selector: 'app-root',
template: `<p>This is nice text<p>`,
})
export class AppComponent {
@HostBinding('style.color') color;
@HostListener('click')
onclick() {
this.color = 'blue';
}
}
In the above example the following occurs:
color
property in our AppComponent
class is bound to the style.color
property on the component. So whenever the color
property is updated so will the style.color
property of our component@Directive
:Although it can be used on component these decorators are often used in a attribute directives. When used in an @Directive
the host changes the element on which the directive is placed. For example take a look at this component template:
<p p_Dir>some paragraph</p>
Here p_Dir is a directive on the <p>
element. When @HostBinding
or @HostListener
is used within the directive class the host will now refer to the <p>
.
I've wrote yet another JavaScript library, it might be better for you since it's very sensitive with the least possible false positives, fast and small in size. I'm currently actively maintaining it so please do test it in the demo page and see how it would work for you.
From the Notes of Fred Swartz (fredosaurus) :
There are two types of methods.
Instance methods are associated with an object and use the instance variables of that object. This is the default.
Static methods use no instance variables of any object of the class they are defined in. If you define a method to be static, you will be given a rude message by the compiler if you try to access any instance variables. You can access static variables, but except for constants, this is unusual. Static methods typically take all they data from parameters and compute something from those parameters, with no reference to variables. This is typical of methods which do some kind of generic calculation. A good example of this are the many utility methods in the predefined Math
class.
From outside the defining class, an instance method is called by prefixing it with an object, which is then passed as an implicit parameter to the instance method, eg, inputTF.setText("");
A static method is called by prefixing it with a class name, eg, Math.max(i,j);
. Curiously, it can also be qualified with an object, which will be ignored, but the class of the object will be used.
Here is a typical static method:
class MyUtils {
. . .
//================================================= mean
public static double mean(int[] p) {
int sum = 0; // sum of all the elements
for (int i=0; i<p.length; i++) {
sum += p[i];
}
return ((double)sum) / p.length;
}//endmethod mean
. . .
}
The only data this method uses or changes is from parameters (or local variables of course).
static
The above mean()
method would work just as well if it wasn't declared static, as long as it was called from within the same class. If called from outside the class and it wasn't declared static, it would have to be qualified (uselessly) with an object. Even when used within the class, there are good reasons to define a method as static when it could be.
There are two cases.
Called from within the same class
Just write the static method name. Eg:
// Called from inside the MyUtils class
double avgAtt = mean(attendance);
Called from outside the class
If a method (static or instance) is called from another class, something must be given before the method name to specify the class where the method is defined. For instance methods, this is the object that the method will access. For static methods, the class name should be specified. Eg:
// Called from outside the MyUtils class.
double avgAtt = MyUtils.mean(attendance);
If an object is specified before it, the object value will be ignored and the the class of the object will be used.
Altho a static
method can't access instance variables, it can access static
variables. A common use of static variables is to define "constants". Examples from the Java library are Math.PI
or Color.RED
. They are qualified with the class name, so you know they are static
. Any method, static
or not, can access static
variables. Instance variables can be accessed only by instance methods.
What's a little peculiar, and not recommended, is that an object of a class may be used instead of the class name to access static methods. This is bad because it creates the impression that some instance variables in the object are used, but this isn't the case.
For me the problem was solved by stocking my datas into an object (here "datas").
NgApp.controller('MyController', function($scope) {_x000D_
_x000D_
$scope.my_title = ""; // This don't work in ng-click function called_x000D_
_x000D_
$scope.datas = {_x000D_
'my_title' : "",_x000D_
};_x000D_
_x000D_
$scope.doAction = function() {_x000D_
console.log($scope.my_title); // bad value_x000D_
console.log($scope.datas.my_title); // Good Value binded by'ng-model'_x000D_
}_x000D_
_x000D_
_x000D_
});
_x000D_
I Hop it will help
ES2015 and later
In ES2015, parameter destructuring can be used to simulate named parameters. It would require the caller to pass an object, but you can avoid all of the checks inside the function if you also use default parameters:
myFunction({ param1 : 70, param2 : 175});
function myFunction({param1, param2}={}){
// ...function body...
}
// Or with defaults,
function myFunc({
name = 'Default user',
age = 'N/A'
}={}) {
// ...function body...
}
ES5
There is a way to come close to what you want, but it is based on the output of Function.prototype.toString
[ES5], which is implementation dependent to some degree, so it might not be cross-browser compatible.
The idea is to parse the parameter names from the string representation of the function so that you can associate the properties of an object with the corresponding parameter.
A function call could then look like
func(a, b, {someArg: ..., someOtherArg: ...});
where a
and b
are positional arguments and the last argument is an object with named arguments.
For example:
var parameterfy = (function() {
var pattern = /function[^(]*\(([^)]*)\)/;
return function(func) {
// fails horribly for parameterless functions ;)
var args = func.toString().match(pattern)[1].split(/,\s*/);
return function() {
var named_params = arguments[arguments.length - 1];
if (typeof named_params === 'object') {
var params = [].slice.call(arguments, 0, -1);
if (params.length < args.length) {
for (var i = params.length, l = args.length; i < l; i++) {
params.push(named_params[args[i]]);
}
return func.apply(this, params);
}
}
return func.apply(null, arguments);
};
};
}());
Which you would use as:
var foo = parameterfy(function(a, b, c) {
console.log('a is ' + a, ' | b is ' + b, ' | c is ' + c);
});
foo(1, 2, 3); // a is 1 | b is 2 | c is 3
foo(1, {b:2, c:3}); // a is 1 | b is 2 | c is 3
foo(1, {c:3}); // a is 1 | b is undefined | c is 3
foo({a: 1, c:3}); // a is 1 | b is undefined | c is 3
There are some drawbacks to this approach (you have been warned!):
undefined
(that's different from having no value at all). That means you cannot use arguments.length
to test how many arguments have been passed.Instead of having a function creating the wrapper, you could also have a function which accepts a function and various values as arguments, such as
call(func, a, b, {posArg: ... });
or even extend Function.prototype
so that you could do:
foo.execute(a, b, {posArg: ...});
I am facing to this problem so many times till I have 32bit PL/SQL Developer and 64bit Oracle DB or Oracle Client.
The solution is:
Edit or create a TNSNAMES.ORA file in c:\app\admin\product\11.2.0\client_1\NETWORK\admin folder like mentioned above.
Try with TNSPING in console like
C:>tnsping ORCL
If still have problem, set the TNS_ADMIN Enviroment properties value pointing to the folder where the TNSNAMES.ORA located, like: c:\app\admin\product\11.2.0\client_1\network\admin
The character set is part of the locale, which is determined by the value of NLS_LANG
. As the documentation makes clear this is an operating system variable:
NLS_LANG
is set as an environment variable on UNIX platforms.NLS_LANG
is set in the registry on Windows platforms.
Now we can use ALTER SESSION
to change the values for a couple of locale elements, NLS_LANGUAGE and NLS_TERRITORY. But not, alas, the character set. The reason for this discrepancy is - I think - that the language and territory simply effect how Oracle interprets the stored data, e.g. whether to display a comma or a period when displaying a large number. Wheareas the character set is concerned with how the client application renders the displayed data. This information is picked up by the client application at startup time, and cannot be changed from within.
I remember when "ANSI" text referred to the pseudo VT-100 escape codes usable in DOS through the ANSI.SYS driver to alter the flow of streaming text.... Probably not what you are referring to but if it is see http://en.wikipedia.org/wiki/ANSI_escape_code
Here's another way you could try, that doesn't need that ID field.
select some_column, min(another_column)
from i_have_a_table
group by some_column
Still I agree with lfagundes that you should add some primary key ..
Also beware that by doing this, you cannot (easily) get at the other values is the same row as the resulting some_colum, another_column pair! You'd need lfagundes apprach and a PK to do that!
Which operating system?
For windows machines, if you're writing a server to scale well, and therefore using I/O Completion Ports and async I/O, then the main limitation is the amount of non-paged pool that you're using for each active connection. This translates directly into a limit based on the amount of memory that your machine has installed (non-paged pool is a finite, fixed size amount that is based on the total memory installed).
For connections that don't see much traffic you can reduce make them more efficient by posting 'zero byte reads' which don't use non-paged pool and don't affect the locked pages limit (another potentially limited resource that may prevent you having lots of socket connections open).
Apart from that, well, you will need to profile but I've managed to get more than 70,000 concurrent connections on a modestly specified (760MB memory) server; see here http://www.lenholgate.com/blog/2005/11/windows-tcpip-server-performance.html for more details.
Obviously if you're using a less efficient architecture such as 'thread per connection' or 'select' then you should expect to achieve less impressive figures; but, IMHO, there's simply no reason to select such architectures for windows socket servers.
Edit: see here http://blogs.technet.com/markrussinovich/archive/2009/03/26/3211216.aspx; the way that the amount of non-paged pool is calculated has changed in Vista and Server 2008 and there's now much more available.
If you are using the animation listener, set v.setAnimationListener(null)
. Use the following code with all options.
v.getAnimation().cancel();
v.clearAnimation();
animation.setAnimationListener(null);
Use 'Exists' which returns either 0 or 1.
The query will be like:
SELECT EXISTS(SELECT * FROM USER WHERE UserID = 20070022)
We have lot of answers to this question. This answer may be helpful in some scenarios If you want to ignore the null values you can use the NOT_NULL in class level. as below
@JsonInclude(Include.NON_NULL)
class Foo
{
String bar;
}
Some times you may need to ignore the empty values such as you may have initialized the arrayList but there is no elements in that list.In that time using NOT_EMPTY annotation to ignore those empty value fields
@JsonInclude(Include.NON_EMPTY)
class Foo
{
String bar;
}
Just to add something I was missing from all the answers - even if it seems to be silly and obvious as soon as you know:
The file has to be named "App.config" or "app.config" and can be located in your project at the same level as e.g. Program.cs.
I do not know if other locations are possible, other names (like application.conf, as suggested in the ODP.net documentation) did not work for me.
PS. I started with Visual Studio Code and created a new project with "dotnet new". No configuration file is created in this case, I am sure there are other cases. PPS. You may need to add a nuget package to be able to read the config file, in case of .NET CORE it would be "dotnet add package System.Configuration.ConfigurationManager --version 4.5.0"
I would suggest the use of jquery mate.
With jQuery you would then be able to get the id of this element by
$(this).attr('id');
without jquery, if I remember correctly we used to access the id with a
this.id
Hope that helps :)
You should use keyPressed
if you want an immediate effect, and keyReleased
if you want the effect after you release the key. You cannot use keyTyped
because F5 is not a character. keyTyped
is activated only when an character is pressed.
You can play with delay
prop of animation, just set visibility:visible
after a delay, demo:
@keyframes delayedShow {_x000D_
to {_x000D_
visibility: visible;_x000D_
}_x000D_
}_x000D_
_x000D_
.delayedShow{_x000D_
visibility: hidden;_x000D_
animation: 0s linear 2.3s forwards delayedShow ;_x000D_
}
_x000D_
So, Where are you?_x000D_
_x000D_
<div class="delayedShow">_x000D_
Hey, I'm here!_x000D_
</div>
_x000D_
You can use the Ripple emulator on Chrome.
I would suggest creating your package structure by feature, and not by the implementation layer. A good write up on this is Java practices: Package by feature, not layer
Note: tcpdump requires root privileges, so you'll have to root your phone if not done already. Here's an ARM binary of tcpdump (this works for my Samsung Captivate). If you prefer to build your own binary, instructions are here (yes, you'd likely need to cross compile).
Also, check out Shark For Root (an Android packet capture tool based on tcpdump).
I don't believe tcpdump can monitor traffic by specific process ID. The strace method that Chris Stratton refers to seems like more effort than its worth. It would be simpler to monitor specific IPs and ports used by the target process. If that info isn't known, capture all traffic during a period of process activity and then sift through the resulting pcap with Wireshark.
public static String fillString(int count,char c) {
StringBuilder sb = new StringBuilder( count );
for( int i=0; i<count; i++ ) {
sb.append( c );
}
return sb.toString();
}
What is wrong?
I did it in this simple way, with Web API 2.0. You can remove UseDefaultCredentials. I used it for my own use cases.
List<YourObject> listObjects = new List<YourObject>();
string response = "";
using (var client = new WebClient() { UseDefaultCredentials = true })
{
response = client.DownloadString(apiUrl);
}
listObjects = JsonConvert.DeserializeObject<List<YourObject>>(response);
return listObjects;
You can use 9 patch in Android Studio to make borders!
I was looking for a solution but I did not find any so I skipped that part.
Then I went to the Google images of Firebase assets and I accidentally discovered that they use 9patch.
Here's the link: https://developer.android.com/studio/write/draw9patch
You just need to drag where the edges are.
It's just like border edge in Unity.
Right click on your project -> properties -> build path. Add to your build path jar
file(s) that have the javax.servlet
implemenation. Ite depends on your servlet container or application server what file(s) you need to include, so search for that information.
relative position
, inside this parent you can set the absolute position
of your divs<div> <------Relative
<div/> <------Absolute
<div/> <------Absolute
<div/> <------Absolute
<div/>
Final result:
https://codepen.io/hiteshsahu/pen/XWKYEYb?editors=0100
<div class="container">
<div class="header">TOP: I am at Top & above of body container</div>
<div class="center">CENTER: I am at Top & in Center of body container</div>
<div class="footer">BOTTOM: I am at Bottom & above of body container</div>
</div>
Set HTML Body full width
html, body {
overflow: hidden;
width: 100%;
height: 100%;
margin: 0;
padding: 0;
}
After that, you can set a div with the relative position to take full width and height
.container {
position: relative;
background-color: blue;
height: 100%;
width: 100%;
border:1px solid;
color: white;
background-image: url("https://images.pexels.com/photos/5591663/pexels-photo-5591663.jpeg?auto=compress&cs=tinysrgb&dpr=2&h=750&w=1260");
background-color: #cccccc;
}
Inside this div with the relative position you can put your div with absolute positions
On TOP above the container
.header {
position: absolute;
margin-top: -10px;
background-color: #d81b60 ;
left:0;
right:0;
margin:15px;
padding:10px;
font-size: large;
}
On BOTTOM above the container
.footer {
position: absolute;
background-color: #00bfa5;
left:0;
right:0;
bottom:0;
margin:15px;
padding:10px;
color: white;
font-size: large;
}
In CENTER above the container
.center {
position: absolute;
background-color: #00bfa5;
left: 30%;
right: 30%;
bottom:30%;
top: 30%;
margin:10px;
padding:10px;
color: white;
font-size: large;
}
Not sure why you aren't able to set it. In the source, PUBLIC_URL
takes precedence over homepage
const envPublicUrl = process.env.PUBLIC_URL;
...
const getPublicUrl = appPackageJson =>
envPublicUrl || require(appPackageJson).homepage;
You can try setting breakpoints in their code to see what logic is overriding your environment variable.
Instead of writing the code from the scratch you can use jquery plug in. Such plug in can provide many configuration option as well.
Here is the one I most liked.
This code works:
$(".ui-button-text").live(
'hover',
function (ev) {
if (ev.type == 'mouseover') {
$(this).addClass("ui-state-hover");
}
if (ev.type == 'mouseout') {
$(this).removeClass("ui-state-hover");
}
});
DataColumnCollection col = datatable.Columns;
if (!columns.Contains("ColumnName1"))
{
//Column1 Not Exists
}
if (columns.Contains("ColumnName2"))
{
//Column2 Exists
}
var array = searchTerms.split(",");
for (var i in array){
alert(array[i]);
}
Well, in java, you can also create a parameterized enum. Say you want to create a className enum, in which you need to store classCode as well as className, you can do that like this:
public enum ClassEnum {
ONE(1, "One"),
TWO(2, "Two"),
THREE(3, "Three"),
FOUR(4, "Four"),
FIVE(5, "Five")
;
private int code;
private String name;
private ClassEnum(int code, String name) {
this.code = code;
this.name = name;
}
public int getCode() {
return code;
}
public String getName() {
return name;
}
}
I read the other questions on Stack but I was still a little confused on communicating across classes. Here is how I approached it:
I use a list to hold all my threads in the __init__
method of my wxFrame class: self.threads = []
As recommended in How to stop a looping thread in Python? I use a signal in my thread class which is set to True
when initializing the threading class.
class PingAssets(threading.Thread):
def __init__(self, threadNum, asset, window):
threading.Thread.__init__(self)
self.threadNum = threadNum
self.window = window
self.asset = asset
self.signal = True
def run(self):
while self.signal:
do_stuff()
sleep()
and I can stop these threads by iterating over my threads:
def OnStop(self, e):
for t in self.threads:
t.signal = False
My favorite answer is as what the first sentence in this thread suggested. Use an Adjacency List to maintain the hierarchy and use Nested Sets to query the hierarchy.
The problem up until now has been that the coversion method from an Adjacecy List to Nested Sets has been frightfully slow because most people use the extreme RBAR method known as a "Push Stack" to do the conversion and has been considered to be way to expensive to reach the Nirvana of the simplicity of maintenance by the Adjacency List and the awesome performance of Nested Sets. As a result, most people end up having to settle for one or the other especially if there are more than, say, a lousy 100,000 nodes or so. Using the push stack method can take a whole day to do the conversion on what MLM'ers would consider to be a small million node hierarchy.
I thought I'd give Celko a bit of competition by coming up with a method to convert an Adjacency List to Nested sets at speeds that just seem impossible. Here's the performance of the push stack method on my i5 laptop.
Duration for 1,000 Nodes = 00:00:00:870
Duration for 10,000 Nodes = 00:01:01:783 (70 times slower instead of just 10)
Duration for 100,000 Nodes = 00:49:59:730 (3,446 times slower instead of just 100)
Duration for 1,000,000 Nodes = 'Didn't even try this'
And here's the duration for the new method (with the push stack method in parenthesis).
Duration for 1,000 Nodes = 00:00:00:053 (compared to 00:00:00:870)
Duration for 10,000 Nodes = 00:00:00:323 (compared to 00:01:01:783)
Duration for 100,000 Nodes = 00:00:03:867 (compared to 00:49:59:730)
Duration for 1,000,000 Nodes = 00:00:54:283 (compared to something like 2 days!!!)
Yes, that's correct. 1 million nodes converted in less than a minute and 100,000 nodes in under 4 seconds.
You can read about the new method and get a copy of the code at the following URL. http://www.sqlservercentral.com/articles/Hierarchy/94040/
I also developed a "pre-aggregated" hierarchy using similar methods. MLM'ers and people making bills of materials will be particularly interested in this article. http://www.sqlservercentral.com/articles/T-SQL/94570/
If you do stop by to take a look at either article, jump into the "Join the discussion" link and let me know what you think.
If you are on linux you implement a non-blocking implementation in python in the following way.
import subprocess
subprocess.call('xterm -title log -hold -e \"tail -f filename\"&', shell=True, executable='/bin/csh')
print "Done"
Quick answer: change int testlib()
to int testlib(void)
to specify that the function takes no arguments.
A prototype is by definition a function declaration that specifies the type(s) of the function's argument(s).
A non-prototype function declaration like
int foo();
is an old-style declaration that does not specify the number or types of arguments. (Prior to the 1989 ANSI C standard, this was the only kind of function declaration available in the language.) You can call such a function with any arbitrary number of arguments, and the compiler isn't required to complain -- but if the call is inconsistent with the definition, your program has undefined behavior.
For a function that takes one or more arguments, you can specify the type of each argument in the declaration:
int bar(int x, double y);
Functions with no arguments are a special case. Logically, empty parentheses would have been a good way to specify that an argument but that syntax was already in use for old-style function declarations, so the ANSI C committee invented a new syntax using the void
keyword:
int foo(void); /* foo takes no arguments */
A function definition (which includes code for what the function actually does) also provides a declaration. In your case, you have something similar to:
int testlib()
{
/* code that implements testlib */
}
This provides a non-prototype declaration for testlib
. As a definition, this tells the compiler that testlib
has no parameters, but as a declaration, it only tells the compiler that testlib
takes some unspecified but fixed number and type(s) of arguments.
If you change ()
to (void)
the declaration becomes a prototype.
The advantage of a prototype is that if you accidentally call testlib
with one or more arguments, the compiler will diagnose the error.
(C++ has slightly different rules. C++ doesn't have old-style function declarations, and empty parentheses specifically mean that a function takes no arguments. C++ supports the (void)
syntax for consistency with C. But unless you specifically need your code to compile both as C and as C++, you should probably use the ()
in C++ and the (void)
syntax in C.)
Just in case for data.table
users, the following works for me:
df[, grep("ABC", names(df)), with = FALSE]
Just cast the entire sockaddr
structure to a sockaddr_in. Then you can use:
char *ip = inet_ntoa(their_addr.sin_addr)
To retrieve the standard ip representation.
you can do that on RowAdded Event :
_data_grid_view.RowsAdded += new System.Windows.Forms.DataGridViewRowsAddedEventHandler(this._data_grid_view_RowsAdded);
private void _data_grid_view_RowsAdded(object sender, DataGridViewRowsAddedEventArgs e)
{
_data_grid_view.Rows[e.RowIndex].Height = 42;
}
when a row add to the dataGridView it just change it height to 42.
Slightly different version I wrote that keeps track of the keys along the way to get there
def print_dict(v, prefix=''):
if isinstance(v, dict):
for k, v2 in v.items():
p2 = "{}['{}']".format(prefix, k)
print_dict(v2, p2)
elif isinstance(v, list):
for i, v2 in enumerate(v):
p2 = "{}[{}]".format(prefix, i)
print_dict(v2, p2)
else:
print('{} = {}'.format(prefix, repr(v)))
On your data, it'll print
data['xml']['config']['portstatus']['status'] = u'good'
data['xml']['config']['target'] = u'1'
data['xml']['port'] = u'11'
It's also easy to modify it to track the prefix as a tuple of keys rather than a string if you need it that way.
If it's not important to use a RelativeLayout, you could use a LinearLayout, and do this:
LinearLayout linearLayout = new LinearLayout(this);
linearLayout.setOrientation(LinearLayout.VERTICAL);
Doing this allows you to avoid the addRule method you've tried. You can simply use addView() to add new TextViews.
Complete code:
String[] textArray = {"One", "Two", "Three", "Four"};
LinearLayout linearLayout = new LinearLayout(this);
setContentView(linearLayout);
linearLayout.setOrientation(LinearLayout.VERTICAL);
for( int i = 0; i < textArray.length; i++ )
{
TextView textView = new TextView(this);
textView.setText(textArray[i]);
linearLayout.addView(textView);
}
Might wanna check this, got everything you need for your app icons
http://developer.android.com/guide/practices/ui_guidelines/icon_design.html
update
I think by default it uses your launcher icon... Your best bet is to create a separate image... Designed for the action bar and using that. For that check: http://developer.android.com/guide/topics/ui/actionbar.html#ActionItems
I had a similar issue and I had to check "Build Active Architecture Only" on each of the Project configurations (Debug, Release and Deployment) and in the Build Settings of the Target.
If there are two dates and you need the range try
from dateutil import rrule, parser
date1 = '1995-01-01'
date2 = '1995-02-28'
datesx = list(rrule.rrule(rrule.DAILY, dtstart=parser.parse(date1), until=parser.parse(date2)))
For checking complete changes:
git diff <commit_Id_1> <commit_Id_2>
For checking only the changed/added/deleted files:
git diff <commit_Id_1> <commit_Id_2> --name-only
NOTE: For checking diff without commit in between, you don't need to put the commit ids.
As Sahil Chhabra suggested you can use @JsonFormat
with proper shape
on your variable.
In case you would like to apply it on every BigDecimal
field you have in your Dto's
you can override default format for given class.
@Configuration
public class JacksonObjectMapperConfiguration {
@Autowired
public void customize(ObjectMapper objectMapper) {
objectMapper
.configOverride(BigDecimal.class).setFormat(JsonFormat.Value.forShape(JsonFormat.Shape.STRING));
}
}
iostream doesn't know it's at the end of the file until it tries to read that first character past the end of the file.
The sample code at cplusplus.com says to do it like this: (But you shouldn't actually do it this way)
while (is.good()) // loop while extraction from file is possible
{
c = is.get(); // get character from file
if (is.good())
cout << c;
}
A better idiom is to move the read into the loop condition, like so:
(You can do this with all istream
read operations that return *this
, including the >>
operator)
char c;
while(is.get(c))
cout << c;
You can put the values as the table's keys. For example:
function addToSet(set, key)
set[key] = true
end
function removeFromSet(set, key)
set[key] = nil
end
function setContains(set, key)
return set[key] ~= nil
end
There's a more fully-featured example here.
The output of FormatDateTime depends on configuration in Regional Settings in Control Panel. So in other countries FormatDateTime(d, 2) may for example return yyyy-MM-dd.
If you want your output to be "culture invariant", use myDateFormat() from stian.net's solution. If you just don't like slashes in dates and you don't care about date format in other countries, you can just use
Replace(FormatDateTime(d,2),"/","-")
Try this:
string baseUrl = Request.Url.Scheme + "://" + Request.Url.Authority +
Request.ApplicationPath.TrimEnd('/') + "/";
Copied from http://technet.microsoft.com/en-us/library/cc750354.aspx
What's FAT?
FAT may sound like a strange name for a file system, but it's actually an acronym for File Allocation Table. Introduced in 1981, FAT is ancient in computer terms. Because of its age, most operating systems, including Microsoft Windows NT®, Windows 98, the Macintosh OS, and some versions of UNIX, offer support for FAT.
The FAT file system limits filenames to the 8.3 naming convention, meaning that a filename can have no more than eight characters before the period and no more than three after. Filenames in a FAT file system must also begin with a letter or number, and they can't contain spaces. Filenames aren't case sensitive.
What About VFAT?
Perhaps you've also heard of a file system called VFAT. VFAT is an extension of the FAT file system and was introduced with Windows 95. VFAT maintains backward compatibility with FAT but relaxes the rules. For example, VFAT filenames can contain up to 255 characters, spaces, and multiple periods. Although VFAT preserves the case of filenames, it's not considered case sensitive.
When you create a long filename (longer than 8.3) with VFAT, the file system actually creates two different filenames. One is the actual long filename. This name is visible to Windows 95, Windows 98, and Windows NT (4.0 and later). The second filename is called an MS-DOS® alias. An MS-DOS alias is an abbreviated form of the long filename. The file system creates the MS-DOS alias by taking the first six characters of the long filename (not counting spaces), followed by the tilde [~] and a numeric trailer. For example, the filename Brien's Document.txt would have an alias of BRIEN'~1.txt.
An interesting side effect results from the way VFAT stores its long filenames. When you create a long filename with VFAT, it uses one directory entry for the MS-DOS alias and another entry for every 13 characters of the long filename. In theory, a single long filename could occupy up to 21 directory entries. The root directory has a limit of 512 files, but if you were to use the maximum length long filenames in the root directory, you could cut this limit to a mere 24 files. Therefore, you should use long filenames very sparingly in the root directory. Other directories aren't affected by this limit.
You may be wondering why we're discussing VFAT. The reason is it's becoming more common than FAT, but aside from the differences I mentioned above, VFAT has the same limitations. When you tell Windows NT to format a partition as FAT, it actually formats the partition as VFAT. The only time you'll have a true FAT partition under Windows NT 4.0 is when you use another operating system, such as MS-DOS, to format the partition.
FAT32
FAT32 is actually an extension of FAT and VFAT, first introduced with Windows 95 OEM Service Release 2 (OSR2). FAT32 greatly enhances the VFAT file system but it does have its drawbacks.
The greatest advantage to FAT32 is that it dramatically increases the amount of free hard disk space. To illustrate this point, consider that a FAT partition (also known as a FAT16 partition) allows only a certain number of clusters per partition. Therefore, as your partition size increases, the cluster size must also increase. For example, a 512-MB FAT partition has a cluster size of 8K, while a 2-GB partition has a cluster size of 32K.
This may not sound like a big deal until you consider that the FAT file system only works in single cluster increments. For example, on a 2-GB partition, a 1-byte file will occupy the entire cluster, thereby consuming 32K, or roughly 32,000 times the amount of space that the file should consume. This rule applies to every file on your hard disk, so you can see how much space can be wasted.
Converting a partition to FAT32 reduces the cluster size (and overcomes the 2-GB partition size limit). For partitions 8 GB and smaller, the cluster size is reduced to a mere 4K. As you can imagine, it's not uncommon to gain back hundreds of megabytes by converting a partition to FAT32, especially if the partition contains a lot of small files.
Note: This section of the quote/ article (1999) is out of date. Updated info quote below.
As I mentioned, FAT32 does have limitations. Unfortunately, it isn't compatible with any operating system other than Windows 98 and the OSR2 version of Windows 95. However, Windows 2000 will be able to read FAT32 partitions.
The other disadvantage is that your disk utilities and antivirus software must be FAT32-aware. Otherwise, they could interpret the new file structure as an error and try to correct it, thus destroying data in the process.
Finally, I should mention that converting to FAT32 is a one-way process. Once you've converted to FAT32, you can't convert the partition back to FAT16. Therefore, before converting to FAT32, you need to consider whether the computer will ever be used in a dual-boot environment. I should also point out that although other operating systems such as Windows NT can't directly read a FAT32 partition, they can read it across the network. Therefore, it's no problem to share information stored on a FAT32 partition with other computers on a network that run older operating systems.
Updated mentioned in comment by Doktor-J (assimilated to update out of date answer in case comment is ever lost):
I'd just like to point out that most modern operating systems (WinXP/Vista/7/8, MacOS X, most if not all Linux variants) can read FAT32, contrary to what the second-to-last paragraph suggests.
The original article was written in 1999, and being posted on a Microsoft website, probably wasn't concerned with non-Microsoft operating systems anyways.
The operating systems "excluded" by that paragraph are probably the original Windows 95, Windows NT 4.0, Windows 3.1, DOS, etc.
To check if a string variable contains a valid email address, the easiest way is to test it against a regular expression. There is a good discussion of various regex's and their trade-offs at regular-expressions.info.
Here is a relatively simple one that leans on the side of allowing some invalid addresses through: ^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,6}$
How you can use regular expressions depends on the version of iOS you are using.
You can use NSRegularExpression
, which allows you to compile and test against a regular expression directly.
Does not include the NSRegularExpression
class, but does include NSPredicate
, which can match against regular expressions.
NSString *emailRegex = ...;
NSPredicate *emailTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", emailRegex];
BOOL isValid = [emailTest evaluateWithObject:checkString];
Read a full article about this approach at cocoawithlove.com.
Does not include any regular expression matching in the Cocoa libraries. However, you can easily include RegexKit Lite in your project, which gives you access to the C-level regex APIs included on iOS 2.0.
When you develop an emulator you are interpreting the processor assembly that the system is working on (Z80, 8080, PS CPU, etc.).
You also need to emulate all peripherals that the system has (video output, controller).
You should start writing emulators for the simpe systems like the good old Game Boy (that use a Z80 processor, am I not not mistaking) OR for C64.
Alternative solution:
>>> from datetime import date
>>> (date(2012, 3, 1) - date(2012, 2, 1)).days
29
very simple
<img onload="loaded(this, 'success')" onerror="error(this,
'error')" src="someurl" alt="" />
function loaded(_this, status){
console.log(_this, status)
// do your work in load
}
function error(_this, status){
console.log(_this, status)
// do your work in error
}
A recursive method to check if a Class<?>
is a sub class of another Class<?>
...
Improved version of @To Kra's answer:
protected boolean isSubclassOf(Class<?> clazz, Class<?> superClass) {
if (superClass.equals(Object.class)) {
// Every class is an Object.
return true;
}
if (clazz.equals(superClass)) {
return true;
} else {
clazz = clazz.getSuperclass();
// every class is Object, but superClass is below Object
if (clazz.equals(Object.class)) {
// we've reached the top of the hierarchy, but superClass couldn't be found.
return false;
}
// try the next level up the hierarchy.
return isSubclassOf(clazz, superClass);
}
}
TEXT and CHAR will convert to/from the character set they have associated with time. BLOB and BINARY simply store bytes.
BLOB is used for storing binary data while Text is used to store large string.
BLOB values are treated as binary strings (byte strings). They have no character set, and sorting and comparison are based on the numeric values of the bytes in column values.
TEXT values are treated as nonbinary strings (character strings). They have a character set, and values are sorted and compared based on the collation of the character set.
In NHibernate (with NHibernate.Linq) you could do it as follows:
return session.Query<T>()
.Single(a => a.Filter == filter &&
a.Id == session.Query<T>()
.Where(a2 => a2.Filter == filter)
.Max(a2 => a2.Id));
Which will generate SQL like follows:
select *
from TableName foo
where foo.Filter = 'Filter On String'
and foo.Id = (select cast(max(bar.RowVersion) as INT)
from TableName bar
where bar.Name = 'Filter On String')
Which seems pretty efficient to me.
With Bash:
python script1.py &
python script2.py &
That's the entire script. It will run the two Python scripts at the same time.
Python could do the same thing itself but it would take a lot more typing and is a bad choice for the problem at hand.
I think it's possible though that you are taking the wrong approach to solving your problem, and I'd like to hear what you're getting at.
When using Windows, the comparison is cut short: memcache
appears to be the only client available.
Just add Quotation Mark
Example:"C:\Users\User Name"
Hope it got Solved!
I show you my example with modal windows...you create your modal and give it an id then In your table you have tr section, just ad the first line you see below (don't forget to set the on the first row like this
<tr onclick="input" data-toggle="modal" href="#the name for my modal windows" >
<td><label>Some value here</label></td>
</tr>
display: inline-block;
max-width: 80%;
height: 1.5em;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
You can use merge to combine two dataframes into one:
import pandas as pd
pd.merge(restaurant_ids_dataframe, restaurant_review_frame, on='business_id', how='outer')
where on specifies field name that exists in both dataframes to join on, and how
defines whether its inner/outer/left/right join, with outer using 'union of keys from both frames (SQL: full outer join).' Since you have 'star' column in both dataframes, this by default will create two columns star_x and star_y in the combined dataframe. As @DanAllan mentioned for the join method, you can modify the suffixes for merge by passing it as a kwarg. Default is suffixes=('_x', '_y')
. if you wanted to do something like star_restaurant_id
and star_restaurant_review
, you can do:
pd.merge(restaurant_ids_dataframe, restaurant_review_frame, on='business_id', how='outer', suffixes=('_restaurant_id', '_restaurant_review'))
The parameters are explained in detail in this link.
This will return specifically what you are asking.
Dim mySiteUrl = Request.Url.Host.ToString()
I know this is an older question. But I needed the same simple answer and this returns exactly what is asked (without the http://).
As he didn't specify which version of SQL server he uses (date
type isn't available in 2005), one could also use
SELECT CONVERT(VARCHAR(10),date_column,112),SUM(num_col) AS summed
FROM table_name
GROUP BY CONVERT(VARCHAR(10),date_column,112)
There are no vertical lines in html that you can use but you can fake one by absolutely positioning a div outside of your container with a top:0;
and bottom:0;
style.
Try this:
CSS
.vr {
width:10px;
background-color:#000;
position:absolute;
top:0;
bottom:0;
left:150px;
}
HTML
<div class="vr"> </div>
Reinstall node, then update npm.
First I removed node
apt-get purge node
Then install node according to the distibution. Docs here .
Then
npm install npm@latest -g
Typically you would accomplish this using an ajax request that looks like
var xhr = new XMLHttpRequest();
xhr.open("GET", "pythoncode.py?text=" + text, true);
xhr.responseType = "JSON";
xhr.onload = function(e) {
var arrOfStrings = JSON.parse(xhr.response);
}
xhr.send();
I have been there, like so many of us. There are so many confusing words like Web API, REST, RESTful, HTTP, SOAP, WCF, Web Services... and many more around this topic. But I am going to give brief explanation of only those which you have asked.
It is neither an API nor a framework. It is just an architectural concept. You can find more details here.
I have not come across any formal definition of RESTful anywhere. I believe it is just another buzzword for APIs to say if they comply with REST specifications.
EDIT: There is another trending open source initiative OpenAPI Specification (OAS) (formerly known as Swagger) to standardise REST APIs.
It in an open source framework for writing HTTP APIs. These APIs can be RESTful or not. Most HTTP APIs we write are not RESTful. This framework implements HTTP protocol specification and hence you hear terms like URIs, request/response headers, caching, versioning, various content types(formats).
Note: I have not used the term Web Services deliberately because it is a confusing term to use. Some people use this as a generic concept, I preferred to call them HTTP APIs. There is an actual framework named 'Web Services' by Microsoft like Web API. However it implements another protocol called SOAP.
What you are trying to do can be simplified down to this.
$('input:text').bind('focus blur', function() {_x000D_
$(this).toggleClass('red');_x000D_
});
_x000D_
input{_x000D_
background:#FFFFEE;_x000D_
}_x000D_
.red{_x000D_
background-color:red;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>_x000D_
_x000D_
<form>_x000D_
<input class="calc_input" type="text" name="start_date" id="start_date" />_x000D_
<input class="calc_input" type="text" name="end_date" id="end_date" />_x000D_
<input class="calc_input" size="8" type="text" name="leap_year" id="leap_year" />_x000D_
</form>
_x000D_
I got the same issue, and able to find it in github https://github.com/angular/angular-cli/issues/1901, which state that it was an issue with [email protected]
.
Downgrade typescript to 2.0.0
both globally and locally helped me to resolve it.
Globally:
npm uninstall typescript -g
npm cache clean
npm install [email protected] -g
Locally: GO into the project folder you created by ng new
npm uninstall typescript
npm cache clean
npm install [email protected]
I also changed the version of typescript within package.json from ^2.0.0
to 2.0.0
, but it didn't work until I downgrade the local typescript installation.
HTTPS proxy doesn't make sense because you can't terminate your HTTP connection at the proxy for security reasons. With your trust policy, it might work if the proxy server has a HTTPS port. Your error is caused by connecting to HTTP proxy port with HTTPS.
You can connect through a proxy using SSL tunneling (many people call that proxy) using proxy CONNECT command. However, Java doesn't support newer version of proxy tunneling. In that case, you need to handle the tunneling yourself. You can find sample code here,
http://www.javaworld.com/javaworld/javatips/jw-javatip111.html
EDIT: If you want defeat all the security measures in JSSE, you still need your own TrustManager. Something like this,
public SSLTunnelSocketFactory(String proxyhost, String proxyport){
tunnelHost = proxyhost;
tunnelPort = Integer.parseInt(proxyport);
dfactory = (SSLSocketFactory)sslContext.getSocketFactory();
}
...
connection.setSSLSocketFactory( new SSLTunnelSocketFactory( proxyHost, proxyPort ) );
connection.setDefaultHostnameVerifier( new HostnameVerifier()
{
public boolean verify( String arg0, SSLSession arg1 )
{
return true;
}
} );
EDIT 2: I just tried my program I wrote a few years ago using SSLTunnelSocketFactory and it doesn't work either. Apparently, Sun introduced a new bug sometime in Java 5. See this bug report,
http://bugs.sun.com/view_bug.do?bug_id=6614957
The good news is that the SSL tunneling bug is fixed so you can just use the default factory. I just tried with a proxy and everything works as expected. See my code,
public class SSLContextTest {
public static void main(String[] args) {
System.setProperty("https.proxyHost", "proxy.xxx.com");
System.setProperty("https.proxyPort", "8888");
try {
SSLContext sslContext = SSLContext.getInstance("SSL");
// set up a TrustManager that trusts everything
sslContext.init(null, new TrustManager[] { new X509TrustManager() {
public X509Certificate[] getAcceptedIssuers() {
System.out.println("getAcceptedIssuers =============");
return null;
}
public void checkClientTrusted(X509Certificate[] certs,
String authType) {
System.out.println("checkClientTrusted =============");
}
public void checkServerTrusted(X509Certificate[] certs,
String authType) {
System.out.println("checkServerTrusted =============");
}
} }, new SecureRandom());
HttpsURLConnection.setDefaultSSLSocketFactory(
sslContext.getSocketFactory());
HttpsURLConnection
.setDefaultHostnameVerifier(new HostnameVerifier() {
public boolean verify(String arg0, SSLSession arg1) {
System.out.println("hostnameVerifier =============");
return true;
}
});
URL url = new URL("https://www.verisign.net");
URLConnection conn = url.openConnection();
BufferedReader reader =
new BufferedReader(new InputStreamReader(conn.getInputStream()));
String line;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
This is what I get when I run the program,
checkServerTrusted =============
hostnameVerifier =============
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
......
As you can see, both SSLContext and hostnameVerifier are getting called. HostnameVerifier is only involved when the hostname doesn't match the cert. I used "www.verisign.net" to trigger this.
The following code will not raise an exception and will exit without a traceback:
import os
os._exit(1)
See this question and related answers for more details. Surprised why all other answers are so overcomplicated.
The error means it's the wrong JVM version for that version of Eclipse. The link has more details:
http://www.ehow.com/how_4784069_terminated-exit-code-error-eclipse.html
if (mysql_num_rows($result)==0) { PERFORM ACTION }
For PHP 5 and 7 and above use mysqli:
if (mysqli_num_rows($result)==0) { PERFORM ACTION }
This gets my vote.
OP assuming query is not returning any error, so this should be one of the way
Follow these steps
npm install --save cors
var cors = require('cors');
app.use(cors());
This is, imo, the most elegant way to do it (with ES6). Instantiate you empty array with 7 indexes and map in one line:
Array.apply(null, Array(7)).map((i)=>
<Somecomponent/>
)
kudos to https://php.quicoto.com/create-loop-inside-react-jsx/
You can find some examples of this here, here (code is taken here), and here.
You can create a POJO class for this, but you need to add some extra code to make it Parcelable
. Have a look at the implementation.
public class Student implements Parcelable{
private String id;
private String name;
private String grade;
// Constructor
public Student(String id, String name, String grade){
this.id = id;
this.name = name;
this.grade = grade;
}
// Getter and setter methods
.........
.........
// Parcelling part
public Student(Parcel in){
String[] data = new String[3];
in.readStringArray(data);
// the order needs to be the same as in writeToParcel() method
this.id = data[0];
this.name = data[1];
this.grade = data[2];
}
@?verride
public int describeContents(){
return 0;
}
@Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeStringArray(new String[] {this.id,
this.name,
this.grade});
}
public static final Parcelable.Creator CREATOR = new Parcelable.Creator() {
public Student createFromParcel(Parcel in) {
return new Student(in);
}
public Student[] newArray(int size) {
return new Student[size];
}
};
}
Once you have created this class, you can easily pass objects of this class through the Intent
like this, and recover this object in the target activity.
intent.putExtra("student", new Student("1","Mike","6"));
Here, the student is the key which you would require to unparcel the data from the bundle.
Bundle data = getIntent().getExtras();
Student student = (Student) data.getParcelable("student");
This example shows only String
types. But, you can parcel any kind of data you want. Try it out.
EDIT: Another example, suggested by Rukmal Dias.
Not answering your question specifically, but isn't that something that should be handled by the presentation layer of your application. Doing it the way you describe creates extra processing on the database end as well as adding extra network traffic (assuming the database exists on a different machine than the application), for something that could be easily computed on the application side, with more rich date processing libraries, as well as being more language agnostic, especially in the case of your first example which contains the abbreviated month name. Anyway the answers others give you should point you in the right direction if you still decide to go this route.
If the case of the user not being found comes up often enough, and you want to deal with that in various ways depending on circumstance (sometimes throwing an exception, sometimes substituting an empty user) you could also use something close to F#'s Option
or Haskell's Maybe
type, which explicitly seperates the 'no value' case from 'found something!'. The database access code could look like this:
public Option<UserEntity> GetUserById(Guid userId)
{
//Imagine some code here to access database.....
//Check if data was returned and return a null if none found
if (!DataExists)
return Option<UserEntity>.Nothing;
else
return Option.Just(existingUserEntity);
}
And be used like this:
Option<UserEntity> result = GetUserById(...);
if (result.IsNothing()) {
// deal with it
} else {
UserEntity value = result.GetValue();
}
Unfortunately, everybody seems to roll a type like this of their own.
You can use:
Start-Process -FilePath "C:\Program Files\IIS\Microsoft Web Deploy\msdeploy.exe" -ArgumentList "-verb:sync -source:dbfullsql="Data Source=mysource;Integrated Security=false;User ID=sa;Pwd=sapass!;Database=mydb;" -dest:dbfullsql="Data Source=.\mydestsource;Integrated Security=false;User ID=sa;Pwd=sapass!;Database=mydb;",computername=10.10.10.10,username=administrator,password=adminpass"
The key thing to note here is that FilePath must be in position 0, according to the Help Guide. To invoke the Help guide for a commandlet, just type in Get-Help <Commandlet-name> -Detailed
. In this case, it is Get-Help Start-Process -Detailed
.
There are other mechanisms to handle overflow than the simple minded linked list of overflow entries which e.g. wastes a lot of memory.
Which mechanism to use depends among other things on if you can choose the hash function and possible pick more than one (to implement e.g. double hashing to handle collisions); if you expect to often add items or if the map is static once filled; if you intend to remove items or not; ...
The best way to implement this is to first think about all these parameters and then not code it yourself but to pick a mature existing implementation. Google has a few good implementations -- e.g. http://code.google.com/p/google-sparsehash/
This is available on linux: pidof keyword
right click on console.. click save as.. its this simple.. you'll get an output text file
Simply in one line:
java.sql.Date date = new java.sql.Date(Calendar.getInstance().getTime().getTime());
If you will invoke the script with source
, you can use return <x>
where <x>
will be the script exit status (use a non-zero value for error or false). But if you invoke an executable script (i.e., directly with its filename), the return statement will result in a complain (error message "return: can only `return' from a function or sourced script").
If exit <x>
is used instead, when the script is invoked with source
, it will result in exiting the shell that started the script, but an executable script will just terminate, as expected.
To handle either case in the same script, you can use
return <x> 2> /dev/null || exit <x>
This will handle whichever invocation may be suitable. That is assuming you will use this statement at the script's top level. I would advise against directly exiting the script from within a function.
Note: <x>
is supposed to be just a number.