You have placed your service outside the application tag. Change bottom to this.
<service
android:name=".NotificationGenie">
<intent-filter>
<action android:name="com.google.firebase.MESSAGING_EVENT"/>
</intent-filter>
</service>
</application>
Unfortunately this was a limitation of Firebase Notifications in SDK 9.0.0-9.6.1. When the app is in the background the launcher icon is use from the manifest (with the requisite Android tinting) for messages sent from the console.
With SDK 9.8.0 however, you can override the default! In your AndroidManifest.xml you can set the following fields to customise the icon and color:
<meta-data
android:name="com.google.firebase.messaging.default_notification_icon"
android:resource="@drawable/notification_icon" />
<meta-data android:name="com.google.firebase.messaging.default_notification_color"
android:resource="@color/google_blue" />
Note that if the app is in the foreground (or a data message is sent) you can completely use your own logic to customise the display. You can also always customise the icon if sending the message from the HTTP/XMPP APIs.
Trying to handle the URI with content:// scheme by calling ContentResolver.query()
is not a good solution. On HTC Desire running 4.2.2 you could get NULL as a query result.
Why not to use ContentResolver instead? https://stackoverflow.com/a/29141800/3205334
Instead of AudioManager.STREAM_RING
you shoul use AudioManager.STREAM_MUSIC
This question has already discussed here.
Intent intent = new Intent(this, MembersLocation.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
intent.putExtra("type",type);
intent.putExtra("sender",sender);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0 /* Request code */, intent,
PendingIntent.FLAG_ONE_SHOT);
String channelId = getString(R.string.default_notification_channel_id);
Uri Emergency_sound_uri=Uri.parse("android.resource://"+getPackageName()+"/raw/emergency_sound");
// Uri Default_Sound_uri= RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
if(type.equals("emergency"))
{
playSound=Emergency_sound_uri;
}
else
{
playSound= Settings.System.DEFAULT_NOTIFICATION_URI;
}
NotificationCompat.Builder notificationBuilder =
new NotificationCompat.Builder(this, channelId)
.setSmallIcon(R.drawable.ic_notification)
.setContentTitle(title)
.setContentText(body)
.setSound(playSound, AudioManager.STREAM_NOTIFICATION)
.setAutoCancel(true)
.setColor(getColor(R.color.dark_red))
.setPriority(NotificationCompat.PRIORITY_HIGH)
.setContentIntent(pendingIntent);
// notificationBuilder.setOngoing(true);//for Android notification swipe delete disabling...
NotificationManager notificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
// Since android Oreo notification channel is needed.
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationChannel channel = new NotificationChannel(channelId,
"Channel human readable title",
NotificationManager.IMPORTANCE_HIGH);
AudioAttributes att = new AudioAttributes.Builder()
.setUsage(AudioAttributes.USAGE_NOTIFICATION)
.setContentType(AudioAttributes.CONTENT_TYPE_SPEECH)
.build();
channel.setSound(Emergency_sound_uri, att);
if (notificationManager != null) {
notificationManager.createNotificationChannel(channel);
}
}
if (notificationManager != null) {
notificationManager.notify(0 /* ID of notification */, notificationBuilder.build());
}
}
This is the way I've done:
Uri notification = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
MediaPlayer mp = MediaPlayer.create(getApplicationContext(), notification);
mp.start();
It is similar to markov00's way, but uses MediaPlayer instead of Ringtone which prevents interrupting other sounds, like music, that might already be playing in the background.
The steps described above do work, however I've encountered this problem on IntelliJ IDEA and have found that I'm having these problems with existing projects and the only solution is to remove the 'appcompat' module (not the library) and re-import it.
Here is my preferred quickest and easiest solution. Works well if all slides have the same background color that you want to remove.
Step 1. In Powerpoint, "Save As" (shortcut F12) PNG, "All Slides".
Now you have a folder full of these PNG images of all your slides. The problem is that they still have a background. So now:
Step 2. Batch remove background color of all the PNG images, for example by following the steps in this SE answer.
If you need to remove multiple elements from array without converting it to List
nor creating additional array, you may do it in O(n) not dependent on count of items to remove.
Here, a
is initial array, int... r
are distinct ordered indices (positions) of elements to remove:
public int removeItems(Object[] a, int... r) {
int shift = 0;
for (int i = 0; i < a.length; i++) {
if (shift < r.length && i == r[shift]) // i-th item needs to be removed
shift++; // increment `shift`
else
a[i - shift] = a[i]; // move i-th item `shift` positions left
}
for (int i = a.length - shift; i < a.length; i++)
a[i] = null; // replace remaining items by nulls
return a.length - shift; // return new "length"
}
Small testing:
String[] a = {"0", "1", "2", "3", "4"};
removeItems(a, 0, 3, 4); // remove 0-th, 3-rd and 4-th items
System.out.println(Arrays.asList(a)); // [1, 2, null, null, null]
In your task, you can first scan array to collect positions of "a", then call removeItems()
.
Editor's note: disabling SSL verification has security implications. Without verification of the authenticity of SSL/HTTPS connections, a malicious attacker can impersonate a trusted endpoint such as Gmail, and you'll be vulnerable to a Man-in-the-Middle Attack.
Be sure you fully understand the security issues before using this as a solution.
Easy fix for this might be editing config/mail.php and turning off TLS
'encryption' => env('MAIL_ENCRYPTION', ''), //'tls'),
Basically by doing this
$options['ssl']['verify_peer'] = FALSE;
$options['ssl']['verify_peer_name'] = FALSE;
You should loose security also, but in first option there is no need to dive into Vendor's code.
Use the tail.exe from the Windows 2003 Resource Kit
Get-ADGroupMember "Group1" -recursive | Select-Object Name | Export-Csv c:\path\Groups.csv
I got this to work for me... I would assume that you could put "Group1, Group2, etc." or try a wildcard. I did pre-load AD into PowerShell before hand:
Get-Module -ListAvailable | Import-Module
This is your primary problem:
The source date could be anything like dd-mm-yyyy, dd/mm/yyyy, mm-dd-yyyy, mm/dd/yyyy or even yyyy-MM-dd.
If you're given 01/02/2013
, is it Jan 2 or Feb 1? You should solve this problem first and parsing the input will be much easier.
I suggest you take a step back and explore what you are trying to solve in more detail.
try this :
<asp:Button runat="server" ID="btnUserDelete" Text="Delete" CssClass="GreenLightButton"
onClientClick=" return confirm('Are you sure you want to delete this user?')"
OnClick="BtnUserDelete_Click" meta:resourcekey="BtnUserDeleteResource1" />
Yes, %d is for decimal (integer), double expect %f. But simply using %f will default to up to precision 6. To print all of the precision digits for a double, you can pass it via string as:
System.out.printf("%s \r\n",String.valueOf(d));
or
System.out.printf("%s \r\n",Double.toString(d));
This is what println do by default:
System.out.println(d)
(and terminates the line)
Usually (same as I do in mysql/postgres) I stores dates in int(mysql/post) or text(sqlite) to store them in the timestamp format.
Then I will convert them into Date objects and perform actions based on user TimeZone
The issue here is that ng-repeat
creates its own scope, so when you do selected=$index
it creates a new a selected
property in that scope rather than altering the existing one. To fix this you have two options:
Change the selected property to a non-primitive (ie object or array, which makes javascript look up the prototype chain) then set a value on that:
$scope.selected = {value: 0};
<a ng-click="selected.value = $index">A{{$index}}</a>
or
Use the $parent
variable to access the correct property. Though less recommended as it increases coupling between scopes
<a ng-click="$parent.selected = $index">A{{$index}}</a>
I've been using this line to launch the default browser:
System.Diagnostics.Process.Start("http://www.google.com");
For me, the issue was that I had a broken symbolic link on the file I was trying to mount into the container
Sounds very much like MySQL events that are stored in system tables. You can look at the structure and figure out which columns are not needed:
EVENT_CATALOG: NULL
EVENT_SCHEMA: myschema
EVENT_NAME: e_store_ts
DEFINER: jon@ghidora
EVENT_BODY: SQL
EVENT_DEFINITION: INSERT INTO myschema.mytable VALUES (UNIX_TIMESTAMP())
EVENT_TYPE: RECURRING
EXECUTE_AT: NULL
INTERVAL_VALUE: 5
INTERVAL_FIELD: SECOND
SQL_MODE: NULL
STARTS: 0000-00-00 00:00:00
ENDS: 0000-00-00 00:00:00
STATUS: ENABLED
ON_COMPLETION: NOT PRESERVE
CREATED: 2006-02-09 22:36:06
LAST_ALTERED: 2006-02-09 22:36:06
LAST_EXECUTED: NULL
EVENT_COMMENT:
A bit late in the game but just in case it helps anyone.
If you are testing using the Sandbox and on the payment page you want to test payments NOT using a PayPal account but using the "Pay with Debit or Credit Card option" (i.e. when a regular Joe/Jane, NOT PayPal users, want to buy your stuff) and want to save yourself some time: just go to a site like http://www.getcreditcardnumbers.com/ and get numbers from there. You can use any Expiry date (in the future) and any numeric CCV (123 works).
The "test credit card numbers" in the PayPal documentation are just another brick in their infuriating wall of convoluted stuff.
I got the url above from PayPal's tech support.
Tested using a simple Hosted button and IPN. Good luck.
I encountered the same problem.
What caused it for me were a bunch of whitespaces (
) that I inserted.
After removing them, the problem was solved.
newaxis
object in the selection tuple serves to expand the dimensions of the resulting selection by one unit-length dimension.
It is not just conversion of row matrix to column matrix.
Consider the example below:
In [1]:x1 = np.arange(1,10).reshape(3,3)
print(x1)
Out[1]: array([[1, 2, 3],
[4, 5, 6],
[7, 8, 9]])
Now lets add new dimension to our data,
In [2]:x1_new = x1[:,np.newaxis]
print(x1_new)
Out[2]:array([[[1, 2, 3]],
[[4, 5, 6]],
[[7, 8, 9]]])
You can see that newaxis
added the extra dimension here, x1 had dimension (3,3) and X1_new has dimension (3,1,3).
How our new dimension enables us to different operations:
In [3]:x2 = np.arange(11,20).reshape(3,3)
print(x2)
Out[3]:array([[11, 12, 13],
[14, 15, 16],
[17, 18, 19]])
Adding x1_new and x2, we get:
In [4]:x1_new+x2
Out[4]:array([[[12, 14, 16],
[15, 17, 19],
[18, 20, 22]],
[[15, 17, 19],
[18, 20, 22],
[21, 23, 25]],
[[18, 20, 22],
[21, 23, 25],
[24, 26, 28]]])
Thus, newaxis
is not just conversion of row to column matrix. It increases the dimension of matrix, thus enabling us to do more operations on it.
This is how I solved this problem.
I first ran npm install @angular/core
.
Then I ran npm install --save
.
When both installs had successfully completed I ran npm serve
and received an error saying
"Versions of @angular/compiler-cli and typescript could not be determined.
The most common reason for this is a broken npm install.
Please make sure your package.json contains both @angular/compiler-cli and typescript in
devDependencies, then delete node_modules and package-lock.json (if you have one) and
run npm install again."
I then deleted my node_modules folder as well as my package-lock.json folder.
After I deleted those folders I ran npm install --save
once more.
I ran npm start
and received another error. This error said Error: Cannot find module '@angular-devkit/core'
.
I ran npm install @angular-devkit/core --save
.
Finally, I ran npm start
and the project started!
Try this:
String yourVal = "20.5";
float a = (Float.valueOf(yourVal)).floatValue();
System.out.println(a);
I've same issue. I test this code and works well. This code Get Image from URL and put in - "bmpImage"
URL url = new URL("http://your URL");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(60000 /* milliseconds */);
conn.setConnectTimeout(65000 /* milliseconds */);
conn.setRequestMethod("GET");
conn.setDoInput(true);
conn.connect();
int response = conn.getResponseCode();
//Log.d(TAG, "The response is: " + response);
is = conn.getInputStream();
BufferedInputStream bufferedInputStream = new BufferedInputStream(is);
Bitmap bmpImage = BitmapFactory.decodeStream(bufferedInputStream);
To those that uses XAMPP 1.7.3 and Mac
which php
/usr/bin/php
, then proceed to 3.sudo nano ~/.bash_profile
(or sudo vim ~/.bash_profile
if you know how to use it)export PATH="/Applications/XAMPP/xamppfiles/bin:$PATH"
cd ~
. .bash_profile
which php
. If you did it right, it should be the same as the path in #4.The reason for the mcrypt error is because your Mac uses its native php, you need to change it to the one xampp has.
P.S. I'd recommend using MAMP for Laravel 4 for Mac users, this issue will get resolved along with the php file info error without a sweat, and the php version of xampp is so outdated.
Like ?egDwight said, you can use the HTML entity &infin
; or ∞
. A easy source of getting these codes, is to look at this entity list.
You can also use them in CSS, which was what I was looking for, just like font-awesome does. A simple CSS based solution would be to have something like:
.infinity-ico:before {
content: '\221E';
}
In addition to RMT's answer. I also had to modify the code a bit.
here is my sample send() methods. The config object is just a dumb data container.
public boolean send(String to, String from, String subject, String text) {
return send(new String[] {to}, from, subject, text);
}
public boolean send(String[] to, String from, String subject, String text) {
Properties props = new Properties();
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.host", config.host);
props.put("mail.smtp.user", config.username);
props.put("mail.smtp.port", config.port);
props.put("mail.smtp.password", config.password);
Session session = Session.getInstance(props, new SmtpAuthenticator(config));
try {
Message message = new MimeMessage(session);
message.setFrom(new InternetAddress(from));
InternetAddress[] addressTo = new InternetAddress[to.length];
for (int i = 0; i < to.length; i++) {
addressTo[i] = new InternetAddress(to[i]);
}
message.setRecipients(Message.RecipientType.TO, addressTo);
message.setSubject(subject);
message.setText(text);
Transport.send(message);
} catch (MessagingException e) {
e.printStackTrace();
return false;
}
return true;
}
In java to prevent multiple threads manipulating a shared variable we use synchronized
keyword. Lets understand it with help of the following example:
In the example I have defined two threads and named them increment and decrement. Increment thread increases the value of shared variable (counter
) by the same amount the decrement thread decreases it i.e 5000 times it is increased (which result in 5000 + 0 = 5000) and 5000 times we decrease (which result in 5000 - 5000 = 0).
Program without synchronized
keyword:
class SynchronizationDemo {
public static void main(String[] args){
Buffer buffer = new Buffer();
MyThread incThread = new MyThread(buffer, "increment");
MyThread decThread = new MyThread(buffer, "decrement");
incThread.start();
decThread.start();
try {
incThread.join();
decThread.join();
}catch(InterruptedException e){ }
System.out.println("Final counter: "+buffer.getCounter());
}
}
class Buffer {
private int counter = 0;
public void inc() { counter++; }
public void dec() { counter--; }
public int getCounter() { return counter; }
}
class MyThread extends Thread {
private String name;
private Buffer buffer;
public MyThread (Buffer aBuffer, String aName) {
buffer = aBuffer;
name = aName;
}
public void run(){
for (int i = 0; i <= 5000; i++){
if (name.equals("increment"))
buffer.inc();
else
buffer.dec();
}
}
}
If we run the above program we expect value of buffer to be same since incrementing and decrementing the buffer by same amount would result in initial value we started with right ?. Lets see the output:
As you can see no matter how many times we run the program we get a different result reason being each thread manipulated the counter
at the same time. If we could manage to let the one thread to first increment the shared variable and then second to decrement it or vice versa we will then get the right result that is exactly what can be done with synchronized
keyword by just adding synchronized
keyword before the inc
and dec
methods of Buffer
like this:
Program with synchronized
keyword:
// rest of the code
class Buffer {
private int counter = 0;
// added synchronized keyword to let only one thread
// be it inc or dec thread to manipulate data at a time
public synchronized void inc() { counter++; }
public synchronized void dec() { counter--; }
public int getCounter() { return counter; }
}
// rest of the code
and the output:
no matter how many times we run it we get the same output as 0
I had a similar problem after updating my VS2017. Project built fine; but lots of 'errors' when code was brought up in the editor. Even tried reinstalling VS. I was able to solve it by setting the option “Ignore Standard Include Paths” to Yes. Attempted to build the solution with lots of errors. Went back and set the option to No. After rebuilding, my problem went away.
Please use SQL Server Data Tools from SQL Server Integration Services (Transfer Database Task) as here: https://stackoverflow.com/a/27777823/2127493
http://www.amk.ca/python/writing/DB-API.html
Be careful when you simply append values of variables to your statements:
Imagine a user naming himself ';DROP TABLE Users;'
--
That's why you need to use sql escaping, which Python provides for you when you use the cursor.execute in a decent manner. Example in the url is:
cursor.execute("insert into Attendees values (?, ?, ?)", (name,
seminar, paid) )
Ok so I was having this issue where I tried several different options.
The font i'm using is Ubuntu-LI , I created a font folder in my working directory. under the folder fonts
I was able to apply it... eventually here is my working code
I wanted this to apply to my entire website so I put it at the top of the css doc. above all of the Div tags (not that it matters, just know that any individual fonts you assign post your script will take precedence)
@font-face{
font-family: "Ubuntu-LI";
src: url("/fonts/Ubuntu/(Ubuntu-LI.ttf"),
url("../fonts/Ubuntu/Ubuntu-LI.ttf");
}
*{
font-family:"Ubuntu-LI";
}
If i then wanted all of my H1 tags to be something else lets say sans sarif I would do something like
h1{
font-family: Sans-sarif;
}
From which case only my H1 tags would be the sans-sarif font and the rest of my page would be the Ubuntu-LI font
jsondata = '{"0001":{"FirstName":"John","LastName":"Mark","MiddleName":"Lewis","username":"johnlewis2","password":"2910"}}'
import json
import pandas as pd
jdata = json.loads(jsondata)
df = pd.DataFrame(jdata)
print df.T
This should look like this:.
FirstName LastName MiddleName password username 0001 John Mark Lewis 2910 johnlewis2
You can't return ajax return value. You stored global variable store your return values after return.
Or Change ur code like this one.
AjaxGet = function (url) {
var result = $.ajax({
type: "POST",
url: url,
param: '{}',
contentType: "application/json; charset=utf-8",
dataType: "json",
async: false,
success: function (data) {
// nothing needed here
}
}) .responseText ;
return result;
}
Using jQuery:
$(".delete-link").on("click", null, function(){
return confirm("Are you sure?");
});
Yes, you can set the screen orientation programatically anytime you want using:
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
for landscape and portrait mode respectively. The setRequestedOrientation() method is available for the Activity class, so it can be used inside your Activity.
And this is how you can get the current screen orientation and set it adequatly depending on its current state:
Display display = ((WindowManager) getSystemService(WINDOW_SERVICE)).getDefaultDisplay();
final int orientation = display.getOrientation();
// OR: orientation = getRequestedOrientation(); // inside an Activity
// set the screen orientation on button click
Button btn = (Button) findViewById(R.id.yourbutton);
btn.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
switch(orientation) {
case Configuration.ORIENTATION_PORTRAIT:
setRequestedOrientation (ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
break;
case Configuration.ORIENTATION_LANDSCAPE:
setRequestedOrientation (ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
break;
}
}
});
Taken from here: http://techblogon.com/android-screen-orientation-change-rotation-example/
EDIT
Also, you can get the screen orientation using the Configuration
:
Activity.getResources().getConfiguration().orientation
In my case, the problem was styling header as "Header 1" but that style was not exist in the Word that I get the error because it was not an Office in English Language.
Here is a query, you can run it in SQL Developer (or SQL*Plus):
SELECT DS.TABLESPACE_NAME, SEGMENT_NAME, ROUND(SUM(DS.BYTES) / (1024 * 1024)) AS MB
FROM DBA_SEGMENTS DS
WHERE SEGMENT_NAME IN (SELECT TABLE_NAME FROM DBA_TABLES)
GROUP BY DS.TABLESPACE_NAME,
SEGMENT_NAME;
html {
background: url(images/bg.jpg) no-repeat center center fixed;
-webkit-background-size: cover;
-moz-background-size: cover;
-o-background-size: cover;
background-size: cover;
min-height: 100%;
}
html body {
min-height: 100%
}
Works for all major browsers: FF, Chrome, Opera, IE9+. Works with Background images and gradients. Scrollbars are available as content needs.
If you want to apply some condition on form submit then you can use this method
<form onsubmit="return checkEmpData();" method="post" action="process.html">
<input type="text" border="0" name="submit" />
<button value="submit">submit</button>
</form>
One thing always keep in mind that method and action attribute write after onsubmit attributes
javascript code
function checkEmpData()
{
var a = 0;
if(a != 0)
{
return confirm("Do you want to generate attendance?");
}
else
{
alert('Please Select Employee First');
return false;
}
}
First, you need to create your branch locally
git checkout -b your_branch
After that, you can work locally in your branch, when you are ready to share the branch, push it. The next command push the branch to the remote repository origin and tracks it
git push -u origin your_branch
Your Teammates/colleagues can push to your branch by doing commits and then push explicitly
... work ...
git commit
... work ...
git commit
git push origin HEAD:refs/heads/your_branch
USE [<dbname>]
GO
sp_changedbowner '<user>' -- you can use 'sa' as a quick fix in databases with SQL authentication
You can use:
return (dateTocheck >= startDate && dateToCheck <= endDate);
I rewrote David's answer using the with
statement, it allows you do do this:
with timeout(seconds=3):
time.sleep(4)
Which will raise a TimeoutError.
The code is still using signal
and thus UNIX only:
import signal
class timeout:
def __init__(self, seconds=1, error_message='Timeout'):
self.seconds = seconds
self.error_message = error_message
def handle_timeout(self, signum, frame):
raise TimeoutError(self.error_message)
def __enter__(self):
signal.signal(signal.SIGALRM, self.handle_timeout)
signal.alarm(self.seconds)
def __exit__(self, type, value, traceback):
signal.alarm(0)
You can subclass the C structure that is available in the standard library. The ctypes module provides a Structure class. The example from the docs:
>>> from ctypes import *
>>> class POINT(Structure):
... _fields_ = [("x", c_int),
... ("y", c_int)]
...
>>> point = POINT(10, 20)
>>> print point.x, point.y
10 20
>>> point = POINT(y=5)
>>> print point.x, point.y
0 5
>>> POINT(1, 2, 3)
Traceback (most recent call last):
File "<stdin>", line 1, in ?
ValueError: too many initializers
>>>
>>> class RECT(Structure):
... _fields_ = [("upperleft", POINT),
... ("lowerright", POINT)]
...
>>> rc = RECT(point)
>>> print rc.upperleft.x, rc.upperleft.y
0 5
>>> print rc.lowerright.x, rc.lowerright.y
0 0
>>>
You are passing a dictionary to a function that expects a string.
This syntax:
{"('Hello',)": 6, "('Hi',)": 5}
is both a valid Python dictionary literal and a valid JSON object literal. But loads
doesn't take a dictionary; it takes a string, which it then interprets as JSON and returns the result as a dictionary (or string or array or number, depending on the JSON, but usually a dictionary).
If you pass this string to loads
:
'''{"('Hello',)": 6, "('Hi',)": 5}'''
then it will return a dictionary that looks a lot like the one you are trying to pass to it.
You could also exploit the similarity of JSON object literals to Python dictionary literals by doing this:
json.loads(str({"('Hello',)": 6, "('Hi',)": 5}))
But in either case you would just get back the dictionary that you're passing in, so I'm not sure what it would accomplish. What's your goal?
You can use https://grabz.it solution.
It's got a PHP API which is very flexible and can be called in different ways such as from a cronjob or a PHP web page.
In order to implement it you will need to first get an app key and secret and download the (free) SDK.
And an example for implementation. First of all initialization:
include("GrabzItClient.class.php");
// Create the GrabzItClient class
// Replace "APPLICATION KEY", "APPLICATION SECRET" with the values from your account!
$grabzIt = new GrabzItClient("Sign in to view your Application Key", "Sign in to view your Application Secret");
And screenshoting example:
// To take a image screenshot
$grabzIt->URLToImage("http://www.google.com");
// Or to take a PDF screenshot
$grabzIt->URLToPDF("http://www.google.com");
// Or to convert online videos into animated GIF's
$grabzIt->URLToAnimation("http://www.example.com/video.avi");
// Or to capture table(s)
$grabzIt->URLToTable("http://www.google.com");
Next is the saving.You can use one of the two save methods, Save
if publicly accessible callback handle available and SaveTo
if not. Check the documentation for details.
In this example you can identify different areas:
<html>
<style>
#divContainer {
width: 100%;
height: 100%;
}
#divHeader {
position: absolute;
left: 0px;
top: 0px;
right: 0px;
height: 28px;
background-color:blue;
}
#divContentArea {
position: absolute;
left: 0px;
top: 30px;
right: 0px;
bottom: 30px;
}
#divContentLeft {
position: absolute;
top: 0px;
left: 0px;
width: 200px;
bottom: 0px;
background-color:red;
}
#divContentCenter {
position: absolute;
top: 0px;
left: 200px;
bottom: 0px;
right:200px;
background-color:yellow;
}
#divContentRight {
position: absolute;
top: 0px;
right: 0px;
bottom: 0px;
width:200px;
background-color:red;
}
#divFooter {
position: absolute;
height: 28px;
left: 0px;
bottom: 0px;
right: 0px;
background-color:blue;
}
</style>
<body >
<div id="divContainer">
<div id="divHeader"> top
</div>
<div id="divContentArea">
<div id="divContentLeft">left
</div>
<div id="divContentCenter">center
</div>
<div id="divContentRight">right
</div>
</div>
<div id="divFooter">bottom
</div>
</div>
</body>
</html>
This is considered as features in Gitlab.
Maintainer / Owner
access is never able to force push again for default & protected branch, as stated in this docs
The string that you get is just the JSON Object.toString(). It means that you get the JSON object, but in a String format.
If you are supposed to get a JSON Object you can just put:
JSONObject myObject = new JSONObject(result);
you don’t need a select … from dual
, just write:
SELECT t.*, dbms_random.value(1,9) RandomNumber
FROM myTable t
private static int countWordsInSentence(String input) {
int wordCount = 0;
if (input.trim().equals("")) {
return wordCount;
}
else {
wordCount = 1;
}
for (int i = 0; i < input.length(); i++) {
char ch = input.charAt(i);
String str = new String("" + ch);
if (i+1 != input.length() && str.equals(" ") && !(""+ input.charAt(i+1)).equals(" ")) {
wordCount++;
}
}
return wordCount;
}
If you want to analyze, repair and optimize all tables in all databases in your MySQL server, you can do this in one go from the command line. You will need root to do that though.
mysqlcheck -u root -p --auto-repair --optimize --all-databases
Once you run that, you will be prompted to enter your MySQL root password. After that, it will start and you will see results as it's happening.
Example output:
yourdbname1.yourdbtable1 OK
yourdbname2.yourdbtable2 Table is already up to date
yourdbname3.yourdbtable3
note : Table does not support optimize, doing recreate + analyze instead
status : OK
etc..
etc...
Repairing tables
yourdbname10.yourdbtable10
warning : Number of rows changed from 121378 to 81562
status : OK
If you don't know the root password and are using WHM, you can change it from within WHM by going to: Home > SQL Services > MySQL Root Password
For version 4.0, 4.5 on Windows
File -> Settings
Then,
Editor -> General -> Appearance -> Show line numbers
For version 4.0 on Mac OSX
PyCharm-->Preferences
Then,
Editor-->General-->Appearance-->checkbox: "Show line numbers"
Casting pointers is usually invalid in C. There are several reasons:
Alignment. It's possible that, due to alignment considerations, the destination pointer type is not able to represent the value of the source pointer type. For example, if int *
were inherently 4-byte aligned, casting char *
to int *
would lose the lower bits.
Aliasing. In general it's forbidden to access an object except via an lvalue of the correct type for the object. There are some exceptions, but unless you understand them very well you don't want to do it. Note that aliasing is only a problem if you actually dereference the pointer (apply the *
or ->
operators to it, or pass it to a function that will dereference it).
The main notable cases where casting pointers is okay are:
When the destination pointer type points to character type. Pointers to character types are guaranteed to be able to represent any pointer to any type, and successfully round-trip it back to the original type if desired. Pointer to void (void *
) is exactly the same as a pointer to a character type except that you're not allowed to dereference it or do arithmetic on it, and it automatically converts to and from other pointer types without needing a cast, so pointers to void are usually preferable over pointers to character types for this purpose.
When the destination pointer type is a pointer to structure type whose members exactly match the initial members of the originally-pointed-to structure type. This is useful for various object-oriented programming techniques in C.
Some other obscure cases are technically okay in terms of the language requirements, but problematic and best avoided.
You can also try using parameters directive for making your build parameterized and accessing parameters:
Doc: Pipeline syntax: Parameters
Example:
pipeline{
agent { node { label 'test' } }
options { skipDefaultCheckout() }
parameters {
string(name: 'suiteFile', defaultValue: '', description: 'Suite File')
}
stages{
stage('Initialize'){
steps{
echo "${params.suiteFile}"
}
}
}
First: reload(sys)
and setting some random default encoding just regarding the need of an output terminal stream is bad practice. reload
often changes things in sys which have been put in place depending on the environment - e.g. sys.stdin/stdout streams, sys.excepthook, etc.
The best solution I know for solving the encode problem of print
'ing unicode strings and beyond-ascii str
's (e.g. from literals) on sys.stdout is: to take care of a sys.stdout (file-like object) which is capable and optionally tolerant regarding the needs:
When sys.stdout.encoding
is None
for some reason, or non-existing, or erroneously false or "less" than what the stdout terminal or stream really is capable of, then try to provide a correct .encoding
attribute. At last by replacing sys.stdout & sys.stderr
by a translating file-like object.
When the terminal / stream still cannot encode all occurring unicode chars, and when you don't want to break print
's just because of that, you can introduce an encode-with-replace behavior in the translating file-like object.
Here an example:
#!/usr/bin/env python
# encoding: utf-8
import sys
class SmartStdout:
def __init__(self, encoding=None, org_stdout=None):
if org_stdout is None:
org_stdout = getattr(sys.stdout, 'org_stdout', sys.stdout)
self.org_stdout = org_stdout
self.encoding = encoding or \
getattr(org_stdout, 'encoding', None) or 'utf-8'
def write(self, s):
self.org_stdout.write(s.encode(self.encoding, 'backslashreplace'))
def __getattr__(self, name):
return getattr(self.org_stdout, name)
if __name__ == '__main__':
if sys.stdout.isatty():
sys.stdout = sys.stderr = SmartStdout()
us = u'aouäöü?zß²'
print us
sys.stdout.flush()
The only good reason to change the global default encoding (to UTF-8 only) I think is regarding an application source code decision - and not because of I/O stream encodings issues: For writing beyond-ascii string literals into code without being forced to always use u'string'
style unicode escaping. This can be done rather consistently (despite what anonbadger's article says) by taking care of a Python 2 or Python 2 + 3 source code basis which uses ascii or UTF-8 plain string literals consistently - as far as those strings potentially undergo silent unicode conversion and move between modules or potentially go to stdout. For that, prefer "# encoding: utf-8
" or ascii (no declaration). Change or drop libraries which still rely in a very dumb way fatally on ascii default encoding errors beyond chr #127 (which is rare today).
And do like this at application start (and/or via sitecustomize.py) in addition to the SmartStdout
scheme above - without using reload(sys)
:
...
def set_defaultencoding_globally(encoding='utf-8'):
assert sys.getdefaultencoding() in ('ascii', 'mbcs', encoding)
import imp
_sys_org = imp.load_dynamic('_sys_org', 'sys')
_sys_org.setdefaultencoding(encoding)
if __name__ == '__main__':
sys.stdout = sys.stderr = SmartStdout()
set_defaultencoding_globally('utf-8')
s = 'aouäöü?zß²'
print s
This way string literals and most operations (except character iteration) work comfortable without thinking about unicode conversion as if there would be Python3 only. File I/O of course always need special care regarding encodings - as it is in Python3.
Note: plains strings then are implicitely converted from utf-8 to unicode in SmartStdout
before being converted to the output stream enconding.
If i
is the int
, then
char c = i;
makes it a char
. You might want to add a check that the value is <128
if it comes from an untrusted source. This is best done with isascii
from <ctype.h>
, if available on your system (see @Steve Jessop's comment to this answer).
You have the following solution from https://www.mkyong.com/java/java-how-to-compare-two-sets/
public static boolean equals(Set<?> set1, Set<?> set2){
if(set1 == null || set2 ==null){
return false;
}
if(set1.size() != set2.size()){
return false;
}
return set1.containsAll(set2);
}
Or if you prefer to use a single return statement:
public static boolean equals(Set<?> set1, Set<?> set2){
return set1 != null
&& set2 != null
&& set1.size() == set2.size()
&& set1.containsAll(set2);
}
Flow allows interface specification, without having to convert your whole code base to TypeScript.
Interfaces are a way of breaking dependencies, while stepping cautiously within existing code.
I think the question is a little bit fuzzy - for example, it can be interpreted as a question about best practices in programming loops with if
inside. So, I'll try to answer this question with this particular interpretation.
If you have if
inside a loop, then in most cases you'd like to know how the loop has ended - was it "broken" by the if
or was it ended "naturally"? So, your sample code can be modified in this way:
bool intMaxFound = false;
for (size = 0; size < HAY_MAX; size++)
{
// wait for hay until EOF
printf("\nhaystack[%d] = ", size);
int straw = GetInt();
if (straw == INT_MAX)
{intMaxFound = true; break;}
// add hay to stack
haystack[size] = straw;
}
if (intMaxFound)
{
// ... broken
}
else
{
// ... ended naturally
}
The problem with this code is that the if
statement is buried inside the loop body, and it takes some effort to locate it and understand what it does. A more clear (even without the break
statement) variant will be:
bool intMaxFound = false;
for (size = 0; size < HAY_MAX && !intMaxFound; size++)
{
// wait for hay until EOF
printf("\nhaystack[%d] = ", size);
int straw = GetInt();
if (straw == INT_MAX)
{intMaxFound = true; continue;}
// add hay to stack
haystack[size] = straw;
}
if (intMaxFound)
{
// ... broken
}
else
{
// ... ended naturally
}
In this case you can clearly see (just looking at the loop "header") that this loop can end prematurely. If the loop body is a multi-page text, written by somebody else, then you'd thank its author for saving your time.
UPDATE:
Thanks to SO - it has just suggested the already answered question about crash of the AT&T phone network in 1990. It's about a risky decision of C creators to use a single reserved word break
to exit from both loops and switch
.
Anyway this interpretation doesn't follow from the sample code in the original question, so I'm leaving my answer as it is.
For 1-hot-encoding
one_hot_encode=pandas.get_dummies(array)
ENJOY CODING
If you cannot see the "Scripts" tab, make sure you are launching Chrome with the right arguments. I had this problem when I launched Chrome for debugging server-side JavaScript with the argument --remote-shell-port=9222
. I have no problem if I launch Chrome with no argument.
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
This will be different for each OS, based on the information at https://code.visualstudio.com/docs/customization/keybindings
Go Back: workbench.action.navigateBack Go Forward: workbench.action.navigateForward
Linux
Go Back: Ctrl+Alt+-
Go Forward: Ctrl+Shift+-
OSX ^- / ^?-
Windows Alt+ ? / ?
Go to mirror.olnevhost.net/pub/apache/maven/binaries/ and check what is the latest tar.gz file
Supposing it is e.g. apache-maven-3.2.1-bin.tar.gz, from the command line; you should be able to simply do:
wget http://mirror.olnevhost.net/pub/apache/maven/binaries/apache-maven-3.2.1-bin.tar.gz
And then proceed to install it.
UPDATE: Adding complete instructions (copied from the comment below)
run the following to extract the tar:
tar xvf apache-maven-3.2.1-bin.tar.gz
Next add the env varibles such as
export M2_HOME=/usr/local/apache-maven/apache-maven-3.2.1
export M2=$M2_HOME/bin
export PATH=$M2:$PATH
Verify
mvn -version
you are not using the $scope you must use $ctrl.area or $scope.area instead of area
Go to Solution properties ? Common Properties ? Startup Project and select Multiple startup projects.
"user.dir" is the current working directory, not the home directory It is all described here.
http://docs.oracle.com/javase/tutorial/essential/environment/sysprop.html
Also, by using \\
instead of File.separator, you will lose portability with *nix system which uses /
for file separator.
While sizeof
works for this specific type of string:
char str[] = "content";
int charcount = sizeof str - 1; // -1 to exclude terminating '\0'
It does not work if str
is pointer (sizeof
returns size of pointer, usually 4 or 8) or array with specified length (sizeof
will return the byte count matching specified length, which for char type are same).
Just use strlen()
.
It means '\0' is a NULL
character in C, don't know about Objective-C
but its probably the same.
This is a one-liner but uses four atomic commands:
head -1000 file.txt > newfile.txt; tail +1000 file.txt > file.txt.tmp; cp file.txt.tmp file.txt; rm file.txt.tmp
A nice approach that i have seen often and I had been used actually is to inject some NULL type element (or a created one, like uint THIS_IS_INFINITY = 82862863263;
) at end of the array.
Then at the loop condition check, TYPE *pagesWords
is some kind of pointer array:
int pagesWordsLength = sizeof(pagesWords) / sizeof(pagesWords[0]);
realloc (pagesWords, sizeof(pagesWords[0]) * (pagesWordsLength + 1);
pagesWords[pagesWordsLength] = MY_NULL;
for (uint i = 0; i < 1000; i++)
{
if (pagesWords[i] == MY_NULL)
{
break;
}
}
This solution won't word if array is filled with struct
types.
To get the first day of the month, simply get a Date
and set the current day to day 1 of the month. Clear hour, minute, second and milliseconds if you need it.
private static Date firstDayOfMonth(Date date) {
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
calendar.set(Calendar.DATE, 1);
return calendar.getTime();
}
First day of the week is the same thing, but using Calendar.DAY_OF_WEEK
instead
private static Date firstDayOfWeek(Date date) {
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
calendar.set(Calendar.DAY_OF_WEEK, 1);
return calendar.getTime();
}
public static String setPrecision(String number, int decimal) {
double nbr = Double.valueOf(number);
int integer_Part = (int) nbr;
double float_Part = nbr - integer_Part;
int floating_point = (int) (Math.pow(10, decimal) * float_Part);
String final_nbr = String.valueOf(integer_Part) + "." + String.valueOf(floating_point);
return final_nbr;
}
[Answer copied from a duplicate, now-deleted question.]
time()
is a very, very old function. It goes back to a day when the C language didn't even have type long
. Once upon a time, the only way to get something like a 32-bit type was to use an array of two int
s -- and that was when int
s were 16 bits.
So you called
int now[2];
time(now);
and it filled the 32-bit time into now[0]
and now[1]
, 16 bits at a time. (This explains why the other time-related functions, such as localtime
and ctime
, tend to accept their time arguments via pointers, too.)
Later on, dmr finished adding long
to the compiler, so you could start saying
long now;
time(&now);
Later still, someone realized it'd be useful if time()
went ahead and returned the value, rather than just filling it in via a pointer. But -- backwards compatibility is a wonderful thing -- for the benefit of all the code that was still doing time(&now)
, the time()
function had to keep supporting the pointer argument. Which is why -- and this is why backwards compatibility is not always such a wonderful thing -- if you're using the return value, you still have to pass NULL as a pointer:
long now = time(NULL);
(Later still, of course, we started using time_t
instead of plain long
for times, so that, for example, it can be changed to a 64-bit type, dodging the y2.038k problem.)
[P.S. I'm not actually sure the change from int [2]
to long
, and the change to add the return value, happened at different times; they might have happened at the same time. But note that when the time was represented as an array, it had to be filled in via a pointer, it couldn't be returned as a value, because of course C functions can't return arrays.]
Script to accomplish this, replace 'DB_NAME' with the database to kill all connections to:
USE master
GO
SET NOCOUNT ON
DECLARE @DBName varchar(50)
DECLARE @spidstr varchar(8000)
DECLARE @ConnKilled smallint
SET @ConnKilled=0
SET @spidstr = ''
Set @DBName = 'DB_NAME'
IF db_id(@DBName) < 4
BEGIN
PRINT 'Connections to system databases cannot be killed'
RETURN
END
SELECT @spidstr=coalesce(@spidstr,',' )+'kill '+convert(varchar, spid)+ '; '
FROM master..sysprocesses WHERE dbid=db_id(@DBName)
IF LEN(@spidstr) > 0
BEGIN
EXEC(@spidstr)
SELECT @ConnKilled = COUNT(1)
FROM master..sysprocesses WHERE dbid=db_id(@DBName)
END
You may get more success if you do a "search" for the runtime env from the preferences screen instead of hitting "add" - see this demo on youtube. http://www.youtube.com/watch?v=EOkN5IPoJVs&playnext_from=TL&videos=rVnITzSU2Z8 - When you hit search, you are prompted to point to the tomcat directory and then it SHOULD add it as a server runtime environment. Unfortunately for me, that is not the case (I get "no new server runtime environments were found") But you might have more success.
I like more another approach described in a similar question: https://stackoverflow.com/a/11885521/2215679
This approach is better especially in case if you need to show more than one field in SELECT. To avoid Error Code: 1241. Operand should contain 1 column(s)
or double sub-select for each column.
For your situation the Query should looks like:
SELECT
c.id,
c.title,
p.id AS product_id,
p.title AS product_title
FROM categories AS c
JOIN products AS p ON
p.id = ( --- the PRIMARY KEY
SELECT p1.id FROM products AS p1
WHERE c.id=p1.category_id
ORDER BY p1.id LIMIT 1
)
I had the same problem and I solved by using the postcast server. You can install it locally and use it.
This is implementation dependent, as the C standard does NOT define the signed-ness of char
. Depending on the platform, char may be signed
or unsigned
, so you need to explicitly ask for signed char
or unsigned char
if your implementation depends on it. Just use char
if you intend to represent characters from strings, as this will match what your platform puts in the string.
The difference between signed char
and unsigned char
is as you'd expect. On most platforms, signed char
will be an 8-bit two's complement number ranging from -128
to 127
, and unsigned char
will be an 8-bit unsigned integer (0
to 255
). Note the standard does NOT require that char
types have 8 bits, only that sizeof(char)
return 1
. You can get at the number of bits in a char with CHAR_BIT
in limits.h
. There are few if any platforms today where this will be something other than 8
, though.
There is a nice summary of this issue here.
As others have mentioned since I posted this, you're better off using int8_t
and uint8_t
if you really want to represent small integers.
In the .service file under the [Unit] section:
[Unit]
Description=My Website
After=syslog.target network.target mongodb.service
The important part is the mongodb.service
The manpage describes it however due to formatting it's not as clear on first sight
I recommend a generic solution so you don't have to add the code for every form. Use the jquery form plugin (http://jquery.malsup.com/form/) and add this code.
$(function(){
$('form.ajax_submit').submit(function() {
$(this).ajaxSubmit();
//validation and other stuff
return false;
});
});
You can use below code for multiple select:
<select asp-for="EmployeeId" multiple="multiple" asp-items="@ViewBag.Employees">
<option>Please select</option>
</select>
You can also use:
<select id="EmployeeId" name="EmployeeId" multiple="multiple" asp-items="@ViewBag.Employees">
<option>Please select</option>
</select>
Here is the code to get the Dimensions of the complete view of the device.
var windowSize = Dimensions.get("window");
Use it like this:
width=windowSize.width,heigth=windowSize.width/0.565
For those who are still getting the error even though you added proper keys into Info.plist:
Make sure you are adding the key into correct Info.plist. Newer version of xCode, apparently has 3 Info.plist.
One is under folder with your app's name which solved problem for me.
Second is under YourappnameTests and third one is under YourappnameUITests.
Hope it helps.
div{_x000D_
border: 1px solid;_x000D_
}_x000D_
span{_x000D_
display: flex;_x000D_
align-items: center;_x000D_
}_x000D_
.col-5{_x000D_
width: 100px;_x000D_
height: 50px;_x000D_
float: left;_x000D_
background: red;_x000D_
}_x000D_
.col-7{_x000D_
width: 200px;_x000D_
height: 24px;_x000D_
_x000D_
float: left;_x000D_
background: green;_x000D_
}
_x000D_
<span>_x000D_
<div class="col-5">_x000D_
</div>_x000D_
<div class="col-7"></div>_x000D_
</span>
_x000D_
Also, when checking for the last image, you must compare with imgArray.length-1
because, for example, when array length is 2 then I will take the values 0 and 1, it won't reach the value 2, so you must compare with length-1 not with length, here is the fixed line:
if(i == imgArray.length-1)
%20
is the space between AmberCRO SOP.
Try -
href="http://file:///K:/AmberCRO SOP/2011-07-05/SOP-SOP-3.0.pdf"
Or rename the folder as AmberCRO-SOP and write it as -
href="http://file:///K:/AmberCRO-SOP/2011-07-05/SOP-SOP-3.0.pdf"
go to manage clinet page in :
http://www.instagram.com/developer/
set a redirect url
then :
use this code to get access token :
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>tst</title>
<script src="../jq.js"></script>
<script type="text/javascript">
$.ajax({
type: 'GET',
url: 'https://api.instagram.com/oauth/authorize/?client_id=CLIENT-??ID&redirect_uri=REDI?RECT-URI&response_ty?pe=code'
dataType: 'jsonp'}).done(function(response){
var access = window.location.hash.substring(14);
//you have access token in access var
});
</script>
</head>
<body>
</body>
</html>
Get yourself a 64-bit JVM from Oracle.
Use the browser/chrome postman plugin to check the CORS/SOP like a website. Use desktop application instead to avoid these controls.
Personally more than anything I would change the logic, or look at the business rules to see if they dictate any potential naming.
Since, the actual condition that toggles the boolean is actually the act of being "last". I would say that switching the logic, and naming it "IsLastItem" or similar would be a more preferred method.
If you are using jQuery 1.2 or newer, you can simply use these:
$(window).width();
$(document).width();
$(window).height();
$(document).height();
From there it is a simple matter to decide the height of your element.
To give a detailed answer to question 3: yes, there are (rare) occasions when you might call the destructor explicitly, in particular as the counterpart to a placement new, as dasblinkenlight observes.
To give a concrete example of this:
#include <iostream>
#include <new>
struct Foo
{
Foo(int i_) : i(i_) {}
int i;
};
int main()
{
// Allocate a chunk of memory large enough to hold 5 Foo objects.
int n = 5;
char *chunk = static_cast<char*>(::operator new(sizeof(Foo) * n));
// Use placement new to construct Foo instances at the right places in the chunk.
for(int i=0; i<n; ++i)
{
new (chunk + i*sizeof(Foo)) Foo(i);
}
// Output the contents of each Foo instance and use an explicit destructor call to destroy it.
for(int i=0; i<n; ++i)
{
Foo *foo = reinterpret_cast<Foo*>(chunk + i*sizeof(Foo));
std::cout << foo->i << '\n';
foo->~Foo();
}
// Deallocate the original chunk of memory.
::operator delete(chunk);
return 0;
}
The purpose of this kind of thing is to decouple memory allocation from object construction.
Solved this problem with flag --with-darwinssl
Go to folder with curl source code
Download it here https://curl.haxx.se/download.html
sudo ./configure --with-darwinssl
make
make install
restart your console and it is done!
You may also want to take a look at OAuth, an emerging open protocol for token-based authorization specifically targeting http apis.
It is very similar to the approach taken by flickr and remember the milk "rest" apis (not necessarily good examples of restful apis, but good examples of the token-based approach).
There's a pretty good explanation of first level caching on the Streamline Logic blog.
Basically, first level caching happens on a per session basis where as second level caching can be shared across multiple sessions.
In order to avoid a "Division by zero" error we have programmed it like this:
Select Case when divisor=0 then null
Else dividend / divisor
End ,,,
But here is a much nicer way of doing it:
Select dividend / NULLIF(divisor, 0) ...
Now the only problem is to remember the NullIf bit, if I use the "/" key.
\b in regular expressions match word boundaries (i.e. the location between the first word character and non-word character):
$ echo "bar embarassment" | sed "s/\bbar\b/no bar/g"
no bar embarassment
IPtables hacks don't work, at least on Docker 1.4.1.
The best way would be to run another container with the exposed port and relay with socat. This is what I've done to (temporarily) connect to the database with SQLPlus:
docker run -d --name sqlplus --link db:db -p 1521:1521 sqlplus
Dockerfile:
FROM debian:7
RUN apt-get update && \
apt-get -y install socat && \
apt-get clean
USER nobody
CMD socat -dddd TCP-LISTEN:1521,reuseaddr,fork TCP:db:1521
A very, very good resource for these kinds of algorithms is Simmetrics: http://sourceforge.net/projects/simmetrics/
Unfortunately the awesome website containing a lot of the documentation is gone :( In case it comes back up again, its previous address was this: http://www.dcs.shef.ac.uk/~sam/simmetrics.html
Voila (courtesy of "Wayback Machine"): http://web.archive.org/web/20081230184321/http://www.dcs.shef.ac.uk/~sam/simmetrics.html
You can study the code source, there are dozens of algorithms for these kinds of comparisons, each with a different trade-off. The implementations are in Java.
Try using the @
symbol before the url string. Import your css in the following manner:
import Vue from 'vue'
require('@/assets/styles/main.css')
In your App.vue file you can do this to import a css file in the style tag
<template>
<div>
</div>
</template>
<style scoped src="@/assets/styles/mystyles.css">
</style>
import com.sun.org.apache.xml.internal.serializer.OutputPropertiesFactory
transformer.setOutputProperty(OutputPropertiesFactory.S_KEY_INDENT_AMOUNT, "2");
There is actually a much faster alternative to convert binary numbers to decimal, based on artificial intelligence (linear regression) model:
See example and time comparison below:
from sklearn.linear_model import LinearRegression
from sklearn.model_selection import train_test_split
import numpy as np
y = np.random.randint(0, 2**32, size=10_000)
def gen_x(y):
_x = bin(y)[2:]
n = 32 - len(_x)
return [int(sym) for sym in '0'*n + _x]
X = np.array([gen_x(x) for x in y])
model = LinearRegression()
model.fit(X, y)
def convert_bin_to_dec_ai(array):
return model.predict(array)
y_pred = convert_bin_to_dec_ai(X)
Time comparison:
This AI solution converts numbers almost x10 times faster than conventional way!
This is how I did it and it seems to work pretty well.
In you webpack.config.js file add the following:
devServer: {
inline:true,
port: 8008
},
Obviously you can use any port that is not conflicting with another. I mention the conflict issue only because I spent about 4 hrs. fighting an issue only to discover that my services were running on the same port.
Here is a complete test case that simulates the click
event, calls all handlers attached (however they have been attached), maintains the "target"
attribute ("srcElement"
in IE), bubbles like a normal event would, and emulates IE's recursion-prevention. Tested in FF 2, Chrome 2.0, Opera 9.10 and of course IE (6):
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<script>
function fakeClick(event, anchorObj) {
if (anchorObj.click) {
anchorObj.click()
} else if(document.createEvent) {
if(event.target !== anchorObj) {
var evt = document.createEvent("MouseEvents");
evt.initMouseEvent("click", true, true, window,
0, 0, 0, 0, 0, false, false, false, false, 0, null);
var allowDefault = anchorObj.dispatchEvent(evt);
// you can check allowDefault for false to see if
// any handler called evt.preventDefault().
// Firefox will *not* redirect to anchorObj.href
// for you. However every other browser will.
}
}
}
</script>
</head>
<body>
<div onclick="alert('Container clicked')">
<a id="link" href="#" onclick="alert((event.target || event.srcElement).innerHTML)">Normal link</a>
</div>
<button type="button" onclick="fakeClick(event, document.getElementById('link'))">
Fake Click on Normal Link
</button>
<br /><br />
<div onclick="alert('Container clicked')">
<div onclick="fakeClick(event, this.getElementsByTagName('a')[0])"><a id="link2" href="#" onclick="alert('foo')">Embedded Link</a></div>
</div>
<button type="button" onclick="fakeClick(event, document.getElementById('link2'))">Fake Click on Embedded Link</button>
</body>
</html>
It avoids recursion in non-IE browsers by inspecting the event object that is initiating the simulated click, by inspecting the target
attribute of the event (which remains unchanged during propagation).
Obviously IE does this internally holding a reference to its global event
object. DOM level 2 defines no such global variable, so for that reason the simulator must pass in its local copy of event
.
When filtering a DataFrame with string values, I find that the pyspark.sql.functions
lower
and upper
come in handy, if your data could have column entries like "foo" and "Foo":
import pyspark.sql.functions as sql_fun
result = source_df.filter(sql_fun.lower(source_df.col_name).contains("foo"))
The right way to do this, starting with Spring 4.1, is to use a @TestPropertySource
annotation.
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "classpath:whereever/context.xml")
@TestPropertySource(properties = {"myproperty = foo"})
public class TestWarSpringContext {
...
}
See @TestPropertySource in the Spring docs and Javadocs.
Appears you are having 'y' default to 1: An arrow function would be useful in 2020:
let x = (y = 1) => //insert operation with y here
Let 'x' be a function where 'y' is a parameter which would be assigned a default to '1' if it is some null or undefined value, then return some operation with y.
An AsyncTask
is background task which runs in the background thread. It takes an Input, performs Progress and gives Output.
ie
AsyncTask<Input,Progress,Output>
.
In my opinion the main source of confusion comes when we try to memorize the parameters in the AsyncTask
.
The key is Don't memorize.
If you can visualize what your task really needs to do then writing the AsyncTask
with the correct signature would be a piece of cake.
Just figure out what your Input, Progress and Output are and you will be good to go.
doInBackgound()
method is the most important method in an AsyncTask
because
AsyncTask
parameters.So lets see the relationship
doInBackground()
andonPostExecute()
,onProgressUpdate()
are also related
Show me the code
So how will I write the code for DownloadTask?
DownloadTask extends AsyncTask<String,Integer,String>{
@Override
public void onPreExecute()
{}
@Override
public String doInbackGround(String... params)
{
// Download code
int downloadPerc = // calculate that
publish(downloadPerc);
return "Download Success";
}
@Override
public void onPostExecute(String result)
{
super.onPostExecute(result);
}
@Override
public void onProgressUpdate(Integer... params)
{
// show in spinner, access UI elements
}
}
How will you run this Task
new DownLoadTask().execute("Paradise.mp3");
I prefer to use the ngModel and ngChange directives when dealing with checkboxes. ngModel allows you to bind the checked/unchecked state of the checkbox to a property on the entity:
<input type="checkbox" ng-model="entity.isChecked">
Whenever the user checks or unchecks the checkbox the entity.isChecked
value will change too.
If this is all you need then you don't even need the ngClick or ngChange directives. Since you have the "Check All" checkbox, you obviously need to do more than just set the value of the property when someone checks a checkbox.
When using ngModel with a checkbox, it's best to use ngChange rather than ngClick for handling checked and unchecked events. ngChange is made for just this kind of scenario. It makes use of the ngModelController for data-binding (it adds a listener to the ngModelController's $viewChangeListeners
array. The listeners in this array get called after the model value has been set, avoiding this problem).
<input type="checkbox" ng-model="entity.isChecked" ng-change="selectEntity()">
... and in the controller ...
var model = {};
$scope.model = model;
// This property is bound to the checkbox in the table header
model.allItemsSelected = false;
// Fired when an entity in the table is checked
$scope.selectEntity = function () {
// If any entity is not checked, then uncheck the "allItemsSelected" checkbox
for (var i = 0; i < model.entities.length; i++) {
if (!model.entities[i].isChecked) {
model.allItemsSelected = false;
return;
}
}
// ... otherwise ensure that the "allItemsSelected" checkbox is checked
model.allItemsSelected = true;
};
Similarly, the "Check All" checkbox in the header:
<th>
<input type="checkbox" ng-model="model.allItemsSelected" ng-change="selectAll()">
</th>
... and ...
// Fired when the checkbox in the table header is checked
$scope.selectAll = function () {
// Loop through all the entities and set their isChecked property
for (var i = 0; i < model.entities.length; i++) {
model.entities[i].isChecked = model.allItemsSelected;
}
};
CSS
What is the best way to... add a CSS class to the
<tr>
containing the entity to reflect its selected state?
If you use the ngModel approach for the data-binding, all you need to do is add the ngClass directive to the <tr>
element to dynamically add or remove the class whenever the entity property changes:
<tr ng-repeat="entity in model.entities" ng-class="{selected: entity.isChecked}">
See the full Plunker here.
Also it'd work to just specify ifelse()
twice:
plot(pos,cn, col= ifelse(cn >= 3, "red", ifelse(cn <= 1,"blue", "black")), ylim = c(0, 10))
Aligning to 6 bytes is not weird, because it is aligning to addresses multiple to 4.
So basically you have 34 bytes in your structure and the next structure should be placed on the address, that is multiple to 4. The closest value after 34 is 36. And this padding area counts into the size of the structure.
As I understand you use ASP.NET authentication and to set cookies persistent you need to set FormsAuthenticationTicket.IsPersistent = true It is the main idea.
bool isPersisted = true;
var authTicket = new FormsAuthenticationTicket(
1,
user_name,
DateTime.Now,
DateTime.Now.AddYears(1),//Expiration (you can set it to 1 year)
isPersisted,//THIS IS THE MAIN FLAG
addition_data);
HttpCookie authCookie = new HttpCookie(FormsAuthentication.FormsCookieName, authTicket );
if (isPersisted)
authCookie.Expires = authTicket.Expiration;
HttpContext.Current.Response.Cookies.Add(authCookie);
I know this thread is somewhat old, but there are a lot of really hacky answers on here, so I'd like to provide something that is a lot simpler and a lot cleaner:
select {
overflow-y: auto;
}
As you can see in this fiddle, this solution provides you with flexibility if you don't know the exact number of select options you are going to have. It hides the scrollbar in the case that you don't need it without hiding possible extra option elements in the other case. Don't do all this hacky overlapping div
stuff. It just makes for unreadable markup.
I was searching how to do something similar in WPF and I got this solution:
<ItemsControl ItemsSource="{Binding MyItems,Mode=OneWay}">
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<StackPanel Orientation="Vertical" />
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
<ItemsControl.ItemTemplate>
<DataTemplate>
<RadioButton
Content="{Binding}"
Command="{Binding Path=DataContext.CustomCommand,
RelativeSource={RelativeSource Mode=FindAncestor,
AncestorType={x:Type ItemsControl}} }"
CommandParameter="{Binding}" />
</DataTemplate>
</ItemsControl.ItemTemplate>
I hope this works for somebody else. I have a data context which is set automatically to the ItemsControls, and this data context has two properties: MyItems
-which is a collection-, and one command 'CustomCommand'. Because of the ItemTemplate
is using a DataTemplate
, the DataContext
of upper levels is not directly accessible. Then the workaround to get the DC of the parent is use a relative path and filter by ItemsControl
type.
You have to do the following 3 steps to fix your issues:
1.Download Node.js from here.
Install it and then add the path C:\Program Files\nodejs to your System variables.
Then restart your visual studio code editor.
Happy code
If you want to disable particular date(s) in jquery datepicker then here is the simple demo for you.
<script type="text/javascript">
var arrDisabledDates = {};
arrDisabledDates[new Date("08/28/2017")] = new Date("08/28/2017");
arrDisabledDates[new Date("12/23/2017")] = new Date("12/23/2017");
$(".datepicker").datepicker({
dateFormat: "dd/mm/yy",
beforeShowDay: function (date) {
var day = date.getDay(),
bDisable = arrDisabledDates[date];
if (bDisable)
return [false, "", ""]
}
});
</script>
Update in 2017: you probably want to use importlib
instead.
Make the Foo directory a package by adding an __init__.py
. In that __init__.py
add:
import bar
import eggs
import spam
Since you want it dynamic (which may or may not be a good idea), list all py-files with list dir and import them with something like this:
import os
for module in os.listdir(os.path.dirname(__file__)):
if module == '__init__.py' or module[-3:] != '.py':
continue
__import__(module[:-3], locals(), globals())
del module
Then, from your code do this:
import Foo
You can now access the modules with
Foo.bar
Foo.eggs
Foo.spam
etc. from Foo import *
is not a good idea for several reasons, including name clashes and making it hard to analyze the code.
$> printf "%x%x\n" "'A" "'a"
4161
Yup, often called a 'cookie jar' Google should provide many examples:
http://devzone.zend.com/16/php-101-part-10-a-session-in-the-cookie-jar/
http://curl.haxx.se/libcurl/php/examples/cookiejar.html <- good example IMHO
Copying that last one here so it does not go away...
Login to on one page and then get another page passing all cookies from the first page along Written by Mitchell
<?php
/*
This script is an example of using curl in php to log into on one page and
then get another page passing all cookies from the first page along with you.
If this script was a bit more advanced it might trick the server into
thinking its netscape and even pass a fake referer, yo look like it surfed
from a local page.
*/
$ch = curl_init();
curl_setopt($ch, CURLOPT_COOKIEJAR, "/tmp/cookieFileName");
curl_setopt($ch, CURLOPT_URL,"http://www.myterminal.com/checkpwd.asp");
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, "UserID=username&password=passwd");
ob_start(); // prevent any output
curl_exec ($ch); // execute the curl command
ob_end_clean(); // stop preventing output
curl_close ($ch);
unset($ch);
$ch = curl_init();
curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
curl_setopt($ch, CURLOPT_COOKIEFILE, "/tmp/cookieFileName");
curl_setopt($ch, CURLOPT_URL,"http://www.myterminal.com/list.asp");
$buf2 = curl_exec ($ch);
curl_close ($ch);
echo "<PRE>".htmlentities($buf2);
?>
Newer versions: (from 8.4 - mentioned in release notes)
TABLE mytablename;
Longer but works on all versions:
SELECT * FROM mytablename;
You may wish to use \x
first if it's a wide table, for readability.
For long data:
SELECT * FROM mytable LIMIT 10;
or similar.
For wide data (big rows), in the psql
command line client, it's useful to use \x
to show the rows in key/value form instead of tabulated, e.g.
\x
SELECT * FROM mytable LIMIT 10;
Note that in all cases the semicolon at the end is important.
And about timing:
fn1 <- function (N) {
for(i in as.numeric(1:N)) { y <- i*i }
}
fn2 <- function (N) {
i=1
while (i <= N) {
y <- i*i
i <- i + 1
}
}
system.time(fn1(60000))
# user system elapsed
# 0.06 0.00 0.07
system.time(fn2(60000))
# user system elapsed
# 0.12 0.00 0.13
And now we know that for-loop is faster than while-loop. You cannot ignore warnings during timing.
Tackling this task, I'd first find the number of decimal places in x
, then round y
accordingly. I'd use:
y.toFixed(x.toString().split(".")[1].length);
It should convert x
to a string, split it over the decimal point, find the length of the right part, and then y.toFixed(length)
should round y
based on that length.
One thing you can do is this:
$(this)[0].value = "Something";
This allows jQuery to return the javascript object for that element, and you can bypass jQuery Functions.
Try to write your code between the HTML pre tag.
using Range with
[Range(typeof(Decimal), "0", "9999", ErrorMessage = "{0} must be a decimal/number between {1} and {2}.")]
[Range(typeof(Decimal),"0.0", "1000000000000000000"]
Hope it will help
My problem was that i had a exculding patern in the resorces folder. After removing it the
config.configure();
worked for me. With the structure src/java/...HibernateUtil.java and cfg file under src/resources.
instanceof is a keyword that can be used to test if an object is of a specified type.
Example :
public class MainClass {
public static void main(String[] a) {
String s = "Hello";
int i = 0;
String g;
if (s instanceof java.lang.String) {
// This is going to be printed
System.out.println("s is a String");
}
if (i instanceof Integer) {
// This is going to be printed as autoboxing will happen (int -> Integer)
System.out.println("i is an Integer");
}
if (g instanceof java.lang.String) {
// This case is not going to happen because g is not initialized and
// therefore is null and instanceof returns false for null.
System.out.println("g is a String");
}
}
Here is my source.
http://asktom.oracle.com/tkyte/Misc/DateDiff.html - link dead as of 2012-01-30
Looks like this is the resource:
http://asktom.oracle.com/pls/asktom/ASKTOM.download_file?p_file=6551242712657900129
You can get this if you ONLY configure https
as a site binding inside IIS.
You need to add http(80)
as well as https(443)
- at least I did :-)
<<
is the left-shift operator, as it is in many other languages.
Here RAM_DEPTH
will be 1
left-shifted by 8 bits
, which is equivalent to 2^8
, or 256
.
The items which will determine the performance impact are:
I created a microbenchmark for four different methods of dispatch. The results from Solaris are as follows, with the smaller number being faster:
InstanceOf 3156
class== 2925
OO 3083
Id 3067
use px for precise placement of graphical elements. use em for measurements having to do positioning and spacing around text elements like line-height etc. px is pixel accurate, em can change dynamically with the font in use
in case if your table has tbody
let tbl = document.getElementById("tbl").getElementsByTagName('tbody')[0];
console.log(tbl.rows[0].cells[0].innerHTML)
I used this command to find last 5 minutes logs for particular event "DHCPACK
", try below:
$ grep "DHCPACK" /var/log/messages | grep "$(date +%h\ %d) [$(date --date='5 min ago' %H)-$(date +%H)]:*:*"
Hi that one works fine for me, maybe useful for someone
select * from your_table where array_column ::text ilike ANY (ARRAY['%text_to_search%'::text]);
to input a file:
fin = open(filename) #filename should be a string type: e.g filename = 'file.txt'
to output this file you can do:
for element in fin:
print element
if the elements are a string you'd better add this before print:
element = element.strip()
strip()
remove notations like this: /n
See this URL for a easy example http://ajithmanmadhan.wordpress.com/2009/12/16/customizing-ckeditor-and-adding-a-new-toolbar-button/
There are a couple of steps:
1) create a plugin folder
2) register your plugin (the URL above says to edit the ckeditor.js file DO NOT do this, as it will break next time a new version is relased. Instead edit the config.js and add a line like so
config.extraPlugins = 'pluginX,pluginY,yourPluginNameHere';
3) make a JS file called plugin.js inside your plugin folder Here is my code
(function() {
//Section 1 : Code to execute when the toolbar button is pressed
var a = {
exec: function(editor) {
var theSelectedText = editor.getSelection().getNative();
alert(theSelectedText);
}
},
//Section 2 : Create the button and add the functionality to it
b='addTags';
CKEDITOR.plugins.add(b, {
init: function(editor) {
editor.addCommand(b, a);
editor.ui.addButton("addTags", {
label: 'Add Tag',
icon: this.path+"addTag.gif",
command: b
});
}
});
})();
On xampp -> Phpmyadmin -> config.inc 21st line you see:
$cfg['Servers'][$i]['password'] = '';
Add your password here and restart your xampp. The password will change.
Gavin,
The issue you are having is a misunderstanding of positioning. If you want it to be "fixed" relative to the parent, then you really want your #fixed
to be position:absolute
which will update its position relative to the parent.
This question fully describes positioning types and how to use them effectively.
In summary, your CSS should be
#wrap{
position:relative;
}
#fixed{
position:absolute;
top:30px;
left:40px;
}
Paste this on your command line:
export LC_CTYPE="en_US.UTF-8"
For more complex layouts I often used GridBagLayout, which is more complex, but that's the price. Today, I would probably check out MiGLayout.
You can do it, without javascript
see this link: http://yonax73.blogspot.com/2014/09/tabla-con-cabecera-estatica-cuerpo-con.html
or live demo: http://jsfiddle.net/yonatanalexis22/aeeme8mt/7/
table{
border-spacing: 0;
display: flex;/*Se ajuste dinamicamente al tamano del dispositivo**/
max-height: 40vh; /*El alto que necesitemos**/
overflow-y: auto; /**El scroll verticalmente cuando sea necesario*/
overflow-x: hidden;/*Sin scroll horizontal*/
table-layout: fixed;/**Forzamos a que las filas tenga el mismo ancho**/
width: 98vw; /*El ancho que necesitemos*/
border:1px solid gray;}
Maven dependency
<dependency>
<groupId>org.springframework.ws</groupId>
<artifactId>spring-ws-security</artifactId>
</dependency>
<dependency>
<groupId>org.apache.ws.security</groupId>
<artifactId>wss4j</artifactId>
<version>1.6.19</version>
</dependency>
Configuration class
import org.springframework.ws.soap.security.wss4j.Wss4jSecurityInterceptor;
@Configuration
public class ConfigurationClass{
@Bean
public Wss4jSecurityInterceptor securityInterceptor() {
Wss4jSecurityInterceptor wss4jSecurityInterceptor = new Wss4jSecurityInterceptor();
wss4jSecurityInterceptor.setSecurementActions("UsernameToken");
wss4jSecurityInterceptor.setSecurementMustUnderstand(true);
wss4jSecurityInterceptor.setSecurementPasswordType("PasswordText");
wss4jSecurityInterceptor.setSecurementUsername("123456789011");
wss4jSecurityInterceptor.setSecurementPassword("TestPass123");
return wss4jSecurityInterceptor;
}
Result xml
<SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/">
<SOAP-ENV:Header>
<wsse:Security
xmlns:wsse="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd"
xmlns:wsu="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd"
SOAP-ENV:mustUnderstand="1">
<wsse:UsernameToken wsu:Id="UsernameToken-F57F40DC89CD6998E214700450735811">
<wsse:Username>123456789011</wsse:Username>
<wsse:Password Type="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-username-token-profile-1.0#PasswordText">TestPass123</wsse:Password>
</wsse:UsernameToken>
</wsse:Security>
</SOAP-ENV:Header>
<SOAP-ENV:Body>
...
something
...
</SOAP-ENV:Body>
You could use the maven dependency plugin which has a nice dependency:get
goal since version 2.1. No need for a pom, everything happens on the command line.
To make sure to find the dependency:get
goal, you need to explicitly tell maven to use the version 2.1, i.e. you need to use the fully qualified name of the plugin, including the version:
mvn org.apache.maven.plugins:maven-dependency-plugin:2.1:get \
-DrepoUrl=url \
-Dartifact=groupId:artifactId:version
UPDATE: With older versions of Maven (prior to 2.1), it is possible to run dependency:get
normally (without using the fully qualified name and version) by forcing your copy of maven to use a given version of a plugin.
This can be done as follows:
1. Add the following line within the <settings>
element of your ~/.m2/settings.xml
file:
<usePluginRegistry>true</usePluginRegistry>
2. Add the file ~/.m2/plugin-registry.xml
with the following contents:
<?xml version="1.0" encoding="UTF-8"?>
<pluginRegistry xsi:schemaLocation="http://maven.apache.org/PLUGIN_REGISTRY/1.0.0 http://maven.apache.org/xsd/plugin-registry-1.0.0.xsd"
xmlns="http://maven.apache.org/PLUGIN_REGISTRY/1.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-dependency-plugin</artifactId>
<useVersion>2.1</useVersion>
<rejectedVersions/>
</plugin>
</plugins>
</pluginRegistry>
But this doesn't seem to work anymore with maven 2.1/2.2. Actually, according to the Introduction to the Plugin Registry, features of the plugin-registry.xml
have been redesigned (for portability) and the plugin registry is currently in a semi-dormant state within Maven 2. So I think we have to use the long name for now (when using the plugin without a pom, which is the idea behind dependency:get
).
Was getting same error. My device was not connected to android studio. When I connected to studio. It works. This solves my problem.
I just want to explain it in my own way with a small story that I experienced in one of my projects. First I want to explain Why DAO is important? rather than go to What is DAO? for better understanding.
Why DAO is important?
In my one project of my project, I used Client.class
which contains all the basic information of our system users. Where I need client then every time I need to do an ugly query where it is needed. Then I felt that decreases the readability and made a lot of redundant boilerplate code.
Then one of my senior developers introduced a QueryUtils.class
where all queries are added using public static
access modifier and then I don't need to do query everywhere. Suppose when I needed activated clients then I just call -
QueryUtils.findAllActivatedClients();
In this way, I made some optimizations of my code.
But there was another problem !!!
I felt that the QueryUtils.class was growing very highly. 100+ methods were included in that class which was also very cumbersome to read and use. Because this class contains other queries of another domain models ( For example- products, categories locations, etc ).
Then the superhero Mr. CTO introduced a new solution named DAO which solved the problem finally. I felt DAO is very domain-specific. For example, he created a DAO called ClientDAO.class
where all Client.class
related queries are found which seems very easy for me to use and maintain. The giant QueryUtils.class
was broken down into many other domain-specific DAO for example - ProductsDAO.class
, CategoriesDAO.class
, etc which made the code more Readable, more Maintainable, more Decoupled.
What is DAO?
It is an object or interface, which made an easy way to access data from the database without writing complex and ugly queries every time in a reusable way.
If you do what users YaW and Doug Paul say, then you have to have in mind that window features must be set prior to calling setContentView. If not, you will get an exception.
Thanks to the talk with Sarfraz we could figure out the solution.
The problem was that I was passing an HTML element instead of its value, which is actually what I wanted to do (in fact in my php code I need that value as a foreign key for querying my cities
table and filter correct entries).
So, instead of:
var data = {
'mode': 'filter_city',
'id_A': e[e.selectedIndex]
};
it should be:
var data = {
'mode': 'filter_city',
'id_A': e[e.selectedIndex].value
};
Note: check Jason Kulatunga's answer, it quotes JQuery doc to explain why passing an HTML element was causing troubles.
The clue is to work with the dict's items (i.e. key-value pair tuples). Then by using the second element of the item as the max
key (as opposed to the dict
key) you can easily extract the highest value and its associated key.
mydict = {'A':4,'B':10,'C':0,'D':87}
>>> max(mydict.items(), key=lambda k: k[1])
('D', 87)
>>> min(mydict.items(), key=lambda k: k[1])
('C', 0)
If you want to handle your webapp's timeout with an apache load balancer, you first have to understand the different meaning of timeout
.
I try to condense the discussion I found here: http://apache-http-server.18135.x6.nabble.com/mod-proxy-When-does-a-backend-be-considered-as-failed-td5031316.html :
It appears that
mod_proxy
considers a backend as failed only when the transport layer connection to that backend fails. Unlessfailonstatus/failontimeout
is used. ...
So, setting failontimeout
is necessary for apache to consider a timeout of the webapp (e.g. served by tomcat) as a fail (and consecutively switch to the hot spare server). For the proper configuration, note the following misconfiguration:
ProxyPass / balancer://localbalance/ failontimeout=on timeout=10 failonstatus=50
This is a misconfiguration because:
You are defining a
balancer
here, so thetimeout
parameter relates to thebalancer
(like the two others). However for abalancer
, thetimeout
parameter is not a connection timeout (like the one used withBalancerMember
), but the maximum time to wait for a free worker/member (e.g. when all the workers are busy or in error state, the default being to not wait).
So, a proper configuration is done like this
timeout
at the BalanceMember
level: <Proxy balancer://mycluster>
BalancerMember http://member1:8080/svc timeout=6
... more BalanceMembers here
</Proxy>
failontimeout
on the balancer
ProxyPass /svc balancer://mycluster failontimeout=on
Restart apache.
if not myList:
print "Nothing here"
By using typecasting you can resolve your problem. Just add the following lines to your return object:
$arrObj = array(yourReturnedObject);
You can also add a new key and value pair to it by using:
$arrObj['key'] = value;
Try:
find . -name "*.txt" | xargs grep -i "text_pattern"
My situation was solved by specifing the VM argument to the JAVA program being debugged, I assume you can also set this in `eclipse.ini file aswell:
I had the same issue with Windows 10.
First, I installed graphviz-2.38.0
with the following command without any problem...
install -c anaconda graphviz=2.38.0
Second, I installed pydotplus
with the following command without any problem...
install -c conda-forge pydotplus
After that, when I got to my step to visualize my decision tree had the following issue with {InvocationException: GraphViz's executables not found}
...
C:\Users\admin\Anaconda3\lib\site-packages\pydotplus\graphviz.py in create(self, prog, format)
1958 if self.progs is None:
1959 raise InvocationException(
-> 1960 'GraphViz\'s executables not found')
1961
1962 if prog not in self.progs:
InvocationException: GraphViz's executables not found
In my case, all I had to do to fix it is to put the environment path of the graphviz
executables in my user PATH
environment variable and this fixed it. Just make sure it is the path where YOUR.exe
files are located :)
C:\Users\admin\Anaconda3\pkgs\graphviz-2.38.0-4\Library\bin\graphviz
First of all you should include ckeditor and jquery connector script in your page,
then create a textarea
<textarea name="content" class="editor" id="ms_editor"></textarea>
attach ckeditor to the text area, in my project I use something like this:
$('textarea.editor').ckeditor(function() {
}, { toolbar : [
['Cut','Copy','Paste','PasteText','PasteFromWord','-','Print', 'SpellChecker', 'Scayt'],
['Undo','Redo'],
['Bold','Italic','Underline','Strike','-','Subscript','Superscript'],
['NumberedList','BulletedList','-','Outdent','Indent','Blockquote'],
['JustifyLeft','JustifyCenter','JustifyRight','JustifyBlock'],
['Link','Unlink','Anchor', 'Image', 'Smiley'],
['Table','HorizontalRule','SpecialChar'],
['Styles','BGColor']
], toolbarCanCollapse:false, height: '300px', scayt_sLang: 'pt_PT', uiColor : '#EBEBEB' } );
on submit get the content using:
var content = $( 'textarea.editor' ).val();
That's it! :)
I assume entropy was mentioned in the context of building decision trees.
To illustrate, imagine the task of learning to classify first-names into male/female groups. That is given a list of names each labeled with either m
or f
, we want to learn a model that fits the data and can be used to predict the gender of a new unseen first-name.
name gender
----------------- Now we want to predict
Ashley f the gender of "Amro" (my name)
Brian m
Caroline f
David m
First step is deciding what features of the data are relevant to the target class we want to predict. Some example features include: first/last letter, length, number of vowels, does it end with a vowel, etc.. So after feature extraction, our data looks like:
# name ends-vowel num-vowels length gender
# ------------------------------------------------
Ashley 1 3 6 f
Brian 0 2 5 m
Caroline 1 4 8 f
David 0 2 5 m
The goal is to build a decision tree. An example of a tree would be:
length<7
| num-vowels<3: male
| num-vowels>=3
| | ends-vowel=1: female
| | ends-vowel=0: male
length>=7
| length=5: male
basically each node represent a test performed on a single attribute, and we go left or right depending on the result of the test. We keep traversing the tree until we reach a leaf node which contains the class prediction (m
or f
)
So if we run the name Amro down this tree, we start by testing "is the length<7?" and the answer is yes, so we go down that branch. Following the branch, the next test "is the number of vowels<3?" again evaluates to true. This leads to a leaf node labeled m
, and thus the prediction is male (which I happen to be, so the tree predicted the outcome correctly).
The decision tree is built in a top-down fashion, but the question is how do you choose which attribute to split at each node? The answer is find the feature that best splits the target class into the purest possible children nodes (ie: nodes that don't contain a mix of both male and female, rather pure nodes with only one class).
This measure of purity is called the information. It represents the expected amount of information that would be needed to specify whether a new instance (first-name) should be classified male or female, given the example that reached the node. We calculate it based on the number of male and female classes at the node.
Entropy on the other hand is a measure of impurity (the opposite). It is defined for a binary class with values a
/b
as:
Entropy = - p(a)*log(p(a)) - p(b)*log(p(b))
This binary entropy function is depicted in the figure below (random variable can take one of two values). It reaches its maximum when the probability is p=1/2
, meaning that p(X=a)=0.5
or similarlyp(X=b)=0.5
having a 50%/50% chance of being either a
or b
(uncertainty is at a maximum). The entropy function is at zero minimum when probability is p=1
or p=0
with complete certainty (p(X=a)=1
or p(X=a)=0
respectively, latter implies p(X=b)=1
).
Of course the definition of entropy can be generalized for a discrete random variable X with N outcomes (not just two):
(the log
in the formula is usually taken as the logarithm to the base 2)
Back to our task of name classification, lets look at an example. Imagine at some point during the process of constructing the tree, we were considering the following split:
ends-vowel
[9m,5f] <--- the [..,..] notation represents the class
/ \ distribution of instances that reached a node
=1 =0
------- -------
[3m,4f] [6m,1f]
As you can see, before the split we had 9 males and 5 females, i.e. P(m)=9/14
and P(f)=5/14
. According to the definition of entropy:
Entropy_before = - (5/14)*log2(5/14) - (9/14)*log2(9/14) = 0.9403
Next we compare it with the entropy computed after considering the split by looking at two child branches. In the left branch of ends-vowel=1
, we have:
Entropy_left = - (3/7)*log2(3/7) - (4/7)*log2(4/7) = 0.9852
and the right branch of ends-vowel=0
, we have:
Entropy_right = - (6/7)*log2(6/7) - (1/7)*log2(1/7) = 0.5917
We combine the left/right entropies using the number of instances down each branch as weight factor (7 instances went left, and 7 instances went right), and get the final entropy after the split:
Entropy_after = 7/14*Entropy_left + 7/14*Entropy_right = 0.7885
Now by comparing the entropy before and after the split, we obtain a measure of information gain, or how much information we gained by doing the split using that particular feature:
Information_Gain = Entropy_before - Entropy_after = 0.1518
You can interpret the above calculation as following: by doing the split with the end-vowels
feature, we were able to reduce uncertainty in the sub-tree prediction outcome by a small amount of 0.1518 (measured in bits as units of information).
At each node of the tree, this calculation is performed for every feature, and the feature with the largest information gain is chosen for the split in a greedy manner (thus favoring features that produce pure splits with low uncertainty/entropy). This process is applied recursively from the root-node down, and stops when a leaf node contains instances all having the same class (no need to split it further).
Note that I skipped over some details which are beyond the scope of this post, including how to handle numeric features, missing values, overfitting and pruning trees, etc..
If anyone is using knockoutjs try:
ko.utils.arrayGetDistinctValues()
BTW have look at all ko.utils.array*
utilities.
According to Laravel Documentation states you can use this way:
$result->isEmpty();
The isEmpty
method returns true
if the collection is empty; otherwise, false
is returned.
[UPDATED privacy keys list to iOS 13 - see below]
There is a list of all Cocoa Keys
that you can specify in your Info.plist
file:
(Xcode: Target -> Info -> Custom iOS Target Properties)
iOS already required permissions to access microphone, camera, and media library earlier (iOS 6, iOS 7), but since iOS 10 app will crash if you don't provide the description why you are asking for the permission (it can't be empty).
Privacy keys with example description:
Alternatively, you can open Info.plist
as source code:
And add privacy keys like this:
<key>NSLocationAlwaysUsageDescription</key>
<string>${PRODUCT_NAME} always location use</string>
List of all privacy keys: [UPDATED to iOS 13]
NFCReaderUsageDescription
NSAppleMusicUsageDescription
NSBluetoothAlwaysUsageDescription
NSBluetoothPeripheralUsageDescription
NSCalendarsUsageDescription
NSCameraUsageDescription
NSContactsUsageDescription
NSFaceIDUsageDescription
NSHealthShareUsageDescription
NSHealthUpdateUsageDescription
NSHomeKitUsageDescription
NSLocationAlwaysUsageDescription
NSLocationUsageDescription
NSLocationWhenInUseUsageDescription
NSMicrophoneUsageDescription
NSMotionUsageDescription
NSPhotoLibraryAddUsageDescription
NSPhotoLibraryUsageDescription
NSRemindersUsageDescription
NSSiriUsageDescription
NSSpeechRecognitionUsageDescription
NSVideoSubscriberAccountUsageDescription
In the last months, two of my apps were rejected during the review because the camera usage description wasn't specifying what I do with taken photos.
I had to change the description from ${PRODUCT_NAME} need access to the camera to take a photo
to ${PRODUCT_NAME} need access to the camera to update your avatar
even though the app context was obvious (user tapped on the avatar).
It seems that Apple is now paying even more attention to the privacy usage descriptions, and we should explain in details why we are asking for permission.
select * from mytable where mydate > now() - interval '1 year';
If you only care about the date and not the time, substitute current_date
for now()
There are no apparent performance benefits to using readonly
, at least none that I've ever seen mentioned anywhere. It's just for doing exactly as you suggest, for preventing modification once it has been initialised.
So it's beneficial in that it helps you write more robust, more readable code. The real benefit of things like this come when you're working in a team or for maintenance. Declaring something as readonly
is akin to putting a contract for that variable's usage in the code. Think of it as adding documentation in the same way as other keywords like internal
or private
, you're saying "this variable should not be modified after initialisation", and moreover you're enforcing it.
So if you create a class and mark some member variables readonly
by design, then you prevent yourself or another team member making a mistake later on when they're expanding upon or modifying your class. In my opinion, that's a benefit worth having (at the small expense of extra language complexity as doofledorfer mentions in the comments).
I was just going through this myself. I had ensured that my MSSQLSERVER login user had full access
but it was still causing issues. It only worked once I moved the destination to the root of C. More importantly out of a user folder (even though I had a share with full permissions - even tried "Everyone" as a test).
I don't know if i consider my issue "fixed", however it is "working".
Just a FYI for any other users that come across this thread.
I have tried some hours now and the easiest way to stop browsers to jump to the anchor instead of scrolling to it is: Using another anchor (an id you do not use on the site). So instead of linking to "http://#YourActualID" you link to "http://#NoIDonYourSite". Poof, browsers won’t jump anymore.
Then just check if an anchor is set (with the script provided below, that is pulled out of the other thread!). And set your actual id you want to scroll to.
$(document).ready(function(){
$(window).load(function(){
// Remove the # from the hash, as different browsers may or may not include it
var hash = location.hash.replace('#','');
if(hash != ''){
// Clear the hash in the URL
// location.hash = ''; // delete front "//" if you want to change the address bar
$('html, body').animate({ scrollTop: $('#YourIDtoScrollTo').offset().top}, 1000);
}
});
});
See https://lightningsoul.com/media/article/coding/30/YOUTUBE-SOCKREAD-SCRIPT-FOR-MIRC#content for a working example.
I had the same problem. My project layout looked like
\---super
\---thirdparty
+---mod1-root
| +---mod1-linux32
| \---mod1-win32
\---mod2-root
+---mod2-linux32
\---mod2-win32
In my case, I had a mistake in my pom.xmls at the modX-root-level. I had copied the mod1-root tree and named it mod2-root. I incorrectly thought I had updated all the pom.xmls appropriately; but in fact, mod2-root/pom.xml had the same group and artifact ids as mod1-root/pom.xml. After correcting mod2-root's pom.xml to have mod2-root specific maven coordinates my issue was resolved.
You can run the passwd command and send it piped input. So, do something like:
echo thePassword | passwd theUsername --stdin
Sorry to add another answer, But I just pulled something like this off and this created the closest-to-UITextField kind of placeholder.
Hope this helps someone.
-(void)textViewDidChange:(UITextView *)textView{
if(textView.textColor == [UIColor lightGrayColor]){
textView.textColor = [UIColor blackColor]; // look at the comment section in this answer
textView.text = [textView.text substringToIndex: 0];// look at the comment section in this answer
}else if(textView.text.length == 0){
textView.text = @"This is some placeholder text.";
textView.textColor = [UIColor lightGrayColor];
textView.selectedRange = NSMakeRange(0, 0);
}
}
-(void)textViewDidChangeSelection:(UITextView *)textView{
if(textView.textColor == [UIColor lightGrayColor] && (textView.selectedRange.location != 0 || textView.selectedRange.length != 0)){
textView.selectedRange = NSMakeRange(0, 0);
}
}
This is what we ended up using:
n = 3
d = dict(raw_input().split() for _ in range(n))
print d
Input:
A1023 CRT
A1029 Regulator
A1030 Therm
Output:
{'A1023': 'CRT', 'A1029': 'Regulator', 'A1030': 'Therm'}
import Foo
dir(Foo)
import collections
dir(collections)
I tried to resolve with the suggested answer and still ran into some issues...
This was a solution to my problem:
ARG APP_EXE="AppName.exe"
ENV _EXE=${APP_EXE}
# Build a shell script because the ENTRYPOINT command doesn't like using ENV
RUN echo "#!/bin/bash \n mono ${_EXE}" > ./entrypoint.sh
RUN chmod +x ./entrypoint.sh
# Run the generated shell script.
ENTRYPOINT ["./entrypoint.sh"]
Specifically targeting your problem:
RUN echo "#!/bin/bash \n ./greeting --message ${ADDRESSEE}" > ./entrypoint.sh
RUN chmod +x ./entrypoint.sh
ENTRYPOINT ["./entrypoint.sh"]
public class Example extends Activity
{
private ListView lv;
ArrayList<String> arrlist=new ArrayList<String>();
//let me assume that you are putting the values in this arraylist
//Now convert your arraylist to array
//You will get an exmaple here
//http://www.java-tips.org/java-se-tips/java.lang/how-to-convert-an-arraylist-into-an-array.html
private String arr[]=convert(arrlist);
@Override
public void onCreate(Bundle bun)
{
super.onCreate(bun);
setContentView(R.layout.main);
lv=(ListView)findViewById(R.id.lv);
lv.setAdapter(new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1 , arr));
}
}
os.system('command')
returns a 16 bit number, which first 8 bits from left(lsb) talks about signal used by os to close the command, Next 8 bits talks about return code of command.
Refer my answer for more detail in What is the return value of os.system() in Python?
Change your input to this:
<input type='submit' value='submit request' onclick='return btnClick();'>
And return false in your function
function btnClick() {
if (!validData())
return false;
}
int days = 1;
var newDate = new Date(Date.now() + days*24*60*60*1000);
var days = 2;_x000D_
var newDate = new Date(Date.now()+days*24*60*60*1000);_x000D_
_x000D_
document.write('Today: <em>');_x000D_
document.write(new Date());_x000D_
document.write('</em><br/> New: <strong>');_x000D_
document.write(newDate);
_x000D_
I know it's an old post but I had the same issue today, what I did is simple : changing my script that send my playbook from my local host to the server, before sending it with maven command, I did this :
cat common_vars.yml > vars.yml
cat snapshot_vars.yml >> vars.yml
# or
#cat release_vars.yml >> vars.yml
mvn ....
The main problem with the validated answer is you'll have to parse the output to get the informations. Here is a query allowing you to get them in a more usable manner :
SELECT cols.TABLE_NAME, cols.COLUMN_NAME, cols.ORDINAL_POSITION,
cols.COLUMN_DEFAULT, cols.IS_NULLABLE, cols.DATA_TYPE,
cols.CHARACTER_MAXIMUM_LENGTH, cols.CHARACTER_OCTET_LENGTH,
cols.NUMERIC_PRECISION, cols.NUMERIC_SCALE,
cols.COLUMN_TYPE, cols.COLUMN_KEY, cols.EXTRA,
cols.COLUMN_COMMENT, refs.REFERENCED_TABLE_NAME, refs.REFERENCED_COLUMN_NAME,
cRefs.UPDATE_RULE, cRefs.DELETE_RULE,
links.TABLE_NAME, links.COLUMN_NAME,
cLinks.UPDATE_RULE, cLinks.DELETE_RULE
FROM INFORMATION_SCHEMA.`COLUMNS` as cols
LEFT JOIN INFORMATION_SCHEMA.`KEY_COLUMN_USAGE` AS refs
ON refs.TABLE_SCHEMA=cols.TABLE_SCHEMA
AND refs.REFERENCED_TABLE_SCHEMA=cols.TABLE_SCHEMA
AND refs.TABLE_NAME=cols.TABLE_NAME
AND refs.COLUMN_NAME=cols.COLUMN_NAME
LEFT JOIN INFORMATION_SCHEMA.REFERENTIAL_CONSTRAINTS AS cRefs
ON cRefs.CONSTRAINT_SCHEMA=cols.TABLE_SCHEMA
AND cRefs.CONSTRAINT_NAME=refs.CONSTRAINT_NAME
LEFT JOIN INFORMATION_SCHEMA.`KEY_COLUMN_USAGE` AS links
ON links.TABLE_SCHEMA=cols.TABLE_SCHEMA
AND links.REFERENCED_TABLE_SCHEMA=cols.TABLE_SCHEMA
AND links.REFERENCED_TABLE_NAME=cols.TABLE_NAME
AND links.REFERENCED_COLUMN_NAME=cols.COLUMN_NAME
LEFT JOIN INFORMATION_SCHEMA.REFERENTIAL_CONSTRAINTS AS cLinks
ON cLinks.CONSTRAINT_SCHEMA=cols.TABLE_SCHEMA
AND cLinks.CONSTRAINT_NAME=links.CONSTRAINT_NAME
WHERE cols.TABLE_SCHEMA=DATABASE()
AND cols.TABLE_NAME="table"
If you do my_list[-1]
this returns the last element of the list. Negative sequence indexes represent positions from the end of the array. Negative indexing means beginning from the end, -1 refers to the last item, -2 refers to the second-last item, etc.
I did a time test here, using each method 100000 times in a loop. The results surprised me. (The results still surprise me after editing them in response to valid criticism in the comments.)
Here's the script:
import timeit
bad_chars = '(){}<>'
setup = """import re
import string
s = 'Barack (of Washington)'
bad_chars = '(){}<>'
rgx = re.compile('[%s]' % bad_chars)"""
timer = timeit.Timer('o = "".join(c for c in s if c not in bad_chars)', setup=setup)
print "List comprehension: ", timer.timeit(100000)
timer = timeit.Timer("o= rgx.sub('', s)", setup=setup)
print "Regular expression: ", timer.timeit(100000)
timer = timeit.Timer('for c in bad_chars: s = s.replace(c, "")', setup=setup)
print "Replace in loop: ", timer.timeit(100000)
timer = timeit.Timer('s.translate(string.maketrans("", "", ), bad_chars)', setup=setup)
print "string.translate: ", timer.timeit(100000)
Here are the results:
List comprehension: 0.631745100021
Regular expression: 0.155561923981
Replace in loop: 0.235936164856
string.translate: 0.0965719223022
Results on other runs follow a similar pattern. If speed is not the primary concern, however, I still think string.translate
is not the most readable; the other three are more obvious, though slower to varying degrees.
I also Had to filter based on the URL pattern(/{servicename}/api/stats/)in java code .
if (path.startsWith("/{servicename}/api/statistics/")) {
validatingAuthToken(((HttpServletRequest) request).getHeader("auth_token"));
filterChain.doFilter(request, response);
}
But its bizarre, that servlet doesn't support url pattern other than (/*), This should be a very common case for servlet API's !
Ok I've done it. I'm sharing this code in case someone else will need it:
super.draw(canvas, mapView, true);
Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);
paint.setStrokeWidth(2);
paint.setColor(android.graphics.Color.RED);
paint.setStyle(Paint.Style.FILL_AND_STROKE);
paint.setAntiAlias(true);
Point point1_draw = new Point();
Point point2_draw = new Point();
Point point3_draw = new Point();
mapView.getProjection().toPixels(point1, point1_draw);
mapView.getProjection().toPixels(point2, point2_draw);
mapView.getProjection().toPixels(point3, point3_draw);
Path path = new Path();
path.setFillType(Path.FillType.EVEN_ODD);
path.moveTo(point1_draw.x,point1_draw.y);
path.lineTo(point2_draw.x,point2_draw.y);
path.lineTo(point3_draw.x,point3_draw.y);
path.lineTo(point1_draw.x,point1_draw.y);
path.close();
canvas.drawPath(path, paint);
//canvas.drawLine(point1_draw.x,point1_draw.y,point2_draw.x,point2_draw.y, paint);
return true;
Thanks for the hint Nicolas!
Use the left
function:
QString yourString = "This is a string";
QString leftSide = yourString.left(5);
qDebug() << leftSide; // output "This "
Also have a look at mid()
if you want more control.
Follow instructions (steps 1 to 3 don't needed in windows):
Find mysql config to edit:
/etc/mysql/my.cnf (Mysql 5.5)
/etc/mysql/conf.d/mysql.cnf (Mysql 5.6+)
Find bind-address=127.0.0.1
in config file change bind-address=0.0.0.0
(you can set bind address to one of your interface ips or like me use 0.0.0.0)
Restart mysql service run on console:
service restart mysql
Create a user with a safe password for remote connection. To do this run following command in mysql (if you are linux user to reach mysql console run mysql
and if you set password for root run mysql -p
):
GRANT ALL PRIVILEGES
ON *.* TO 'remote'@'%'
IDENTIFIED BY 'safe_password'
WITH GRANT OPTION;`
Now you should have a user with name of user
and password of safe_password
with capability of remote connect.
So this is way late, but I've discovered an answer, in case it becomes useful to anyone who comes across this thread.
Changes in value to hidden elements don't automatically fire the .change() event. So, wherever it is that you're setting that value, you also have to tell jQuery to trigger it.
function setUserID(myValue) {
$('#userid').val(myValue)
.trigger('change');
}
Once that's the case,
$('#userid').change(function(){
//fire your ajax call
})
should work as expected.
You can open the file using the ios::ate
flag (and ios::binary
flag), so the tellg()
function will give you directly the file size:
ifstream file( "example.txt", ios::binary | ios::ate);
return file.tellg();
TO_DATE supports conversion to DATE datatype, which doesn't support milliseconds. If you want millisecond support in Oracle, you should look at TIMESTAMP datatype and TO_TIMESTAMP function.
Hope that helps.
You need not to use even the package "tcltk". You can simply do as shown below:
write.csv(x, file = "c:\\myname\\yourfile.csv", row.names = FALSE)
Give your path inspite of "c:\myname\yourfile.csv".
hasExtra()
for checking if intent has data on key.getStringExtra()
directly.Pass Data
intent.putExtra(PutExtraConstants.USER_NAME, "user");
Get Data
String userName;
if (getIntent().hasExtra(PutExtraConstants.USER_NAME)) {
userName = getIntent().getStringExtra(PutExtraConstants.USER_NAME);
}
Always put keys in constants as best practice.
public interface PutExtraConstants {
String USER_NAME = "USER_NAME";
}
The closest I have come is by trying to create it, and seeing if it succeeds.
If your system has python2
as default, use below command to install packages to python3
$ python3 -m pip install <package-name>
Another simple example is to do a safe-thread modification in a session object.
public PlayerScore getHighScore() {
ServletContext ctx = getServletConfig().getServletContext();
AtomicReference<PlayerScore> holder
= (AtomicReference<PlayerScore>) ctx.getAttribute("highScore");
return holder.get();
}
public void updateHighScore(PlayerScore newScore) {
ServletContext ctx = getServletConfig().getServletContext();
AtomicReference<PlayerScore> holder
= (AtomicReference<PlayerScore>) ctx.getAttribute("highScore");
while (true) {
HighScore old = holder.get();
if (old.score >= newScore.score)
break;
else if (holder.compareAndSet(old, newScore))
break;
}
}
Source: http://www.ibm.com/developerworks/library/j-jtp09238/index.html
I know question is already answered.
But let me add one point here. This is not only case of true or false. See below:
var val="Do";
Var c= (val == "Do" || val == "Done")
? 7
: 0
Here if val is Do or Done then c will be 7 else it will be zero. In this case c will be 7.
This is actually another perspective of this operator.
Just simply the css style using white-space:nowrap
works very well to avoid text wrapping in cells. And ofcourse you can use the text-overflow:ellipsis
and overflow:hidden
for truncating text with ellipsis effect.
<td style="white-space:nowrap">Cell Value</td>
Make sure you are using Javascript module or not?!
if using js6 modules your html events attributes won't work.
in that case you must bring your function from global scope to module scope. Just add this to your javascript file:
window.functionName= functionName;
example:
<h1 onClick="functionName">some thing</h1>
Some readers will have another issue and need this fix. read the links below. the same problem occured with visual studio 2015 with the advent of windows sdk 10 which brings up libucrt. ucrt is the windows implementation of C Runtime (CRT) aka the posix runtime library. You most likely have code that was ported from unix... Welcome to the drawback
https://github.com/lordmulder/libsndfile-MSVC/blob/master/src/sf_unistd.h
https://lists.gnu.org/archive/html/bug-gnulib/2011-09/msg00224.html
https://msdn.microsoft.com/en-us/library/y23kc048.aspx
https://blogs.msdn.microsoft.com/vcblog/2015/03/03/introducing-the-universal-crt/
This provides you to retrieve information from your URI strings
$this->uri->segment(n); // n=1 for controller, n=2 for method, etc
Consider this example:
http://example.com/index.php/controller/action/1stsegment/2ndsegment
it will return
$this->uri->segment(1); // controller
$this->uri->segment(2); // action
$this->uri->segment(3); // 1stsegment
$this->uri->segment(4); // 2ndsegment
If you are using NGINX over linux and want a pure bash/html, you can add a mask on your template and pipe the requests to use the sed command to do a replace by using a regullar expression.
Anyway I would rather have a bash script that takes from a templates folder and generate the final HTML.
You can look at the HEAD pointer (stored in .git/HEAD
) to see the sha1 of the currently checked-out commit, or it will be of the format ref: refs/heads/foo
for example if you have a local ref foo
checked out.
EDIT: If you'd like to do this from a shell, git symbolic-ref HEAD
will give you the same information.
If you are looking for generic usage, here is my suggestion:
Create a class named as Run
:
class Run {
companion object {
fun after(delay: Long, process: () -> Unit) {
Handler().postDelayed({
process()
}, delay)
}
}
}
And use like this:
Run.after(1000, {
// print something useful etc.
})
The logarithm
Ok let's try and fully understand what a logarithm actually is.
Imagine we have a rope and we have tied it to a horse. If the rope is directly tied to the horse, the force the horse would need to pull away (say, from a man) is directly 1.
Now imagine the rope is looped round a pole. The horse to get away will now have to pull many times harder. The amount of times will depend on the roughness of the rope and the size of the pole, but let's assume it will multiply one's strength by 10 (when the rope makes a complete turn).
Now if the rope is looped once, the horse will need to pull 10 times harder. If the human decides to make it really difficult for the horse, he may loop the rope again round a pole, increasing it's strength by an additional 10 times. A third loop will again increase the strength by a further 10 times.
We can see that for each loop, the value increases by 10. The number of turns required to get any number is called the logarithm of the number i.e. we need 3 posts to multiple your strength by 1000 times, 6 posts to multiply your strength by 1,000,000.
3 is the logarithm of 1,000, and 6 is the logarithm of 1,000,000 (base 10).
So what does O(log n) actually mean?
In our example above, our 'growth rate' is O(log n). For every additional loop, the force our rope can handle is 10 times more:
Turns | Max Force
0 | 1
1 | 10
2 | 100
3 | 1000
4 | 10000
n | 10^n
Now the example above did use base 10, but fortunately the base of the log is insignificant when we talk about big o notation.
Now let's imagine you are trying to guess a number between 1-100.
Your Friend: Guess my number between 1-100!
Your Guess: 50
Your Friend: Lower!
Your Guess: 25
Your Friend: Lower!
Your Guess: 13
Your Friend: Higher!
Your Guess: 19
Your Friend: Higher!
Your Friend: 22
Your Guess: Lower!
Your Guess: 20
Your Friend: Higher!
Your Guess: 21
Your Friend: YOU GOT IT!
Now it took you 7 guesses to get this right. But what is the relationship here? What is the most amount of items that you can guess from each additional guess?
Guesses | Items
1 | 2
2 | 4
3 | 8
4 | 16
5 | 32
6 | 64
7 | 128
10 | 1024
Using the graph, we can see that if we use a binary search to guess a number between 1-100 it will take us at most 7 attempts. If we had 128 numbers, we could also guess the number in 7 attemps but 129 numbers will takes us at most 8 attempts (in relations to logarithms, here we would need 7 guesses for a 128 value range, 10 guesses for a 1024 value range. 7 is the logarithm of 128, 10 is the logarithm of 1024 (base 2)).
Notice that I have bolded 'at most'. Big-O notation always refers to the worse case. If you're lucky, you could guess the number in one attempt and so the best case is O(1), but that's another story.
We can see that for every guess our data set is shrinking. A good rule of thumb to identify if an algorithm has a logarithmtic time is to see if the data set shrinks by a certain order after each iteration
What about O(n log n)?
You will eventually come across a linearithmic time O(n log(n)) algorithm. The rule of thumb above applies again, but this time the logarithmic function has to run n times e.g. reducing the size of a list n times, which occurs in algorithms like a mergesort.
You can easily identify if the algorithmic time is n log n. Look for an outer loop which iterates through a list (O(n)). Then look to see if there is an inner loop. If the inner loop is cutting/reducing the data set on each iteration, that loop is (O(log n)), and so the overall algorithm is = O(n log n).
Disclaimer: The rope-logarithm example was grabbed from the excellent Mathematician's Delight book by W.Sawyer.