Whenever such an error occurs. Try to check Following Things
Check what kind of Activity is being used, is it a simple android.app Activity or an AppCompatActivity or an ActionBarActivity and so on.
Check if your activity type which is extended falls under the compat category
example android.app based Activity/Fragment are non appCompat types, whereas android.support.v4.app.Fragment or android.support.v4.app.ActivityCompat are appCompat based
if it falls under appCompat we use getSupportActionBar() else for android.app types we can use getActionBar()
example: In the manifest file if theme applied is say android:theme="@android:style/Theme.Holo.Dialog" getActionBar() will work
but if theme applied for the activity in the manifest is as follows android:theme="@style/Theme.AppCompat.Light" then you have to use getSupportActionBar()
Use these animations:
bottom_up.xml
<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android">
<translate android:fromYDelta="75%p" android:toYDelta="0%p"
android:fillAfter="true"
android:duration="500"/>
</set>
bottom_down.xml
<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android">
<translate android:fromYDelta="0%p" android:toYDelta="100%p" android:fillAfter="true"
android:interpolator="@android:anim/linear_interpolator"
android:duration="500" />
</set>
Use this code in your activity for hiding/animating your view:
Animation bottomUp = AnimationUtils.loadAnimation(getContext(),
R.anim.bottom_up);
ViewGroup hiddenPanel = (ViewGroup)findViewById(R.id.hidden_panel);
hiddenPanel.startAnimation(bottomUp);
hiddenPanel.setVisibility(View.VISIBLE);
No curly braces required you can directly write
@if($user->status =='waiting')
<td><a href="#" class="viewPopLink btn btn-default1" role="button" data-id="{{ $user->travel_id }}" data-toggle="modal" data-target="#myModal">Approve/Reject<a></td>
@else
<td>{{ $user->status }}</td>
@endif
Here is a Github link to a lightweight and very easy to integrate library that enables you to play with borders as you want for any widget you want, simply based on a FrameLayout widget.
Here is a quick sample code for you to see how easy it is, but you will find more information on the link.
<com.khandelwal.library.view.BorderFrameLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
app:leftBorderColor="#00F0F0"
app:leftBorderWidth="10dp"
app:topBorderColor="#F0F000"
app:topBorderWidth="15dp"
app:rightBorderColor="#F000F0"
app:rightBorderWidth="20dp"
app:bottomBorderColor="#000000"
app:bottomBorderWidth="25dp" >
</com.khandelwal.library.view.BorderFrameLayout>
So, if you don't want borders on bottom, delete the two lines about bottom in this custom widget, and that's done.
And no, I'm neither the author of this library nor one of his friend ;-)
$(document).ready(function () {
$('#divType button').click(function () {
$(this).addClass('active').siblings().removeClass('active');
$('#<%= hidType.ClientID%>').val($(this).data('value'));
//alert($(this).data('value'));
});
});
_x000D_
<div class="col-xs-12">
<div class="form-group">
<asp:HiddenField ID="hidType" runat="server" />
<div class="btn-group" role="group" aria-label="Selection type" id="divType">
<button type="button" class="btn btn-default BtnType" data-value="1">Food</button>
<button type="button" class="btn btn-default BtnType" data-value="2">Drink</button>
</div>
</div>
</div>
_x000D_
Eclipse should be able to do it, go to TeamSynchronize perspective and then into Project->Apply patch
Here is a complete solution with application-json
:
// Input values will be grabbed by ID
<input id="loginEmail" type="text" name="email" placeholder="Email">
<input id="loginPassword" type="password" name="password" placeholder="Password">
// return stops normal action and runs login()
<button onclick="return login()">Submit</button>
<script>
function login() {
// Form fields, see IDs above
const params = {
email: document.querySelector('#loginEmail').value,
password: document.querySelector('#loginPassword').value
}
const http = new XMLHttpRequest()
http.open('POST', '/login')
http.setRequestHeader('Content-type', 'application/json')
http.send(JSON.stringify(params)) // Make sure to stringify
http.onload = function() {
// Do whatever with response
alert(http.responseText)
}
}
</script>
Ensure that your Backend API can parse JSON.
For example, in Express JS:
import bodyParser from 'body-parser'
app.use(bodyParser.json())
on command line type journalctl -xe
and the results will be
SELinux is preventing /usr/sbin/httpd from name_bind access on the tcp_socket port 83 or 80
This means that the SELinux is running on your machine and you need to disable it. then edit the configuration file by type the following
nano /etc/selinux/config
Then find the line SELINUX=enforce
and change to SELINUX=disabled
Then type the following and run the command to start httpd
setenforce 0
Lastly start a server
systemctl start httpd
I run cntlm
localy, configured with NTLMv2
password hashes to authenticate with the corporate proxy, and use
export MAVEN_OPTS="-DproxyHost=127.0.0.1 -DproxyPort=3128"
to use that proxy from maven
. Of course the proxy you use should support cntlm
/NTLMv2
.
<!DOCTYPE html>
<html>
<body>
<select name="" id="select" onClick="hello();">
<option>Select</option>
<option style="background-color: #CD5C5C;">#CD5C5C</option>
<option style="background-color: #F08080;">#F08080</option>
<option style="background-color: #FA8072;">#FA8072</option>
<option style="background-color: #E9967A;">#E9967A</option>
<option style="background-color: #FFA07A;">#FFA07A</option>
</select>
<script>
function hello(){
let d = document.getElementById("select");
let text = d.options[d.selectedIndex].value;
document.body.style.backgroundColor=text;
}
</script>
</body>
</html>
Currently, the eyedropper tool is not working in my version of Chrome (as described above), though it worked for me in the past. I hear it is being updated in the latest version of Chrome.
However, I'm able to grab colors easily in Firefox.
In case you cannot get the eyedropper tool to work in Chrome, this is a good work around.
I also find it easier to access :-)
UPDATE
(Given the upvotes, I feel there is a need for a complete step-by-step explanation...)
File
->Open Folder...
FOLDERS
sidebar available)View
-> Side Bar
-> Show Side Bar
FOLDERS
-titled Side Bar to navigate to the first file you want to compare.Diff Files...
There should be a new Tab now showing the comparison.
Original short answer:
Note that:
The "Diff files" only appears with the "folders" sidebar (to open a folder: File->Open Folder) , not with "open files" sidebar.
Looks like Users that are added in your Country object, are not already present in the DB. You need to use cascade to make sure that when Country is persisted, all User which are not there in data but are associated with Country also get persisted.
Below code should help:
@ManyToOne (cascade = CascadeType.ALL)
@JoinColumn (name = "countryId")
private Country country;
Visual Studio Express for Windows needs Windows 8.1. Having a look at the requirements page you might want to try the Web or Windows Desktop version which are able to run under Windows 7.
Bootstrap >= v4.0 dropped glyphicon support
Dropped the Glyphicons icon font. If you need icons, some options are:
the upstream version of Glyphicons
Source: https://v4-alpha.getbootstrap.com/migration/#components
If you are using Bootstrap >= v4.0 or newer, you can use existing style classes of bootstrap such as text-success
,text-warning
etc.
For example, if you are using fontawesome:
<i class="fa fa-tag text-danger" aria-hidden="true"></i>
You can call dispose()
on the current window and setVisible(true)
on the one you want to display.
Use the strong element, that is it's purpose:
<div id="content">
<p><strong>First Word</strong> rest of paragraph.</p>
</div>
Then create a style for it in your style sheet.
#content p strong
{
font-size: 14pt;
}
just use a regex as a separator:
', *' - for leading spaces
' *,' - for trailing spaces
for both leading and trailing:
awk -F' *,? *' '{print $1","$2}' input.txt
You can use the below syntax -
from FolderName.FileName import Classname
I'd say export your server config in IIS manager:
Move these files to your new server
administration.config
applicationHost.config
configEncKey.key
On the new server, go back to the “Shared Configuration” section and check “Enable shared configuration.” Enter the location in physical path to these files and apply them.
BAM! Go have a beer!
Great answers above. This one also illustrates @wraps
, which takes the doc string and function name from the original function and applies it to the new wrapped version:
from functools import wraps
def decorator_func_with_args(arg1, arg2):
def decorator(f):
@wraps(f)
def wrapper(*args, **kwargs):
print("Before orginal function with decorator args:", arg1, arg2)
result = f(*args, **kwargs)
print("Ran after the orginal function")
return result
return wrapper
return decorator
@decorator_func_with_args("foo", "bar")
def hello(name):
"""A function which prints a greeting to the name provided.
"""
print('hello ', name)
return 42
print("Starting script..")
x = hello('Bob')
print("The value of x is:", x)
print("The wrapped functions docstring is:", hello.__doc__)
print("The wrapped functions name is:", hello.__name__)
Prints:
Starting script..
Before orginal function with decorator args: foo bar
hello Bob
Ran after the orginal function
The value of x is: 42
The wrapped functions docstring is: A function which prints a greeting to the name provided.
The wrapped functions name is: hello
If you want to open inside the app itself instead of leaving the app you can import SafariServices and work it out.
import UIKit
import SafariServices
let url = URL(string: "https://www.google.com")
let vc = SFSafariViewController(url: url!)
present(vc, animated: true, completion: nil)
In my case I had to login to Apple Developer Website and reset the list of devices.
It appears they now require you to do it every year when the subscription is renewed, before being able to add new devices and generate certificates.
Perhaps you don't have to include the single quotes:
curl --request POST 'http://localhost/Service' --data "path=/xyz/pqr/test/&fileName=1.doc"
Update: Reading curl's manual, you could actually separate both fields with two --data:
curl --request POST 'http://localhost/Service' --data "path=/xyz/pqr/test/" --data "fileName=1.doc"
You could also try --data-binary:
curl --request POST 'http://localhost/Service' --data-binary "path=/xyz/pqr/test/" --data-binary "fileName=1.doc"
And --data-urlencode:
curl --request POST 'http://localhost/Service' --data-urlencode "path=/xyz/pqr/test/" --data-urlencode "fileName=1.doc"
IMO looking at the /proc
filesystem is less nasty than hacking the text output of ps
.
import os
pids = [pid for pid in os.listdir('/proc') if pid.isdigit()]
for pid in pids:
try:
print open(os.path.join('/proc', pid, 'cmdline'), 'rb').read().split('\0')
except IOError: # proc has already terminated
continue
Just use .only before 'describe', 'it' or 'context'. I run using "$npm run test:unit", and it executes only units with .only.
describe.only('get success', function() {
// ...
});
it.only('should return 1', function() {
// ...
});
Use obj[0].nick and you will get desired result,
If I had to do this with a regex, I'd do it like this:
s = re.sub(r'\.jpg$', '', s)
^\r\n
with nothing (select regular expression)Note: step 1 will remove your code intendation done via tabs and blank spaces
What about:
PrintWriter out = response.getWriter();
out.println("THE_STRING_TO_SEND_AS_RESPONSE");
return null;
This woks for me.
Would this work better?
import java.util.Scanner;
public class Work {
public static void main(String[] args){
System.out.println("Please enter the following information");
String name = "0";
String num = "0";
String address = "0";
int i = 0;
Scanner input = new Scanner(System.in);
//The Arrays
String [] contactName = new String [7];
String [] contactNum = new String [7];
String [] contactAdd = new String [7];
//I set these as the Array titles
contactName[0] = "Name";
contactNum[0] = "Phone Number";
contactAdd[0] = "Address";
//This asks for the information and builds an Array for each
//i -= i resets i back to 0 so the arrays are not 7,14,21+
while (i < 6){
i++;
System.out.println("Enter contact name." + i);
name = input.nextLine();
contactName[i] = name;
}
i -= i;
while (i < 6){
i++;
System.out.println("Enter contact number." + i);
num = input.nextLine();
contactNum[i] = num;
}
i -= i;
while (i < 6){
i++;
System.out.println("Enter contact address." + i);
num = input.nextLine();
contactAdd[i] = num;
}
//Now lets print out the Arrays
i -= i;
while(i < 6){
i++;
System.out.print( i + " " + contactName[i] + " / " );
}
//These are set to print the array on one line so println will skip a line
System.out.println();
i -= i;
i -= 1;
while(i < 6){
i++;
System.out.print( i + " " + contactNum[i] + " / " );
}
System.out.println();
i -= i;
i -= 1;
while(i < 6){
i++;
System.out.print( i + " " + contactAdd[i] + " / " );
}
System.out.println();
System.out.println("End of program");
}
}
This is my aproximation:
Declare
Variableclob Clob;
Temp_Save Varchar2(32767); //whether it is greater than 4000
Begin
Select reportClob Into Temp_Save From Reporte Where Id=...;
Variableclob:=To_Clob(Temp_Save);
Dbms_Output.Put_Line(Variableclob);
End;
This happened to me when I tried to update a table whose size on disk was bigger than the available disk space. The solution for me was simply to increase the available disk space.
For "English locale" file names, this works nicely. I'm using this for sanitizing uploaded file names. The file name is not meant to be linked to anything on disk, it's for when the file is being downloaded hence there are no path checks.
$file_name = preg_replace('/([^\x20-~]+)|([\\/:?"<>|]+)/g', '_', $client_specified_file_name);
Basically it strips all non-printable and reserved characters for Windows and other OSs. You can easily extend the pattern to support other locales and functionalities.
I found that I couldn't use multiple databases within the same database model when using EF. But in linq2sql I could just by prefixing the schema names with database names.
This was one of the reasons I originally began working with linq2sql. I do not know if EF has yet allowed this functionality, but I remember reading that it was intended for it not to allow this.
The other answers didn't work for me. I kept searching and found a blog post that covered how a team was running non-root inside of a docker container.
Here's the TL;DR version:
RUN apt-get update \
&& apt-get install -y sudo
RUN adduser --disabled-password --gecos '' docker
RUN adduser docker sudo
RUN echo '%sudo ALL=(ALL) NOPASSWD:ALL' >> /etc/sudoers
USER docker
# this is where I was running into problems with the other approaches
RUN sudo apt-get update
I was using FROM node:9.3
for this, but I suspect that other similar container bases would work as well.
One simple way to set session variable is by sending request to another PHP file. Here no need to use Jquery or any other library.
Consider I have index.php file where I am creating SESSION
variable (say $_SESSION['v']=0
) if SESSION
is not created otherwise I will load other file.
Code is like this:
session_start();
if(!isset($_SESSION['v']))
{
$_SESSION['v']=0;
}
else
{
header("Location:connect.php");
}
Now in count.html I want to set this session variable to 1.
Content in count.html
function doneHandler(result) {
window.location="setSession.php";
}
In count.html javascript part, send a request to another PHP file (say setSession.php
) where i can have access to session variable.
So in setSession.php will write
session_start();
$_SESSION['v']=1;
header('Location:index.php');
Although this question has been asked a while ago, it is still relevant as of today. This is not a trivial approach using script file params, but I already had some extreme use-cases that this way was most suited.
I came across this post to find out a better solution than I wrote a while ago, with hope to find maybe a native feature or something similar.
I will share my solution, up until a better one will be implemented. This works on most modern browsers, maybe even on older ones, didn't try.
All the solutions above, are based on the fact that it has to be injected with predefined and well marked SCRIPT tag and rely completely on the HTML implementation. But, what if the script is injected dynamically, or even worse, what if you are write a library, that will be used in a variety of websites?
In these and some other cases, all the above answers are not sufficient and even becoming too complicated.
First, let's try to understand what do we need to achieve here. All we need to do is to get the URL of the script itself, from there it's a piece of cake.
There is actually a nice trick to get the script URL from the script itself. One of the functionalities of the native Error
class, is the ability to provide a stack trace of the "problematic location", including the exact file trace to the last call. In order to achieve this, I will use the stack property of the Error instance, that once created, will give the full stack trace.
Here is how the magic works:
// The pattern to split each row in the stack trace string
const STACK_TRACE_SPLIT_PATTERN = /(?:Error)?\n(?:\s*at\s+)?/;
// For browsers, like Chrome, IE, Edge and more.
const STACK_TRACE_ROW_PATTERN1 = /^.+?\s\((.+?):\d+:\d+\)$/;
// For browsers, like Firefox, Safari, some variants of Chrome and maybe other browsers.
const STACK_TRACE_ROW_PATTERN2 = /^(?:.*?@)?(.*?):\d+(?::\d+)?$/;
const getFileParams = () => {
const stack = new Error().stack;
const row = stack.split(STACK_TRACE_SPLIT_PATTERN, 2)[1];
const [, url] = row.match(STACK_TRACE_ROW_PATTERN1) || row.match(STACK_TRACE_ROW_PATTERN2) || [];
if (!url) {
console.warn("Something went wrong. You should debug it and find out why.");
return;
}
try {
const urlObj = new URL(url);
return urlObj.searchParams; // This feature doesn't exists in IE, in this case you should use urlObj.search and handle the query parsing by yourself.
} catch (e) {
console.warn(`The URL '${url}' is not valid.`);
}
}
Now, in any case of script call, like in the OP case:
<script type="text/javascript" src="file.js?obj1=somevalue&obj2=someothervalue"></script>
In the file.js
script, you can now do:
const params = getFileParams();
console.log(params.get('obj2'));
// Prints: someothervalue
This will also work with RequireJS and other dynamically injected file scripts.
To answer your question, update_attribute
skips pre save "validations" but it still runs any other callbacks like after_save
etc. So if you really want to "just update the column and skip any AR cruft" then you need to use (apparently)
Model.update_all(...)
see https://stackoverflow.com/a/7243777/32453
You can easily determine the file MIME type with JavaScript's FileReader
before uploading it to a server. I agree that we should prefer server-side checking over client-side, but client-side checking is still possible. I'll show you how and provide a working demo at the bottom.
Check that your browser supports both File
and Blob
. All major ones should.
if (window.FileReader && window.Blob) {
// All the File APIs are supported.
} else {
// File and Blob are not supported
}
You can retrieve the File
information from an <input>
element like this (ref):
<input type="file" id="your-files" multiple>
<script>
var control = document.getElementById("your-files");
control.addEventListener("change", function(event) {
// When the control has changed, there are new files
var files = control.files,
for (var i = 0; i < files.length; i++) {
console.log("Filename: " + files[i].name);
console.log("Type: " + files[i].type);
console.log("Size: " + files[i].size + " bytes");
}
}, false);
</script>
Here is a drag-and-drop version of the above (ref):
<div id="your-files"></div>
<script>
var target = document.getElementById("your-files");
target.addEventListener("dragover", function(event) {
event.preventDefault();
}, false);
target.addEventListener("drop", function(event) {
// Cancel default actions
event.preventDefault();
var files = event.dataTransfer.files,
for (var i = 0; i < files.length; i++) {
console.log("Filename: " + files[i].name);
console.log("Type: " + files[i].type);
console.log("Size: " + files[i].size + " bytes");
}
}, false);
</script>
We can now inspect the files and tease out headers and MIME types.
✘ Quick method
You can naïvely ask Blob for the MIME type of whatever file it represents using this pattern:
var blob = files[i]; // See step 1 above
console.log(blob.type);
For images, MIME types come back like the following:
image/jpeg
image/png
...
Caveat: The MIME type is detected from the file extension and can be fooled or spoofed. One can rename a .jpg
to a .png
and the MIME type will be be reported as image/png
.
✓ Proper header-inspecting method
To get the bonafide MIME type of a client-side file we can go a step further and inspect the first few bytes of the given file to compare against so-called magic numbers. Be warned that it's not entirely straightforward because, for instance, JPEG has a few "magic numbers". This is because the format has evolved since 1991. You might get away with checking only the first two bytes, but I prefer checking at least 4 bytes to reduce false positives.
Example file signatures of JPEG (first 4 bytes):
FF D8 FF E0 (SOI + ADD0)
FF D8 FF E1 (SOI + ADD1)
FF D8 FF E2 (SOI + ADD2)
Here is the essential code to retrieve the file header:
var blob = files[i]; // See step 1 above
var fileReader = new FileReader();
fileReader.onloadend = function(e) {
var arr = (new Uint8Array(e.target.result)).subarray(0, 4);
var header = "";
for(var i = 0; i < arr.length; i++) {
header += arr[i].toString(16);
}
console.log(header);
// Check the file signature against known types
};
fileReader.readAsArrayBuffer(blob);
You can then determine the real MIME type like so (more file signatures here and here):
switch (header) {
case "89504e47":
type = "image/png";
break;
case "47494638":
type = "image/gif";
break;
case "ffd8ffe0":
case "ffd8ffe1":
case "ffd8ffe2":
case "ffd8ffe3":
case "ffd8ffe8":
type = "image/jpeg";
break;
default:
type = "unknown"; // Or you can use the blob.type as fallback
break;
}
Accept or reject file uploads as you like based on the MIME types expected.
Here is a working demo for local files and remote files (I had to bypass CORS just for this demo). Open the snippet, run it, and you should see three remote images of different types displayed. At the top you can select a local image or data file, and the file signature and/or MIME type will be displayed.
Notice that even if an image is renamed, its true MIME type can be determined. See below.
Screenshot
// Return the first few bytes of the file as a hex string_x000D_
function getBLOBFileHeader(url, blob, callback) {_x000D_
var fileReader = new FileReader();_x000D_
fileReader.onloadend = function(e) {_x000D_
var arr = (new Uint8Array(e.target.result)).subarray(0, 4);_x000D_
var header = "";_x000D_
for (var i = 0; i < arr.length; i++) {_x000D_
header += arr[i].toString(16);_x000D_
}_x000D_
callback(url, header);_x000D_
};_x000D_
fileReader.readAsArrayBuffer(blob);_x000D_
}_x000D_
_x000D_
function getRemoteFileHeader(url, callback) {_x000D_
var xhr = new XMLHttpRequest();_x000D_
// Bypass CORS for this demo - naughty, Drakes_x000D_
xhr.open('GET', '//cors-anywhere.herokuapp.com/' + url);_x000D_
xhr.responseType = "blob";_x000D_
xhr.onload = function() {_x000D_
callback(url, xhr.response);_x000D_
};_x000D_
xhr.onerror = function() {_x000D_
alert('A network error occurred!');_x000D_
};_x000D_
xhr.send();_x000D_
}_x000D_
_x000D_
function headerCallback(url, headerString) {_x000D_
printHeaderInfo(url, headerString);_x000D_
}_x000D_
_x000D_
function remoteCallback(url, blob) {_x000D_
printImage(blob);_x000D_
getBLOBFileHeader(url, blob, headerCallback);_x000D_
}_x000D_
_x000D_
function printImage(blob) {_x000D_
// Add this image to the document body for proof of GET success_x000D_
var fr = new FileReader();_x000D_
fr.onloadend = function() {_x000D_
$("hr").after($("<img>").attr("src", fr.result))_x000D_
.after($("<div>").text("Blob MIME type: " + blob.type));_x000D_
};_x000D_
fr.readAsDataURL(blob);_x000D_
}_x000D_
_x000D_
// Add more from http://en.wikipedia.org/wiki/List_of_file_signatures_x000D_
function mimeType(headerString) {_x000D_
switch (headerString) {_x000D_
case "89504e47":_x000D_
type = "image/png";_x000D_
break;_x000D_
case "47494638":_x000D_
type = "image/gif";_x000D_
break;_x000D_
case "ffd8ffe0":_x000D_
case "ffd8ffe1":_x000D_
case "ffd8ffe2":_x000D_
type = "image/jpeg";_x000D_
break;_x000D_
default:_x000D_
type = "unknown";_x000D_
break;_x000D_
}_x000D_
return type;_x000D_
}_x000D_
_x000D_
function printHeaderInfo(url, headerString) {_x000D_
$("hr").after($("<div>").text("Real MIME type: " + mimeType(headerString)))_x000D_
.after($("<div>").text("File header: 0x" + headerString))_x000D_
.after($("<div>").text(url));_x000D_
}_x000D_
_x000D_
/* Demo driver code */_x000D_
_x000D_
var imageURLsArray = ["http://media2.giphy.com/media/8KrhxtEsrdhD2/giphy.gif", "http://upload.wikimedia.org/wikipedia/commons/e/e9/Felis_silvestris_silvestris_small_gradual_decrease_of_quality.png", "http://static.giantbomb.com/uploads/scale_small/0/316/520157-apple_logo_dec07.jpg"];_x000D_
_x000D_
// Check for FileReader support_x000D_
if (window.FileReader && window.Blob) {_x000D_
// Load all the remote images from the urls array_x000D_
for (var i = 0; i < imageURLsArray.length; i++) {_x000D_
getRemoteFileHeader(imageURLsArray[i], remoteCallback);_x000D_
}_x000D_
_x000D_
/* Handle local files */_x000D_
$("input").on('change', function(event) {_x000D_
var file = event.target.files[0];_x000D_
if (file.size >= 2 * 1024 * 1024) {_x000D_
alert("File size must be at most 2MB");_x000D_
return;_x000D_
}_x000D_
remoteCallback(escape(file.name), file);_x000D_
});_x000D_
_x000D_
} else {_x000D_
// File and Blob are not supported_x000D_
$("hr").after( $("<div>").text("It seems your browser doesn't support FileReader") );_x000D_
} /* Drakes, 2015 */
_x000D_
img {_x000D_
max-height: 200px_x000D_
}_x000D_
div {_x000D_
height: 26px;_x000D_
font: Arial;_x000D_
font-size: 12pt_x000D_
}_x000D_
form {_x000D_
height: 40px;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>_x000D_
<form>_x000D_
<input type="file" />_x000D_
<div>Choose an image to see its file signature.</div>_x000D_
</form>_x000D_
<hr/>
_x000D_
Check out in here, worked well for me, with no limits in the output size, no omitted elements, even beyond 1000
Following is the DP based solution for Edit Distance problem which is top down. I hope it will also help in understanding the world of Dynamic Programming:
public int minDistance(String word1, String word2) {//Standard dynamic programming puzzle.
int m = word2.length();
int n = word1.length();
if(m == 0) // Cannot miss the corner cases !
return n;
if(n == 0)
return m;
int[][] DP = new int[n + 1][m + 1];
for(int j =1 ; j <= m; j++) {
DP[0][j] = j;
}
for(int i =1 ; i <= n; i++) {
DP[i][0] = i;
}
for(int i =1 ; i <= n; i++) {
for(int j =1 ; j <= m; j++) {
if(word1.charAt(i - 1) == word2.charAt(j - 1))
DP[i][j] = DP[i-1][j-1];
else
DP[i][j] = Math.min(Math.min(DP[i-1][j], DP[i][j-1]), DP[i-1][j-1]) + 1; // Main idea is this.
}
}
return DP[n][m];
}
You can think of its recursive implementation at your home. It's quite good and challenging if you haven't solved something like this before.
not so elegant but you dont need to declare any variable:
for k in (select max(1) from table where 1 = 1) loop
update x where column = value;
end loop;
If you are optimizing your page for IE8 or newer, you should really consider whether you need jquery or not. Modern browsers have many assets natively which jquery provides.
If you care for performance, you can have incredible performance benefits (2-10 faster) using native javascript: http://jsperf.com/jquery-vs-native-selector-and-element-style/2
I transformed a div-tagcloud from jquery to native javascript (IE8+ compatible), the results are impressive. 4 times faster with just a little overhead.
Number of lines Execution Time
Jquery version : 340 155ms
Native version : 370 27ms
You Might Not Need Jquery provides a really nice overview, which native methods replace for which browser version.
http://youmightnotneedjquery.com/
Appendix: Further speed comparisons how native methods compete to jquery
If your looking for something a little more native, you can use getGnuWin32 to install all of the unix command line tools that have been ported. That plus winBash gives you most of a working unix environment. Add console2 for a better terminal emulator and you almost can't tell your on windows!
Cygwin is a better toolkit overall, but I have found myself running into suprise problems because of the divide between it and windows. None of these solutions are as good as a native linux system though.
You may want to look into using virtualbox to create a linux VM with your distro of choice. Set it up to share a folder with the host os, and you can use a true linux development environment, and share with windows. Just watch out for those EOL markers, they get ya every time.
String.Format
adds many options in addition to the concatenation operators, including the ability to specify the specific format of each item added into the string.
For details on what is possible, I'd recommend reading the section on MSDN titled Composite Formatting. It explains the advantage of String.Format
(as well as xxx.WriteLine
and other methods that support composite formatting) over normal concatenation operators.
You could use JavaScript and XMLHTTPRequest (AJAX) to perform a POST without using a form. Check this link out. Keep in mind that you will need JavaScript enabled in your browser though.
use following method to convert bitmap to byte array:
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 100, byteArrayOutputStream);
byte[] byteArray = byteArrayOutputStream .toByteArray();
to encode base64 from byte array use following method
String encoded = Base64.encodeToString(byteArray, Base64.DEFAULT);
@ECHO OFF
:: %HOMEDRIVE% = C:
:: %HOMEPATH% = \Users\Ruben
:: %system32% ??
:: No spaces in paths
:: Program Files > ProgramFiles
:: cls = clear screen
:: CMD reads the system environment variables when it starts. To re-read those variables you need to restart CMD
:: Use console 2 http://sourceforge.net/projects/console/
:: Assign all Path variables
SET PHP="%HOMEDRIVE%\wamp\bin\php\php5.4.16"
SET SYSTEM32=";%HOMEDRIVE%\Windows\System32"
SET ANT=";%HOMEDRIVE%%HOMEPATH%\Downloads\apache-ant-1.9.0-bin\apache-ant-1.9.0\bin"
SET GRADLE=";%HOMEDRIVE%\tools\gradle-1.6\bin;"
SET ADT=";%HOMEDRIVE%\tools\adt-bundle-windows-x86-20130219\eclipse\jre\bin"
SET ADTTOOLS=";%HOMEDRIVE%\tools\adt-bundle-windows-x86-20130219\sdk\tools"
SET ADTP=";%HOMEDRIVE%\tools\adt-bundle-windows-x86-20130219\sdk\platform-tools"
SET YII=";%HOMEDRIVE%\wamp\www\yii\framework"
SET NODEJS=";%HOMEDRIVE%\ProgramFiles\nodejs"
SET CURL=";%HOMEDRIVE%\tools\curl_734_0_ssl"
SET COMPOSER=";%HOMEDRIVE%\ProgramData\ComposerSetup\bin"
SET GIT=";%HOMEDRIVE%\Program Files\Git\cmd"
:: Set Path variable
setx PATH "%PHP%%SYSTEM32%%NODEJS%%COMPOSER%%YII%%GIT%" /m
:: Set Java variable
setx JAVA_HOME "%HOMEDRIVE%\ProgramFiles\Java\jdk1.7.0_21" /m
PAUSE
If you want to avoid inline script, you can simply listen for a click event on the radio. This can be achieved with plain Javascript by listening to a click event on
for (var radioCounter = 0 ; radioCounter < document.getElementsByName('myRadios').length; radioCounter++) {
document.getElementsByName('myRadios')[radioCounter].onclick = function() {
//VALUE OF THE CLICKED RADIO ELEMENT
console.log('this : ',this.value);
}
}
You can filter by multiple columns (more than two) by using the np.logical_and
operator to replace &
(or np.logical_or
to replace |
)
Here's an example function that does the job, if you provide target values for multiple fields. You can adapt it for different types of filtering and whatnot:
def filter_df(df, filter_values):
"""Filter df by matching targets for multiple columns.
Args:
df (pd.DataFrame): dataframe
filter_values (None or dict): Dictionary of the form:
`{<field>: <target_values_list>}`
used to filter columns data.
"""
import numpy as np
if filter_values is None or not filter_values:
return df
return df[
np.logical_and.reduce([
df[column].isin(target_values)
for column, target_values in filter_values.items()
])
]
Usage:
df = pd.DataFrame({'a': [1, 2, 3, 4], 'b': [1, 2, 3, 4]})
filter_df(df, {
'a': [1, 2, 3],
'b': [1, 2, 4]
})
You don't have to add any extra javascript to what's already included with bootstraps collapse option. Instead simply include data-toggle and data-target selectors on your menu list items just as you do with your navbar-toggle button. So for your Products menu item it would look like this
<li><a href="#Products" data-toggle="collapse" data-target=".navbar-collapse">Products</a></li>
Then you would need to repeat the data-toggle and data-target selectors for each menu item
EDIT!!! In order to fix overflow issues and flickering on this fix I'm adding some more code that will fix this and still not have any extra javascript. Here is the new code:
<li><a href="#products" class="hidden-xs">Products</a></li>
<li><a href="#products" class="visible-xs" data-toggle="collapse" data-target=".navbar-collapse">Products</a></li>
Here it is at work http://jsfiddle.net/jaketaylor/84mqazgq/
This will make your toggle and target selectors specific to screen size and eliminate glitches on the larger menu. If anyone is still having issues with glitches please let me know and I'll find a fix. Thanks
EDIT: In the bootstrap v4.1.3 I couldnt use visible/hidden classes. Instead of hidden-xs
use d-none d-sm-block
and instead of visible-xs
use d-block d-sm-none
.
If you want this environment variable available to all users and on system start then you can add the following to /etc/profile.d/java.sh (create it if necessary):
export JDK_HOME=/usr/lib/jvm/java-7-oracle
export JAVA_HOME=/usr/lib/jvm/java-7-oracle
Then in a terminal run:
sudo chmod +x /etc/profile.d/java.sh
source /etc/profile.d/java.sh
My second question is - should it point to java-6-sun or java-6-sun-1.6.0.24 ?
It should always point to java-7-oracle
as that symlinks to the latest installed one (assuming you installed Java from the Ubuntu repositories and now from the download available at oracle.com).
You could try:
$(this).closest(".column").prev().find(".inputQty").val();
CPython (the classic and prevalent implementation of Python) can't have more than one thread executing Python bytecode at the same time. This means compute-bound programs will only use one core. I/O operations and computing happening inside C extensions (such as numpy) can operate simultaneously.
Other implementation of Python (such as Jython or PyPy) may behave differently, I'm less clear on their details.
The usual recommendation is to use many processes rather than many threads.
ISO 8601-esque datestrings, as excellent as the standard is, are still not widely supported.
This is a great resource to figure out which datestring format you should use:
http://dygraphs.com/date-formats.html
Yes, that means that your datestring could be as simple as as opposed to
"2014/10/13 23:57:52"
instead of
"2014-10-13 23:57:52"
One option is to put the subquery in a LEFT JOIN
:
select sum ( t.graduates ) - t1.summedGraduates
from table as t
left join
(
select sum ( graduates ) summedGraduates, id
from table
where group_code not in ('total', 'others' )
group by id
) t1 on t.id = t1.id
where t.group_code = 'total'
group by t1.summedGraduates
Perhaps a better option would be to use SUM
with CASE
:
select sum(case when group_code = 'total' then graduates end) -
sum(case when group_code not in ('total','others') then graduates end)
from yourtable
Use toString
when you need to display the name to the user.
Use name
when you need the name for your program itself, e.g. to identify and differentiate between different enum values.
Use pm2 to start and run your nodejs processes on windows.
Be sure to read this github discussion of how to set up task scheduler to start pm2: https://github.com/Unitech/pm2/issues/1079
You can use the -quit
option of find
:
find <dir> -maxdepth 1 -type d -name '*foo*' -print -quit
You can change that default behavior in your .gitconfig
, for example:
[push]
default = current
To check the current settings, run:
git config --global --get push.default
You might want to look at Quick-R, which has a lot of nice little tutorials on how you can do basic statistics in R. For example on correlations:
In order to check if your variable is something you could go like:
s='Hello World'
if isinstance(s,str):
#do something here,
The output of isistance will give you a boolean True or False value so you can adjust accordingly. You can check the expected acronym of your value by initially using: type(s) This will return you type 'str' so you can use it in the isistance function.
By default, every Object in Java has the toString()
method which outputs the ObjectType@HashCode.
If you want more meaningfull information then you need to override the toString()
method in your class.
public class Person {
private String name;
// constructor and getter/setter omitted
// overridding toString() to print name
public String toString(){
return name;
}
}
Now when you print the person object using System.out.prtinln(personObj);
it will print the name of the person instead of the classname and hashcode.
In your second case when you are trying to print the array, it prints [Lcom.foo.Person;@28a418fc
the Array type and it's hashcode.
If you want to print the person names, there are many ways.
You could write your own function that iterates each person and prints
void printPersonArray(Person[] persons){
for(Person person: persons){
System.out.println(person);
}
}
You could print it using Arrays.toString(). This seems the simplest to me.
System.out.println(Arrays.toString(persons));
System.out.println(Arrays.deepToString(persons)); // for nested arrays
You could print it the java 8 way (using streams and method reference).
Arrays.stream(persons).forEach(System.out::println);
There might be other ways as well. Hope this helps. :)
I guess GameObject
is a reference type. Default for reference types is null =>
you have an array of nulls.
You need to initialize each member of the array separatedly.
houses[0] = new GameObject(..);
Only then can you access the object without compilation errors.
So you can explicitly initalize the array:
for (int i = 0; i < houses.Length; i++)
{
houses[i] = new GameObject();
}
or you can change GameObject
to value type.
I have searched for a solution that will visualize process steps in my web application. I have found the following excellent write-up by Stephen A Thomas:
Tracking Progress in Pure CSS (Original Link now dead)
In his approach Thomas even gets away with just using CSS - no Javascript! In an essence the following CSS code from his article does the trick for me:
<style>
<!-- Progress with steps -->
ol.progtrckr {
margin: 0;
padding: 0;
list-style-type: none;
}
ol.progtrckr li {
display: inline-block;
text-align: center;
line-height: 3em;
}
ol.progtrckr[data-progtrckr-steps="2"] li { width: 49%; }
ol.progtrckr[data-progtrckr-steps="3"] li { width: 33%; }
ol.progtrckr[data-progtrckr-steps="4"] li { width: 24%; }
ol.progtrckr[data-progtrckr-steps="5"] li { width: 19%; }
ol.progtrckr[data-progtrckr-steps="6"] li { width: 16%; }
ol.progtrckr[data-progtrckr-steps="7"] li { width: 14%; }
ol.progtrckr[data-progtrckr-steps="8"] li { width: 12%; }
ol.progtrckr[data-progtrckr-steps="9"] li { width: 11%; }
ol.progtrckr li.progtrckr-done {
color: black;
border-bottom: 4px solid yellowgreen;
}
ol.progtrckr li.progtrckr-todo {
color: silver;
border-bottom: 4px solid silver;
}
ol.progtrckr li:after {
content: "\00a0\00a0";
}
ol.progtrckr li:before {
position: relative;
bottom: -2.5em;
float: left;
left: 50%;
line-height: 1em;
}
ol.progtrckr li.progtrckr-done:before {
content: "\2713";
color: white;
background-color: yellowgreen;
height: 1.2em;
width: 1.2em;
line-height: 1.2em;
border: none;
border-radius: 1.2em;
}
ol.progtrckr li.progtrckr-todo:before {
content: "\039F";
color: silver;
background-color: white;
font-size: 1.5em;
bottom: -1.6em;
}
</style>
As well as HTML tags from his example (I use Grails GSP pages to generate tags and 'done/todo' class dynamically):
<ol class="progtrckr" data-progtrckr-steps="5">
<li class="progtrckr-done">Order Processing</li>
<li class="progtrckr-done">Pre-Production</li>
<li class="progtrckr-done">In Production</li>
<li class="progtrckr-done">Shipped</li>
<li class="progtrckr-todo">Delivered</li>
</ol>
Hope it helps. Works pretty well for me.
UPDATE: The following (shortened) version also works well.
ol.progtrckr {
display: table;
list-style-type: none;
margin: 0;
padding: 0;
table-layout: fixed;
width: 100%;
}
ol.progtrckr li {
display: table-cell;
text-align: center;
line-height: 3em;
}
... and the rest of the CSS ...
<ol class="progtrckr">
...
</ol>
display: table; table-layout: fixed; width: 100%
ensure that the list items are automatically sized equally as long as the content does not overflow. There is no need to use data-progtrckr-steps
and its associated CSS.
Make sure you read SilverlightFox's answer. It highlights a more important reason.
The reason is mostly that if you know the source of a request you may want to customize it a little bit.
For instance lets say you have a website which has many recipes. And you use a custom jQuery framework to slide recipes into a container based on a link they click.
The link may be www.example.com/recipe/apple_pie
Now normally that returns a full page, header, footer, recipe content and ads. But if someone is browsing your website some of those parts are already loaded. So you can use an AJAX to get the recipe the user has selected but to save time and bandwidth don't load the header/footer/ads.
Now you can just write a secondary endpoint for the data like www.example.com/recipe_only/apple_pie
but that's harder to maintain and share to other people.
But it's easier to just detect that it is an ajax request making the request and then returning only a part of the data. That way the user wastes less bandwidth and the site appears more responsive.
The frameworks just add the header because some may find it useful to keep track of which requests are ajax and which are not. But it's entirely dependent on the developer to use such techniques.
It's actually kind of similar to the Accept-Language
header. A browser can request a website please show me a Russian version of this website without having to insert /ru/ or similar in the URL.
You could try this code:
private float GetBrightestColor(float r, float g, float b) {
if (r > g && r > b) {
return r;
} else if (g > r && g > b) {
return g;
} else if (b > r && b > g) {
return b;
}
}
You can always do this:
jQuery.fn.extend({
myfunction: function(param){
// code here
},
});
OR
jQuery.extend({
myfunction: function(param){
// code here
},
});
$(element).myfunction(param);
Inner join - An inner join using either of the equivalent queries gives the intersection of the two tables, i.e. the two rows they have in common.
Left outer join -
A left outer join will give all rows in A, plus any common rows in B.
Full outer join -
A full outer join will give you the union of A and B, i.e. All the rows in A and all the rows in B. If something in A doesn't have a corresponding datum in B, then the B portion is null, and vice versa.
check this
You don't need the 'values' clause when using a 'select' as your source.
insert into table1 (col1, col2)
select t1.col1, t2.col2 from oldtable1 t1, oldtable2 t2;
You need a bindingsource object to act as an intermediary and assist in the binding. Then instead of updating the user interface, update the underlining model.
var model = (Fruit) bindingSource1.DataSource;
model.FruitType = "oranges";
bindingSource.ResetBindings();
Read up on BindingSource and simple data binding for Windows Forms.
this will replace multiple tabs with a single tab
preg_replace("/\s{2,}/", "\t", $string);
Just like you can password protect workbooks and worksheets, you can password protect a macro in Excel from being viewed (and executed).
Place a command button on your worksheet and add the following code lines:
First, create a simple macro that you want to protect.
Range("A1").Value = "This is secret code"
Next, click Tools, Then VBAProject Properties...
Click Tools, VBAProject Properties...
Enter a Password Twice
Click OK.
Save, close and reopen the Excel file. Try to view the code.
The following dialog box will appear:
Password Protected from being Viewed
You can still execute the code by clicking on the command button but you cannot view or edit the code anymore (unless you know the password). The password for the downloadable Excel file is "easy".
Dim password As Variant password = Application.InputBox("Enter Password", "Password Protected") Select Case password Case Is = False 'do nothing Case Is = "easy" Range("A1").Value = "This is secret code" Case Else MsgBox "Incorrect Password" End Select
Result when you click the command button on the sheet:
Password Protected from being Executed
Explanation: The macro uses the InputBox method of the Application object. If the users clicks Cancel, this method returns False and nothing happens (InputBox disappears). Only when the user knows the password ("easy" again), the secret code will be executed. If the entered password is incorrect, a MsgBox is displayed. Note that the user cannot take a look at the password in the Visual Basic Editor because the project is protected from being viewed
select[value="value"]{
background-color: red;
padding: 3px;
font-weight:bold;
}
You don't necessarily need Ajax for this. Just an <a>
link is enough if you set the content-disposition
to attachment
in the server side code. This way the parent page will just stay open, if that was your major concern (why would you unnecessarily have chosen Ajax for this otherwise?). Besides, there is no way to handle this nicely acynchronously. PDF is not character data. It's binary data. You can't do stuff like $(element).load()
. You want to use completely new request for this. For that <a href="pdfservlet/filename.pdf">pdf</a>
is perfectly suitable.
To assist you more with the server side code, you'll need to tell more about the language used and post an excerpt of the code attempts.
pDialog = new ProgressDialog(this);
// Set progressbar message
pDialog.setMessage("Buffering...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
// Show progressbar
pDialog.show();
try {
// Start the MediaController
MediaController mediacontroller = new MediaController(this);
mediacontroller.setAnchorView(mVideoView);
Uri videoUri = Uri.parse(videoUrl);
mVideoView.setMediaController(mediacontroller);
mVideoView.setVideoURI(videoUri);
} catch (Exception e) {
e.printStackTrace();
}
mVideoView.requestFocus();
mVideoView.setOnPreparedListener(new OnPreparedListener() {
// Close the progress bar and play the video
public void onPrepared(MediaPlayer mp) {
pDialog.dismiss();
mVideoView.start();
}
});
mVideoView.setOnCompletionListener(new OnCompletionListener() {
public void onCompletion(MediaPlayer mp) {
if (pDialog.isShowing()) {
pDialog.dismiss();
}
finish();
}
});
If you are using jQuery in your project, or are willing to include it you can call nth-last-child
through its selector API (this is this simulated it will cross browser). Here is a link to an nth-last-child
plugin. If you took this method of targeting the elements you were interested in:
$('ul li:nth-last-child(1)').addClass('last');
And then style again the last
class instead of the nth-child
or nth-last-child
pseudo selectors, you will have a much more consistent cross browser experience.
You can use StringFormat in Silverlight 4 to provide a custom formatting of the value you bind to.
The date formatting has a huge range of options.
For the DateTime of “April 17, 2004, 1:52:45 PM”
You can either use a set of standard formats (standard formats)…
StringFormat=f : “Saturday, April 17, 2004 1:52 PM”
StringFormat=g : “4/17/2004 1:52 PM”
StringFormat=m : “April 17”
StringFormat=y : “April, 2004”
StringFormat=t : “1:52 PM”
StringFormat=u : “2004-04-17 13:52:45Z”
StringFormat=o : “2004-04-17T13:52:45.0000000”
… or you can create your own date formatting using letters (custom formats)
StringFormat=’MM/dd/yy’ : “04/17/04”
StringFormat=’MMMM dd, yyyy g’ : “April 17, 2004 A.D.”
StringFormat=’hh:mm:ss.fff tt’ : “01:52:45.000 PM”
There is no need to involve any image classes, you can simply call WebClient.DownloadFile
:
string localFilename = @"c:\localpath\tofile.jpg";
using(WebClient client = new WebClient())
{
client.DownloadFile("http://www.example.com/image.jpg", localFilename);
}
Update
Since you will want to check whether the file exists and download the file if it does, it's better to do this within the same request. So here is a method that will do that:
private static void DownloadRemoteImageFile(string uri, string fileName)
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri);
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
// Check that the remote file was found. The ContentType
// check is performed since a request for a non-existent
// image file might be redirected to a 404-page, which would
// yield the StatusCode "OK", even though the image was not
// found.
if ((response.StatusCode == HttpStatusCode.OK ||
response.StatusCode == HttpStatusCode.Moved ||
response.StatusCode == HttpStatusCode.Redirect) &&
response.ContentType.StartsWith("image",StringComparison.OrdinalIgnoreCase))
{
// if the remote file was found, download oit
using (Stream inputStream = response.GetResponseStream())
using (Stream outputStream = File.OpenWrite(fileName))
{
byte[] buffer = new byte[4096];
int bytesRead;
do
{
bytesRead = inputStream.Read(buffer, 0, buffer.Length);
outputStream.Write(buffer, 0, bytesRead);
} while (bytesRead != 0);
}
}
}
In brief, it makes a request for the file, verifies that the response code is one of OK
, Moved
or Redirect
and also that the ContentType
is an image. If those conditions are true, the file is downloaded.
On mac OS X Yosemite, after installing it with brew it put it into
/usr/local/opt/openssl/bin/openssl
But kept getting an error "Linking keg-only openssl means you may end up linking against the insecure" when trying to link it
So I just linked it by supplying the full path like so
ln -s /usr/local/opt/openssl/bin/openssl /usr/local/bin/openssl
Now it's showing version OpenSSL 1.0.2o when I do "openssl version -a", I'm assuming it worked
A somewhat better solution:
atexit([] { system("PAUSE"); });
at the beginning of your program.
Pros:
cin.sync(); cin.ignore();
trick instead of system("pause");
)Cons:
extern "C" int __stdcall IsDebuggerPresent(void);
int main(int argc, char** argv) {
if (IsDebuggerPresent())
atexit([] {system("PAUSE"); });
...
}
Let say you have string contains anchor tag and you want to remove this tag with content then this method will helpful.
$srting = '<a title="" href="/index.html"><b>Some Text</b></a>
Lorem Ipsum is simply dummy text of the printing and typesetting industry.';
echo strip_tags_content($srting);
function strip_tags_content($text) {
return preg_replace('@<(\w+)\b.*?>.*?</\1>@si', '', $text);
}
Output:
Lorem Ipsum is simply dummy text of the printing and typesetting industry.
As King King said, you must add the browser specific prefix. This should cover most browsers:
@keyframes flickerAnimation {_x000D_
0% { opacity:1; }_x000D_
50% { opacity:0; }_x000D_
100% { opacity:1; }_x000D_
}_x000D_
@-o-keyframes flickerAnimation{_x000D_
0% { opacity:1; }_x000D_
50% { opacity:0; }_x000D_
100% { opacity:1; }_x000D_
}_x000D_
@-moz-keyframes flickerAnimation{_x000D_
0% { opacity:1; }_x000D_
50% { opacity:0; }_x000D_
100% { opacity:1; }_x000D_
}_x000D_
@-webkit-keyframes flickerAnimation{_x000D_
0% { opacity:1; }_x000D_
50% { opacity:0; }_x000D_
100% { opacity:1; }_x000D_
}_x000D_
.animate-flicker {_x000D_
-webkit-animation: flickerAnimation 1s infinite;_x000D_
-moz-animation: flickerAnimation 1s infinite;_x000D_
-o-animation: flickerAnimation 1s infinite;_x000D_
animation: flickerAnimation 1s infinite;_x000D_
}
_x000D_
<div class="animate-flicker">Loading...</div>
_x000D_
To follow up on the comment by suhendri to Rory McCrossan answer. Here is an Action delegate example:
In child add:
public Action UpdateProgress; // In place of event handler declaration
// declare an Action delegate
.
.
.
private LoadData() {
this.UpdateProgress(); // call to Action delegate - MyMethod in
// parent
}
In parent add:
// The 3 lines in the parent becomes:
ChildClass child = new ChildClass();
child.UpdateProgress = this.MyMethod; // assigns MyMethod to child delegate
Seems that you need classmethod:
class World(object):
allAirports = []
@classmethod
def initialize(cls):
if not cls.allAirports:
f = open(os.path.expanduser("~/Desktop/1000airports.csv"))
file_reader = csv.reader(f)
for col in file_reader:
cls.allAirports.append(Airport(col[0],col[2],col[3]))
return cls.allAirports
Using PyParsing
import pyparsing as pp
word = pp.Word(pp.alphanums)
s = 'gfgfdAAA1234ZZZuijjk'
rule = pp.nestedExpr('AAA', 'ZZZ')
for match in rule.searchString(s):
print(match)
which yields:
[['1234']]
This works for me permanently:
[Environment]::SetEnvironmentVariable("Path", "$env:Path;C:\Python27","User")
Can't you just refer to the _body
object directly? Apparently it doesn't return any errors if used this way.
this.http.get('https://thecatapi.com/api/images/get?format=html&results_per_page=10')
.map(res => res)
.subscribe(res => {
this.data = res._body;
});
You can convert yourInt
to bytes by using a ByteBuffer
like this:
return ByteBuffer.allocate(4).putInt(yourInt).array();
Beware that you might have to think about the byte order when doing so.
The first case (export default {...}
) is ES2015 syntax for making some object definition available for use.
The second case (new Vue (...)
) is standard syntax for instantiating an object that has been defined.
The first will be used in JS to bootstrap Vue, while either can be used to build up components and templates.
See https://vuejs.org/v2/guide/components-registration.html for more details.
This has been asked many times. A possible solution can be found here: https://stackoverflow.com/a/6527838/552671
This solution requires both an UPDATE
and INSERT
.
UPDATE table SET field='C', field2='Z' WHERE id=3;
INSERT INTO table (id, field, field2)
SELECT 3, 'C', 'Z'
WHERE NOT EXISTS (SELECT 1 FROM table WHERE id=3);
With Postgres 9.1 it is possible to do it with one query: https://stackoverflow.com/a/1109198/2873507
Honestly the easiest way was to add file hosting to the server.
Open IIS
Add a Virtual Directory under Default Web Site
Add the appropriate permissions to the folder on the C: drive for "NETWORK SERVICE" and "IIS AppPool\DefaultAppPool"
Refresh Default Web Site
And you're done. You can now browse to any image in that folder by navigating to http://yourServerName/whateverYourFolderNameIs/yourImage.jpg and use that url in your img src
Hope this helps someone
Because the dot is inside character class (square brackets []
).
Take a look at http://www.regular-expressions.info/reference.html, it says (under char class section):
Any character except ^-]\ add that character to the possible matches for the character class.
After generation of woff files, you have to define font-family, which can be used later in all your css styles. Below is the code to define font families (for normal, bold, bold-italic, italic) typefaces. It is assumed, that there are 4 *.woff files (for mentioned typefaces), placed in fonts
subdirectory.
In CSS code:
@font-face {
font-family: "myfont";
src: url("fonts/awesome-font.woff") format('woff');
}
@font-face {
font-family: "myfont";
src: url("fonts/awesome-font-bold.woff") format('woff');
font-weight: bold;
}
@font-face {
font-family: "myfont";
src: url("fonts/awesome-font-boldoblique.woff") format('woff');
font-weight: bold;
font-style: italic;
}
@font-face {
font-family: "myfont";
src: url("fonts/awesome-font-oblique.woff") format('woff');
font-style: italic;
}
After having that definitions, you can just write, for example,
In HTML code:
<div class="mydiv">
<b>this will be written with awesome-font-bold.woff</b>
<br/>
<b><i>this will be written with awesome-font-boldoblique.woff</i></b>
<br/>
<i>this will be written with awesome-font-oblique.woff</i>
<br/>
this will be written with awesome-font.woff
</div>
In CSS code:
.mydiv {
font-family: myfont
}
The good tool for generation woff files, which can be included in CSS stylesheets is located here. Not all woff files work correctly under latest Firefox versions, and this generator produces 'correct' fonts.
After 10 years :) . Without list comprehension
Return a single row of values from a select query like below.
"select name,userid, address from table1 where userid = 1"
json
output
{ name : "name1", userid : 1, address : "adress1, street1" }
Code
cur.execute(f"select name,userid, address from table1 where userid = 1 ")
row = cur.fetchone()
desc = list(zip(*cur.description))[0] #To get column names
rowdict = dict(zip(desc,row))
jsondict = jsonify(rowdict) #Flask jsonify
cur.description
is a tuple of tuples as below. unzip
and zip
to combine column name with values
(('name', None, None, None, None, None, None), ('userid', None, None, None, None, None, None), ('address', None, None, None, None, None, None))
Set the activity content from a layout resource. The resource will be inflated, adding all top-level views to the activity.
It is cumbersome to interoperate socket.io and connect sessions support. The problem is not because socket.io "hijacks" request somehow, but because certain socket.io transports (I think flashsockets) don't support cookies. I could be wrong with cookies, but my approach is the following:
One can use base python for this. The code needs a function to flatten lists of lists:
def flatten(B): # function needed for code below;
A = []
for i in B:
if type(i) == list: A.extend(i)
else: A.append(i)
return A
Then one can run:
L = [[1,2,3],[4,5,6],[7,8,9,10]]
outlist =[]; templist =[[]]
for sublist in L:
outlist = templist; templist = [[]]
for sitem in sublist:
for oitem in outlist:
newitem = [oitem]
if newitem == [[]]: newitem = [sitem]
else: newitem = [newitem[0], sitem]
templist.append(flatten(newitem))
outlist = list(filter(lambda x: len(x)==len(L), templist)) # remove some partial lists that also creep in;
print(outlist)
Output:
[[1, 4, 7], [2, 4, 7], [3, 4, 7],
[1, 5, 7], [2, 5, 7], [3, 5, 7],
[1, 6, 7], [2, 6, 7], [3, 6, 7],
[1, 4, 8], [2, 4, 8], [3, 4, 8],
[1, 5, 8], [2, 5, 8], [3, 5, 8],
[1, 6, 8], [2, 6, 8], [3, 6, 8],
[1, 4, 9], [2, 4, 9], [3, 4, 9],
[1, 5, 9], [2, 5, 9], [3, 5, 9],
[1, 6, 9], [2, 6, 9], [3, 6, 9],
[1, 4, 10], [2, 4, 10], [3, 4, 10],
[1, 5, 10], [2, 5, 10], [3, 5, 10],
[1, 6, 10], [2, 6, 10], [3, 6, 10]]
You can check in all the below ways for a List
List<string> FilteredList = new List<string>();
//Comparing the two lists and gettings common elements.
FilteredList = a1.Intersect(a2, StringComparer.OrdinalIgnoreCase);
In your view:
{% if user.is_authenticated %}
<p>{{ user }}</p>
{% endif %}
In you controller functions add decorator:
from django.contrib.auth.decorators import login_required
@login_required
def privateFunction(request):
The other solutions that use the GLOBAL keyword are a nightmare to maintain/readability (+namespace pollution and bugs) when the project gets bigger. I've seen this mistake many times and had the hassle of fixing it.
Use a JavaScript file and then use module exports.
Example:
var Globals = {
'domain':'www.MrGlobal.com';
}
module.exports = Globals;
Then if you want to use these, use require.
var globals = require('globals'); // << globals.js path
globals.domain // << Domain.
I encountered this problem while developing on my local workstation.
After several unsuccessful iisreset
invocations, I remedied this situation by rebooting my machine.
In retrospect, an open file handle may have been causing issues.
Use inet_ntop()
and inet_pton()
if you need it other way around. Do not use inet_ntoa(), inet_aton()
and similar as they are deprecated and don't support ipv6.
Here is a nice guide with quite a few examples.
// IPv4 demo of inet_ntop() and inet_pton()
struct sockaddr_in sa;
char str[INET_ADDRSTRLEN];
// store this IP address in sa:
inet_pton(AF_INET, "192.0.2.33", &(sa.sin_addr));
// now get it back and print it
inet_ntop(AF_INET, &(sa.sin_addr), str, INET_ADDRSTRLEN);
printf("%s\n", str); // prints "192.0.2.33"
Here's a function that uses .NET's System.IO
classes directly:
function GetLineAt([String] $path, [Int32] $index)
{
[System.IO.FileMode] $mode = [System.IO.FileMode]::Open;
[System.IO.FileAccess] $access = [System.IO.FileAccess]::Read;
[System.IO.FileShare] $share = [System.IO.FileShare]::Read;
[Int32] $bufferSize = 16 * 1024;
[System.IO.FileOptions] $options = [System.IO.FileOptions]::SequentialScan;
[System.Text.Encoding] $defaultEncoding = [System.Text.Encoding]::UTF8;
# FileStream(String, FileMode, FileAccess, FileShare, Int32, FileOptions) constructor
# http://msdn.microsoft.com/library/d0y914c5.aspx
[System.IO.FileStream] $input = New-Object `
-TypeName 'System.IO.FileStream' `
-ArgumentList ($path, $mode, $access, $share, $bufferSize, $options);
# StreamReader(Stream, Encoding, Boolean, Int32) constructor
# http://msdn.microsoft.com/library/ms143458.aspx
[System.IO.StreamReader] $reader = New-Object `
-TypeName 'System.IO.StreamReader' `
-ArgumentList ($input, $defaultEncoding, $true, $bufferSize);
[String] $line = $null;
[Int32] $currentIndex = 0;
try
{
while (($line = $reader.ReadLine()) -ne $null)
{
if ($currentIndex++ -eq $index)
{
return $line;
}
}
}
finally
{
# Close $reader and $input
$reader.Close();
}
# There are less than ($index + 1) lines in the file
return $null;
}
GetLineAt 'file.txt' 9;
Tweaking the $bufferSize
variable might affect performance. A more concise version that uses default buffer sizes and doesn't provide optimization hints could look like this:
function GetLineAt([String] $path, [Int32] $index)
{
# StreamReader(String, Boolean) constructor
# http://msdn.microsoft.com/library/9y86s1a9.aspx
[System.IO.StreamReader] $reader = New-Object `
-TypeName 'System.IO.StreamReader' `
-ArgumentList ($path, $true);
[String] $line = $null;
[Int32] $currentIndex = 0;
try
{
while (($line = $reader.ReadLine()) -ne $null)
{
if ($currentIndex++ -eq $index)
{
return $line;
}
}
}
finally
{
$reader.Close();
}
# There are less than ($index + 1) lines in the file
return $null;
}
GetLineAt 'file.txt' 9;
This can be done in this way too
string actualString = "1111222233334444";
var listResult = new List<string>();
int groupingLength = actualString.Length % 4;
if (groupingLength > 0)
listResult.Add(actualString.Substring(0, groupingLength));
for (int i = groupingLength; i < actualString.Length; i += 4)
{
listResult.Add(actualString.Substring(i, 4));
}
foreach(var res in listResult)
{
Console.WriteLine(res);
}
Console.Read();
If you cannot use std::to_string
from C++11, you can write it as it is defined on cppreference.com:
std::string to_string( int value )
Converts a signed decimal integer to a string with the same content as whatstd::sprintf(buf, "%d", value)
would produce for sufficiently large buf.
Implementation
#include <cstdio>
#include <string>
#include <cassert>
std::string to_string( int x ) {
int length = snprintf( NULL, 0, "%d", x );
assert( length >= 0 );
char* buf = new char[length + 1];
snprintf( buf, length + 1, "%d", x );
std::string str( buf );
delete[] buf;
return str;
}
You can do more with it. Just use "%g"
to convert float or double to string, use "%x"
to convert int to hex representation, and so on.
There is a node.js library called named-regexp that you could use in your node.js projects (on in the browser by packaging the library with browserify or other packaging scripts). However, the library cannot be used with regular expressions that contain non-named capturing groups.
If you count the opening capturing braces in your regular expression you can create a mapping between named capturing groups and the numbered capturing groups in your regex and can mix and match freely. You just have to remove the group names before using the regex. I've written three functions that demonstrate that. See this gist: https://gist.github.com/gbirke/2cc2370135b665eee3ef
What kind of document library information do you want in the view? How do you want the user to filter the view?
In general the most powerful way of creating views in sharepoint is with the data view web part. http://office.microsoft.com/en-us/sharepointdesigner/HA100948041033.aspx
You will need Microsoft Office SharePoint Designer.
You can present different views of you folders using the data view filter and sorting controls.
You can use web part connections to filter a dataview. You can use any datasource linked to say a drop down to filter a dataview. How to tie a dropdown list to a gridview in Sharepoint 2007?
To expand on Bartho Bernsmann's answer, I should like to add that one can have a universal, future-proof implementation at the expense of a little reflection:
static void AllowAllSecurityPrototols()
{ int i, n;
Array types;
SecurityProtocolType combined;
types = Enum.GetValues( typeof( SecurityProtocolType ) );
combined = ( SecurityProtocolType )types.GetValue( 0 );
n = types.Length;
for( i = 1; i < n; i += 1 )
{ combined |= ( SecurityProtocolType )types.GetValue( i ); }
ServicePointManager.SecurityProtocol = combined;
}
I invoke this method in the static constructor of the class that accesses the internet.
One alternative - and more lightweight approach to your problem - might be, just editing the array temporarily and then assigning the whole array back to your variable. Because as Vue does not watch individual items it will watch the whole variable being updated.
So you this should work as well:
var tempArray[];
tempArray = this.items;
tempArray[targetPosition] = value;
this.items = tempArray;
This then should also update your DOM.
Just you need to desc with asc. Write the query like below. It will return the values in ascending order.
SELECT * FROM table GROUP BY m_id ORDER BY m_id asc;
You can provide a file-like object to the stdin
argument of subprocess.call()
.
The documentation for the Popen
object applies here.
To capture the output, you should instead use subprocess.check_output()
, which takes similar arguments. From the documentation:
>>> subprocess.check_output(
... "ls non_existent_file; exit 0",
... stderr=subprocess.STDOUT,
... shell=True)
'ls: non_existent_file: No such file or directory\n'
Just do svn up into command line or if you are in windows select the svn update option.
After you change PATH
with the GUI, close and re-open the console window.
This works because only programs started after the change will see the new PATH
.
Execute this command in the command window you have open:
set PATH=%PATH%;C:\your\path\here\
This command appends C:\your\path\here\
to the current PATH
.
Breaking it down:
set
– A command that changes cmd's environment variables only for the current cmd session; other programs and the system are unaffected.PATH=
– Signifies that PATH
is the environment variable to be temporarily changed.%PATH%;C:\your\path\here\
– The %PATH%
part expands to the current value of PATH
, and ;C:\your\path\here\
is then concatenated to it. This becomes the new PATH
.With Python 3.x you can do it like this:
from datetime import datetime, timedelta
from dateutil.relativedelta import *
date = datetime.now()
print(date)
# 2018-09-24 13:24:04.007620
date = date + relativedelta(months=+6)
print(date)
# 2019-03-24 13:24:04.007620
but you will need to install python-dateutil module:
pip install python-dateutil
This works fine in JAR files as well. You can obtain CodeSource
by ProtectionDomain#getCodeSource()
and the ProtectionDomain
in turn can be obtained by Class#getProtectionDomain()
.
public class Test {
public static void main(String... args) throws Exception {
URL location = Test.class.getProtectionDomain().getCodeSource().getLocation();
System.out.println(location.getFile());
}
}
If you're worried about changes and possibly incompatibly VMs, just copy the existing hashcode implementation into your own utility class, and use that to generate your hashcodes .
The simplest way of doing this is:
SELECT id,name,FROM_UNIXTIME(registration_date) FROM `tbl_registration`;
This gives the date column atleast in a readable format. Further if you want to change te format click here.
// In jest.setup.js
jest.setTimeout(30000)
If on Jest <= 23:
// In jest.config.js
module.exports = {
setupTestFrameworkScriptFile: './jest.setup.js'
}
If on Jest > 23:
// In jest.config.js
module.exports = {
setupFilesAfterEnv: ['./jest.setup.js']
}
I like the chosen answer. However, it tends to be slower than awk since 2 tools are needed to do the job.
$ wc -l file
49999998 file
$ time paste -sd+ file | bc
1448700364
real 1m36.960s
user 1m24.515s
sys 0m1.772s
$ time awk '{s+=$1}END{print s}' file
1448700364
real 0m45.476s
user 0m40.756s
sys 0m0.287s
It is impossible to safely escape a string without a DB connection. mysql_real_escape_string()
and prepared statements need a connection to the database so that they can escape the string using the appropriate character set - otherwise SQL injection attacks are still possible using multi-byte characters.
If you are only testing, then you may as well use mysql_escape_string()
, it's not 100% guaranteed against SQL injection attacks, but it's impossible to build anything safer without a DB connection.
You should install Brew first:
ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)"
Then brew install Python
brew install python
Then pip
will work
explode('.', $string)
If you know your string has a fixed number of components you could use something like
list($a, $b) = explode('.', 'object.attribute');
echo $a;
echo $b;
Prints:
object
attribute
You could use the Toolkit, no need for ImageIO
Image image = Toolkit.getDefaultToolkit().getImage(file.getAbsolutePath());
int width = image.getWidth(null);
int height = image.getHeight(null);
If you don't want to handle the loading of the image do
ImageIcon imageIcon = new ImageIcon(file.getAbsolutePath());
int height = imageIcon.getIconHeight();
int width = imageIcon.getIconWidth();
On my machine a PID was not being shown from this command netstat -tulpn
for the in-use port (8080), so i could not kill it, killing the containers and restarting the computer did not work. So service docker restart
command restarted docker for me (ubuntu) and the port was no longer in use and i am a happy chap and off to lunch.
Calling preventDefault
on touchmove
while you're actively scrolling is not working in Chrome. To prevent performance issues, you cannot interrupt a scroll.
Try to call preventDefault()
from touchstart
and everything should be ok.
JSON.stringify
takes more optional arguments.
Try:
JSON.stringify({a:1,b:2,c:{d:1,e:[1,2]}}, null, 4); // Indented 4 spaces
JSON.stringify({a:1,b:2,c:{d:1,e:[1,2]}}, null, "\t"); // Indented with tab
From:
How can I beautify JSON programmatically?
Should work in modern browsers, and it is included in json2.js if you need a fallback for browsers that don't support the JSON helper functions. For display purposes, put the output in a <pre>
tag to get newlines to show.
You could also use inline blocks to avoid floating elements
<ul>
<li>
<a href="#">some item</a>
</li>
<li>
<a href="#">another item</a>
</li>
</ul>
and then style as:
li{
/* with fix for IE */
display:inline;
display:inline-block;
zoom:1;
/*
additional styles to make it look nice
*/
}
that way you wont need to float anything, eliminating the need for clearfixes
If the app minSdkVersion
which you are working is level 9, you can use:
android:foreground="?selectableItemBackground"
android:clickable="true"
Instead, starting from level 11, you use:
android:foreground="?android:attr/selectableItemBackground"
android:clickable="true"
From documentation:
clickable - Defines whether this view reacts to click events. Must be a boolean value, either "true" or "false".
foreground - Defines the drawable to draw over the content. This can be used as an overlay. The foreground drawable participates in the padding of the content if the gravity is set to fill.
Basically, pip comes with python itself.Therefore it carries no meaning for using pip itself to install or upgrade python. Thus,try to install python through installer itself,visit the site "https://www.python.org/downloads/" for more help. Thank you.
How about this:
$ seq 1 100000 | tail -n +10000 | head -n 10
10000
10001
10002
10003
10004
10005
10006
10007
10008
10009
It uses tail
to output from the 10,000th line and onwards and then head
to only keep 10 lines.
The same (almost) result with sed
:
$ seq 1 100000 | sed -n '10000,10010p'
10000
10001
10002
10003
10004
10005
10006
10007
10008
10009
10010
This one has the advantage of allowing you to input the line range directly.
Another solution is Remove ng.ps1 from the directory C:\Users%username%\AppData\Roaming\npm\ and clearing the npm cache
What's abaut this one:
List<int> tmpList = intArry.ToList();
tmpList.Add(anyInt);
intArry = tmpList.ToArray();
This is @Jason's answer but with simplified output
SELECT name, CASE WHEN value = 1 THEN 'YES' ELSE 'NO' END AS 'Enabled'
FROM sys.configurations WHERE name = 'clr enabled'
The above returns the following:
| name | Enabled |
-------------------------
| clr enabled | YES |
Tested on SQL Server 2017
This answer is late, but I'm posting anyway hoping it will help someone. Like you, I also had difficulty submitting a form that was outside my bootstrap modal, and I didn't want to use ajax because I wanted a whole new page to load, not just part of the current page. After much trial and error here's the jQuery that worked for me:
$(function () {
$('body').on('click', '.odom-submit', function (e) {
$(this.form).submit();
$('#myModal').modal('hide');
});
});
To make this work I did this in the modal footer
<div class="modal-footer">
<button class="btn" data-dismiss="modal" aria-hidden="true">Close</button>
<button class="btn btn-primary odom-submit">Save changes</button>
</div>
Notice the addition to class of odom-submit. You can, of course, name it whatever suits your particular situation.
from
a directory_of_modules
, you can import
a specific_module.py
specific_module.py
, can contain a Class
with some_methods()
or just functions()
specific_module.py
, you can instantiate a Class
or call functions()
Class
, you can execute some_method()
Example:
#!/usr/bin/python3
from directory_of_modules import specific_module
instance = specific_module.DbConnect("username","password")
instance.login()
Excerpts from PEP 8 - Style Guide for Python Code:
Modules should have short and all-lowercase names.
Notice: Underscores can be used in the module name if it improves readability.
A Python module is simply a source file(*.py), which can expose:
Class: names using the "CapWords" convention.
Function: names in lowercase, words separated by underscores.
Global Variables: the conventions are about the same as those for Functions.
I tried use [disabled]="!editmode"
but it not work in my case.
This is my solution [disabled]="!editmode ? 'disabled': null"
, I share for whom concern.
<button [disabled]="!editmode ? 'disabled': null"
(click)='loadChart()'>
<div class="btn-primary">Load Chart</div>
</button>
You can turn off foreign key checks:
SET FOREIGN_KEY_CHECKS = 0;
/* DO WHAT YOU NEED HERE */
SET FOREIGN_KEY_CHECKS = 1;
Please make sure to NOT use this on production and have a backup.
An addition to the answer: when you do not want to list the folders, only the files in the subfolders, use /A-D switch like this:
dir ..\myfolder /b /s /A-D /o:gn>list.txt
If you append json data to query string, and parse it later in web api side. you can parse complex object. It's useful rather than post json object style. This is my solution.
//javascript file
var data = { UserID: "10", UserName: "Long", AppInstanceID: "100", ProcessGUID: "BF1CC2EB-D9BD-45FD-BF87-939DD8FF9071" };
var request = JSON.stringify(data);
request = encodeURIComponent(request);
doAjaxGet("/ProductWebApi/api/Workflow/StartProcess?data=", request, function (result) {
window.console.log(result);
});
//webapi file:
[HttpGet]
public ResponseResult StartProcess()
{
dynamic queryJson = ParseHttpGetJson(Request.RequestUri.Query);
int appInstanceID = int.Parse(queryJson.AppInstanceID.Value);
Guid processGUID = Guid.Parse(queryJson.ProcessGUID.Value);
int userID = int.Parse(queryJson.UserID.Value);
string userName = queryJson.UserName.Value;
}
//utility function:
public static dynamic ParseHttpGetJson(string query)
{
if (!string.IsNullOrEmpty(query))
{
try
{
var json = query.Substring(7, query.Length - 7); //seperate ?data= characters
json = System.Web.HttpUtility.UrlDecode(json);
dynamic queryJson = JsonConvert.DeserializeObject<dynamic>(json);
return queryJson;
}
catch (System.Exception e)
{
throw new ApplicationException("can't deserialize object as wrong string content!", e);
}
}
else
{
return null;
}
}
like
is best, or at least easiest.match
is used for regex comparisons.Boolean types are defined in documentation:
http://docs.python.org/library/stdtypes.html#boolean-values
Quoted from doc:
Boolean values are the two constant objects False and True. They are used to represent truth values (although other values can also be considered false or true). In numeric contexts (for example when used as the argument to an arithmetic operator), they behave like the integers 0 and 1, respectively. The built-in function bool() can be used to cast any value to a Boolean, if the value can be interpreted as a truth value (see section Truth Value Testing above).
They are written as False and True, respectively.
So in java code remove braces, change true
to True
and you will be ok :)
You could try:
agg <- aggregate(list(x$val1, x$val2, x$val3, x$val4), by = list(x$id1, x$id2), mean)
public static void main(String[] args) {
System.out.println("test word".contains(" "));
}
In fact, your query is right except for the typo: your filter is excluding all records: you should change the <=
for >=
and vice versa:
qry = DBSession.query(User).filter(
and_(User.birthday <= '1988-01-17', User.birthday >= '1985-01-17'))
# or same:
qry = DBSession.query(User).filter(User.birthday <= '1988-01-17').\
filter(User.birthday >= '1985-01-17')
Also you can use between
:
qry = DBSession.query(User).filter(User.birthday.between('1985-01-17', '1988-01-17'))
in Content script , i add script tag to the head which binds a 'onmessage' handler, inside the handler i use , eval to execute code. In booth content script i use onmessage handler as well , so i get two way communication. Chrome Docs
//Content Script
var pmsgUrl = chrome.extension.getURL('pmListener.js');
$("head").first().append("<script src='"+pmsgUrl+"' type='text/javascript'></script>");
//Listening to messages from DOM
window.addEventListener("message", function(event) {
console.log('CS :: message in from DOM', event);
if(event.data.hasOwnProperty('cmdClient')) {
var obj = JSON.parse(event.data.cmdClient);
DoSomthingInContentScript(obj);
}
});
pmListener.js is a post message url listener
//pmListener.js
//Listen to messages from Content Script and Execute Them
window.addEventListener("message", function (msg) {
console.log("im in REAL DOM");
if (msg.data.cmnd) {
eval(msg.data.cmnd);
}
});
console.log("injected To Real Dom");
This way , I can have 2 way communication between CS to Real Dom. Its very usefull for example if you need to listen webscoket events , or to any in memory variables or events.
As an alternative to Directory.Exists(), you can use the File.GetAttributes() method to get the attributes of a file or a directory, so you could create a helper method like this:
private static bool IsDirectory(string path)
{
System.IO.FileAttributes fa = System.IO.File.GetAttributes(path);
return (fa & FileAttributes.Directory) != 0;
}
You could also consider adding an object to the tag property of the TreeView control when populating the control that contains additional metadata for the item. For instance, you could add a FileInfo object for files and a DirectoryInfo object for directories and then test for the item type in the tag property to save making additional system calls to get that data when clicking on the item.
(This answer might seem needlessly complicated, but it’s easily extensible and robust regarding whitespace and special characters, as far as I know.)
You can feed data right through the standard input of the ssh
command and read
that from the remote location.
In the following example,
ssh
a null-terminated line giving the name and value of the variable.shh
command itself, we loop through these lines to initialise the required variables.# Initialize examples of variables.
# The first one even contains whitespace and a newline.
readonly FOO=$'apjlljs ailsi \n ajlls\t éjij'
readonly BAR=ygnàgyààynygbjrbjrb
# Make a list of what you want to pass through SSH.
# (The “unset” is just in case someone exported
# an associative array with this name.)
unset -v VAR_NAMES
readonly VAR_NAMES=(
FOO
BAR
)
for name in "${VAR_NAMES[@]}"
do
printf '%s %s\0' "$name" "${!name}"
done | ssh [email protected] '
while read -rd '"''"' name value
do
export "$name"="$value"
done
# Check
printf "FOO = [%q]; BAR = [%q]\n" "$FOO" "$BAR"
'
Output:
FOO = [$'apjlljs ailsi \n ajlls\t éjij']; BAR = [ygnàgyààynygbjrbjrb]
If you don’t need to export
those, you should be able to use declare
instead of export
.
A really simplified version (if you don’t need the extensibility, have a single variable to process, etc.) would look like:
$ ssh [email protected] 'read foo' <<< "$foo"
Note:put this code in your javascript at the point you want the beep to occur. and remember to specify the directory or folder where the beep sound is stored(source).
<script>
//Appending HTML5 Audio Tag in HTML Body
$('<audio id="chatAudio"><source src="sound/notify.ogg" type="audio/ogg"><source src="sound/notify.mp3" type="audio/mpeg"><source src="sound/notify.wav" type="audio/wav"></audio>').appendTo('body');
$('#chatAudio')[0].play();
</script>
Reference:http://www.9lessons.info/2013/04/play-notification-sound-using-jquery.html.
I implemented this in a social media i am developing and it works find, a notification like that of facebook when chatting, notifying you that you have a new chat message
I had this problem. It took me ages to figure out. I had people over my shoulder to help. We rebuilt, cleaned and restarted Visual studio and this didn't fix it. We removed and re-added the references...
All to no avail.... Until!
The solution to my problem was that my class declaration was spelt incorrectly.
Before you start judging me harshly, allow me to explain why it wasn't stupid, and also why this mistake could be made by even the most intelligent of programmers.
Since the mistake was early on in the name, it wasn't appearing in the intellisense class listing when I began typing.
e.g.
Class name:
Message.cs
Declaration:
public class Massage
{
//code here
}
At a glance and in a small font, Massage looks identical to Message.
Typing M listed too many classes, so I typed e, which didn't appear in the mistyped version, which gave the impression that the class wasn't being picked up by the compiler.
This is the way to iterate on this array:
foreach($hotels as $row) {
foreach($row['rooms'] as $k) {
echo $k['boards']['board_id'];
echo $k['boards']['price'];
}
}
You want to iterate on the hotels and the rooms (the ones with numeric indexes), because those seem to be the "collections" in this case. The other arrays only hold and group properties.
To write console output to a txt file
public static void main(String[] args) {
int i;
List<String> ls = new ArrayList<String>();
for (i = 1; i <= 100; i++) {
String str = null;
str = +i + ":- HOW TO WRITE A CONSOLE OUTPUT IN A TEXT FILE";
ls.add(str);
}
String listString = "";
for (String s : ls) {
listString += s + "\n";
}
FileWriter writer = null;
try {
writer = new FileWriter("final.txt");
writer.write(listString);
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
}
If you want to generate the PDF rather then the text file, you use the dependency given below:
<dependency>
<groupId>com.itextpdf</groupId>
<artifactId>itextpdf</artifactId>
<version>5.0.6</version>
</dependency>
To generate a PDF, use this code:
public static void main(String[] args) {
int i;
List<String> ls = new ArrayList<String>();
for (i = 1; i <= 100; i++) {
String str = null;
str = +i + ":- HOW TO WRITE A CONSOLE OUTPUT IN A PDF";
ls.add(str);
}
String listString = "";
for (String s : ls) {
listString += s + "\n";
}
Document document = new Document();
try {
PdfWriter writer1 = PdfWriter
.getInstance(
document,
new FileOutputStream(
"final_pdf.pdf"));
document.open();
document.add(new Paragraph(listString));
document.close();
writer1.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (DocumentException e) {
e.printStackTrace();
}
}
To alter the password expiry policy for a certain user profile in Oracle first check which profile the user is using:
select profile from DBA_USERS where username = '<username>';
Then you can change the limit to never expire using:
alter profile <profile_name> limit password_life_time UNLIMITED;
If you want to previously check the limit you may use:
select resource_name,limit from dba_profiles where profile='<profile_name>';
I went to publish, application files, found the dll throwing the error changed it to 'Include' from 'Include (Auto)'. I can now publish.
For Windows
I had the same problem, I tried to reinstall and didn't worked for me.
Remove "C:\Program Files(x86)\nodejs"
from your system enviorment PATH
and thats it!
You can find the basedir (and within maybe your my.cnf) if you do the following query in your mysql-Client (e.g. phpmyadmin)
SHOW VARIABLES
On Mac/Linux System, the successfully downloaded boxes are located at:
~/.vagrant.d/boxes
and unsuccessful boxes are located at:
~/.vagrant.d/tmp
On Windows systems it is located under the Users folder:
C:\Users\%userprofile%\.vagrant.d\boxes
Hope this will help. Thanks
Actually, it looks like you may be able to download language packs directly through Windows Update. Open the old Control Panel by pressing WinKey+X and clicking Control Panel. Then go to Clock, Language, and Region > Add a language. Add the desired language. Then under the language it should say "Windows display language: Available". Click "Options" and then "Download and install language pack."
I'm not sure why this functionality appears to be less accessible than it was in Windows 8.
If you must work with only standard JDK classes you can use this:
/**
* Converts the given <code>date</code> from the <code>fromTimeZone</code> to the
* <code>toTimeZone</code>. Since java.util.Date has does not really store time zome
* information, this actually converts the date to the date that it would be in the
* other time zone.
* @param date
* @param fromTimeZone
* @param toTimeZone
* @return
*/
public static Date convertTimeZone(Date date, TimeZone fromTimeZone, TimeZone toTimeZone)
{
long fromTimeZoneOffset = getTimeZoneUTCAndDSTOffset(date, fromTimeZone);
long toTimeZoneOffset = getTimeZoneUTCAndDSTOffset(date, toTimeZone);
return new Date(date.getTime() + (toTimeZoneOffset - fromTimeZoneOffset));
}
/**
* Calculates the offset of the <code>timeZone</code> from UTC, factoring in any
* additional offset due to the time zone being in daylight savings time as of
* the given <code>date</code>.
* @param date
* @param timeZone
* @return
*/
private static long getTimeZoneUTCAndDSTOffset(Date date, TimeZone timeZone)
{
long timeZoneDSTOffset = 0;
if(timeZone.inDaylightTime(date))
{
timeZoneDSTOffset = timeZone.getDSTSavings();
}
return timeZone.getRawOffset() + timeZoneDSTOffset;
}
Credit goes to this post.
The following is a regular expression matching a multiline block of text:
import re
result = re.findall('(startText)(.+)((?:\n.+)+)(endText)',input)
You may try altering toolchain in case if for some reason you can't use gcc. Open Properties for your project (by right clicking on your project name in the Project Explorer), then C/C++ Build > Tool Chain Editor. You can change the current builder there from GNU Make Builder to CDT Internal Builder or whatever compatible you have.
You may be using old version of Mysql but surely you can use
DELETE FROM konta WHERE taken <> ''
But there are many other options available. You can try the following ones
DELETE * from konta WHERE strcmp(taken, '') <> 0;
DELETE * from konta where NOT (taken = '');
No official API to do it. Using private API you can use following method:
-(NSString*) getMyNumber {
NSLog(@"Open CoreTelephony");
void *lib = dlopen("/Symbols/System/Library/Framework/CoreTelephony.framework/CoreTelephony",RTLD_LAZY);
NSLog(@"Get CTSettingCopyMyPhoneNumber from CoreTelephony");
NSString* (*pCTSettingCopyMyPhoneNumber)() = dlsym(lib, "CTSettingCopyMyPhoneNumber");
NSLog(@"Get CTSettingCopyMyPhoneNumber from CoreTelephony");
if (pCTSettingCopyMyPhoneNumber == nil) {
NSLog(@"pCTSettingCopyMyPhoneNumber is nil");
return nil;
}
NSString* ownPhoneNumber = pCTSettingCopyMyPhoneNumber();
dlclose(lib);
return ownPhoneNumber;
}
It works on iOS 6 without JB and special signing.
As mentioned creker on iOS 7 with JB you need to use entitlements to make it working.
How to do it with entitlements you can find here: iOS 7: How to get own number via private API?
I found out it was:
$ git fetch upstream
$ git merge upstream/master
Private Sub Worksheet_Change(ByVal Target As Range)
Dim rng As Range, r As Range
Set rng = Intersect(Target, Range("a2:a" & Rows.Count))
If rng Is Nothing Then Exit Sub
For Each r In rng
If Not IsEmpty(r.Value) Then
r.Copy Destination:=Sheets("sheet2").Range("a2")
End If
Next
Set rng = Nothing
End Sub
Quick and dirty - Turn it off:
USE_TZ = False
in your settings.py
This can be confusing for anyone using nodejs for the first time. It is actually possible to pipe your node console output to the browser console. Take a look at connect-browser-logger on github
UPDATE: As pointed out by Yan, connect-browser-logger appears to be defunct. I would recommend NodeMonkey as detailed here : Output to Chrome console from Node.js
You should be able to use Windows "UNC" paths with robocopy. For example:
robocopy \\myServer\myFolder\myFile.txt \\myOtherServer\myOtherFolder
Robocopy has the ability to recover from certain types of network hiccups automatically.
What kind of processing are you trying to do? You can do XmlDocument doc = new XmlDocument();
followed by doc.Load(filename)
. Then the XML document can be parsed in memory.
Read here for more information on XmlDocument:
The git pull -X theirs
answers may create an ugly merge commit, or issue an
error: Your local changes to the following files would be overwritten by merge:
If you want to simply ignore any local modifications to files from the repo, for example on a client that should always be a mirror of an origin, run this (replace master
with the branch you want):
git fetch && git reset --hard origin/master
How does it work? git fetch
does git pull
but without merge. Then git reset --hard
makes your working tree match the last commit. All of your local changes to files in the repo will be discarded, but new local files will be left alone.
In your IServece.cs add the following tag : BodyStyle = WebMessageBodyStyle.Bare
[WebInvoke(Method = "GET", ResponseFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.Bare, UriTemplate = "Getperson/{id}")]
List<personClass> Getperson(string id);
Here you go:
$.inArray('specialword', arr)
This function returns a positive integer (the array index of the given value), or -1
if the given value was not found in the array.
Live demo: http://jsfiddle.net/simevidas/5Gdfc/
You probably want to use this like so:
if ( $.inArray('specialword', arr) > -1 ) {
// the value is in the array
}
Along with Python 2.7 and 3.3, Red Hat Software Collections now includes Python 3.4 - all work on both RHEL 6 and 7.
RHSCL 2.0 docs are at https://access.redhat.com/documentation/en-US/Red_Hat_Software_Collections/
Plus lot of articles at developerblog.redhat.com.
edit
# 1. Install the Software Collections tools:
yum install scl-utils
# 2. Download a package with repository for your system.
# (See the Yum Repositories on external link. For RHEL/CentOS 6:)
wget https://www.softwarecollections.org/en/scls/rhscl/rh-python34/epel-6-x86_64/download/rhscl-rh-python34-epel-6-x86_64.noarch.rpm
# or for RHEL/CentOS 7
wget https://www.softwarecollections.org/en/scls/rhscl/rh-python34/epel-7-x86_64/download/rhscl-rh-python34-epel-7-x86_64.noarch.rpm
# 3. Install the repo package (on RHEL you will need to enable optional channel first):
yum install rhscl-rh-python34-*.noarch.rpm
# 4. Install the collection:
yum install rh-python34
# 5. Start using software collections:
scl enable rh-python34 bash
try this code to create Scale animation without using xml
ScaleAnimation animation = new ScaleAnimation(fromXscale, toXscale, fromYscale, toYscale, Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f);
$timeFirst = strtotime('2011-05-12 18:20:20');
$timeSecond = strtotime('2011-05-13 18:20:20');
$differenceInSeconds = $timeSecond - $timeFirst;
You will then be able to use the seconds to find minutes, hours, days, etc.
You can't modify strings; they're immutable. You can do this instead:
txtBox.Text = txtBox.Text.Substring(0, i) + "TEXT" + txtBox.Text.Substring(i);
In PostreSQL you can use SIMILAR TO operator (more):
-- only digits
select * from books where title similar to '^[0-9]*$';
-- start with digit
select * from books where title similar to '^[0-9]%$';
This should work on mysql > 5.5
SHOW VARIABLES LIKE '%long%';
SET GLOBAL long_query_time = 1;
Security warning: This code snippet is vulnerable to Bleichenbacher's 1998 padding oracle attack. See this answer for better security.
class MyEncryption
{
public $pubkey = '...public key here...';
public $privkey = '...private key here...';
public function encrypt($data)
{
if (openssl_public_encrypt($data, $encrypted, $this->pubkey))
$data = base64_encode($encrypted);
else
throw new Exception('Unable to encrypt data. Perhaps it is bigger than the key size?');
return $data;
}
public function decrypt($data)
{
if (openssl_private_decrypt(base64_decode($data), $decrypted, $this->privkey))
$data = $decrypted;
else
$data = '';
return $data;
}
}
I ran into this problem, and when I checked out the database directory, there were a number of exp
files (the ibd
and frm
files had been removed). Listing the files to look at their attributes (since the owner already had rw privileges on the files)
lsattr *.exp
-------------e-- foo.exp
-------------e-- bar.exp
Man page says
The 'e' attribute indicates that the file is using extents for mapping the blocks on disk.
It may not be removed using chattr(1).
You actually can chattr -e
these files, but mysql still won't let you drop the database. Removing the files with rm
, however, allows the database to be dropped cleanly.
I implemented all the previous answers and still had one view that did not work correctly.
It turned out the name of the view I was having the problem with was named 'Recent'. Apparently this confused the Internet Explorer browser.
After I changed the view name (in the controller) to a different name (I chose to 'Recent5'), the solutions above started to work.
We can use params
, new feature of the UI-Router:
API Reference / ui.router.state / $stateProvider
params
A map which optionally configures parameters declared in the url, or defines additional non-url parameters. For each parameter being configured, add a configuration object keyed to the name of the parameter.
See the part: "...or defines additional non-url parameters..."
So the state def would be:
$stateProvider
.state('home', {
url: "/home",
templateUrl: 'tpl.html',
params: { hiddenOne: null, }
})
Few examples form the doc mentioned above:
// define a parameter's default value
params: {
param1: { value: "defaultValue" }
}
// shorthand default values
params: {
param1: "defaultValue",
param2: "param2Default"
}
// param will be array []
params: {
param1: { array: true }
}
// handling the default value in url:
params: {
param1: {
value: "defaultId",
squash: true
} }
// squash "defaultValue" to "~"
params: {
param1: {
value: "defaultValue",
squash: "~"
} }
EXTEND - working example: http://plnkr.co/edit/inFhDmP42AQyeUBmyIVl?p=info
Here is an example of a state definition:
$stateProvider
.state('home', {
url: "/home",
params : { veryLongParamHome: null, },
...
})
.state('parent', {
url: "/parent",
params : { veryLongParamParent: null, },
...
})
.state('parent.child', {
url: "/child",
params : { veryLongParamChild: null, },
...
})
This could be a call using ui-sref:
<a ui-sref="home({veryLongParamHome:'Home--f8d218ae-d998-4aa4-94ee-f27144a21238'
})">home</a>
<a ui-sref="parent({
veryLongParamParent:'Parent--2852f22c-dc85-41af-9064-d365bc4fc822'
})">parent</a>
<a ui-sref="parent.child({
veryLongParamParent:'Parent--0b2a585f-fcef-4462-b656-544e4575fca5',
veryLongParamChild:'Child--f8d218ae-d998-4aa4-94ee-f27144a61238'
})">parent.child</a>
Check the example here
You can use a try-except
try:
print(str.to.id)
except AttributeError: # Not a Retweet
print('null')
There's no direct support for LIKE operator against DATETIME variables, but you can always cast the DATETIME to a VARCHAR:
SELECT (list of fields) FROM YourTable
WHERE CONVERT(VARCHAR(25), register_date, 126) LIKE '2009-10-10%'
Check the MSDN docs for a complete list of available "styles" in the CONVERT function.
Marc
char c = 'A';
printf("ptr: %p,\tvalue: %c,\tand also address: %zu", &c, c, &c);
Result:
ptr: 0x7ffc48e5105f, value: A, and also address: 140721531457631
Putty doesn't use openssh key files - there is a utility in putty suite to convert them.
edit: it is called puttygen
You can stub a static void method like this:
PowerMockito.doNothing().when(StaticResource.class, "getResource", anyString());
Although I'm not sure why you would bother, because when you call mockStatic(StaticResource.class) all static methods in StaticResource are by default stubbed
More useful, you can capture the value passed to StaticResource.getResource() like this:
ArgumentCaptor<String> captor = ArgumentCaptor.forClass(String.class);
PowerMockito.doNothing().when(
StaticResource.class, "getResource", captor.capture());
Then you can evaluate the String that was passed to StaticResource.getResource like this:
String resourceName = captor.getValue();
basename
and dirname
solutions are more convenient. Those are alternative commands:
FILE_PATH="/opt/datastores/sda2/test.old.img"
echo "$FILE_PATH" | sed "s/.*\///"
This returns test.old.img
like basename
.
This is salt filename without extension:
echo "$FILE_PATH" | sed -r "s/.+\/(.+)\..+/\1/"
It returns test.old
.
And following statement gives the full path like dirname
command.
echo "$FILE_PATH" | sed -r "s/(.+)\/.+/\1/"
It returns /opt/datastores/sda2
I had a similar problem and I needed to insert multiple if not existing. So from the examples above I came to this combination... it's here just in case somebody would need it.
Notice: I had to define name everywhere as MSSQL required it... MySQL works with * too.
INSERT INTO names (name)
SELECT name
FROM
(
SELECT name
FROM
(
SELECT 'Test 4' as name
) AS tmp_single
WHERE NOT EXISTS
(
SELECT name FROM names WHERE name = 'Test 4'
)
UNION ALL
SELECT name
FROM
(
SELECT 'Test 5' as name
) AS tmp_single
WHERE NOT EXISTS
(
SELECT name FROM names WHERE name = 'Test 5'
)
) tmp_all;
MySQL:
CREATE TABLE names
(
OID
int(11) NOT NULL AUTO_INCREMENT,
name
varchar(32) COLLATE utf8_unicode_ci NOT NULL,
PRIMARY KEY (OID
),
UNIQUE KEY name_UNIQUE
(name
)
) ENGINE=InnoDB AUTO_INCREMENT=1;
or
MSSQL: CREATE TABLE [names] ( [OID] INT IDENTITY (1, 1) NOT NULL, [name] NVARCHAR (32) NOT NULL, PRIMARY KEY CLUSTERED ([OID] ASC) ); CREATE UNIQUE NONCLUSTERED INDEX [Index_Names_Name] ON [names]([name] ASC);
^ these suggestions are great for those who are programmatically creating an interface.
But there are two LAZY EASY WAYS for those of us who use the Xcode interface builder:
easier: put a UIImageView behind a text field
easiest: change the border style on your to the simple black square (second from left option), then add your image as a background image. The image takes precedence over the square, so you still get the padding needed for a normal image background, without the square actually being drawn on.
EDIT: you can also use the black sphere (third from left option when selecting the UITextBox in IB), it does not work with the far right, "graphical sphere" style.
For those who find this topic much later:
If you have just three values to compare there is no significant difference. But if you have to find min of, say, thirty or sixty values, "min" could be easier for anyone to read in the code next year:
int smallest;
smallest = min(a1, a2);
smallest = min(smallest, a3);
smallest = min(smallest, a4);
...
smallest = min(smallest, a37);
But if you think of speed, maybe better way would be to put values into list, and then find min of that:
List<Integer> mySet = Arrays.asList(a1, a2, a3, ..., a37);
int smallest = Collections.min(mySet);
Would you agree?
The asterisk (*) means "zero or more of the previous item".
If you want to match any single character use
sed -i 's/string-./string-0/g' file.txt
If you want to match any string (i.e. any single character zero or more times) use
sed -i 's/string-.*/string-0/g' file.txt
I prefer to use something like this:
int? var1 = ds.Tables[0].Rows[0].Field<int?>("ColumnName");
or
int? var1 = ds.Tables[0].Rows[0].Field<int?>(3); //column index
Define a class like this :
public class myclass {
string id ;
string title ;
string content;
}
public class program {
public void Main () {
List<myclass> objlist = new List<myclass> () ;
foreach (var value in objlist) {
TextBox1.Text = value.id ;
TextBox2.Text= value.title;
TextBox3.Text= value.content ;
}
}
}
I tried to draw a sketch and you can improve it in many ways. Instead of defining class "myclass", you can define struct.
Well I know this might be a big change or even not suitable for your project, but did you consider not performing the push until you already have the data? That way you only need to draw the view once and the user experience will also be better - the push will move in already loaded.
The way you do this is in the UITableView
didSelectRowAtIndexPath
you asynchronously ask for the data. Once you receive the response, you manually perform the segue and pass the data to your viewController in prepareForSegue
.
Meanwhile you may want to show some activity indicator, for simple loading indicator check https://github.com/jdg/MBProgressHUD
This is work for me
@FOR /f "delims=" %i in ('reg query hklm\SOFTWARE\Macromedia\FlashPlayer\CurrentVersion') DO set var=%i
echo %var%
You can update gem to any specific version like this,
gem update --system 'version'
gem update --system '2.3.0'
If you want to recompile PHP
with mcrypt
enable.
1.
Insatll mcrypt
. libmcrypt-devel
is from Third Party Repositories EPEL, so you should:
yum --enablerepo=extras install epel-release
yum install libmcrypt-devel
2.
Append --with-mcrypt
to your ./configure
arguments:
./configure --with-mcrypt
3. Build and install:
make & make install
Open a new worksheet on the related instance (Alt-F10)
and run the following query
SELECT view_name, owner
FROM sys.all_views
ORDER BY owner, view_name