Work 100%. maybe not relation to creator answer but i share it for users have a problem with export mysql query to excel with phpexcel. Good Luck.
require('../phpexcel/PHPExcel.php');
require('../phpexcel/PHPExcel/Writer/Excel5.php');
$filename = 'userReport'; //your file name
$objPHPExcel = new PHPExcel();
/*********************Add column headings START**********************/
$objPHPExcel->setActiveSheetIndex(0)
->setCellValue('A1', 'username')
->setCellValue('B1', 'city_name');
/*********************Add data entries START**********************/
//get_result_array_from_class**You can replace your sql code with this line.
$result = $get_report_clas->get_user_report();
//set variable for count table fields.
$num_row = 1;
foreach ($result as $value) {
$user_name = $value['username'];
$c_code = $value['city_name'];
$num_row++;
$objPHPExcel->setActiveSheetIndex(0)
->setCellValue('A'.$num_row, $user_name )
->setCellValue('B'.$num_row, $c_code );
}
/*********************Autoresize column width depending upon contents START**********************/
foreach(range('A','B') as $columnID) {
$objPHPExcel->getActiveSheet()->getColumnDimension($columnID)->setAutoSize(true);
}
$objPHPExcel->getActiveSheet()->getStyle('A1:B1')->getFont()->setBold(true);
//Make heading font bold
/*********************Add color to heading START**********************/
$objPHPExcel->getActiveSheet()
->getStyle('A1:B1')
->getFill()
->setFillType(PHPExcel_Style_Fill::FILL_SOLID)
->getStartColor()
->setARGB('99ff99');
$objPHPExcel->getActiveSheet()->setTitle('userReport'); //give title to sheet
$objPHPExcel->setActiveSheetIndex(0);
header('Content-Type: application/vnd.ms-excel');
header("Content-Disposition: attachment;Filename=$filename.xls");
header('Cache-Control: max-age=0');
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
$objWriter->save('php://output');
Create New User Environment Variables:
MAVEN_HOME=D:\apache-maven-3.5.3
MAVEN=D:\apache-maven-3.5.3\bin
MAVEN_OPTS=-Xms256m -Xmx512m
Appened below in Path variable (System Variable):
;D:\apache-maven-3.5.3\bin;
You could format the dates before you add them to your array. That is how I did. I used AngularJS
//convert the date to a standard format
var dt = new Date(date);
//take only the date and month and push them to your label array
$rootScope.charts.mainChart.labels.push(dt.getDate() + "-" + (dt.getMonth() + 1));
Use this array in your chart presentation
Try this
<form method="post" id="reg" name="reg" action="<?php echo htmlspecialchars($_SERVER['PHP_SELF']);?>"
Works well :)
As far as I know, there are 2 standard ways you can do that.
1. @Input
Whenever the data in the parent changes, the child gets notified about this in the ngOnChanges method. The child can act on it. This is the standard way of interacting with a child.
Parent-Component
public inputToChild: Object;
Parent-HTML
<child [data]="inputToChild"> </child>
Child-Component: @Input() data;
ngOnChanges(changes: { [property: string]: SimpleChange }){
// Extract changes to the input property by its name
let change: SimpleChange = changes['data'];
// Whenever the data in the parent changes, this method gets triggered. You
// can act on the changes here. You will have both the previous value and the
// current value here.
}
Creating a service and using an observable in the shared service. The child subscribes to it and whenever there is a change, the child will be notified. This is also a popular method. When you want to send something other than the data you pass as the input, this can be used.
SharedService
subject: Subject<Object>;
Parent-Component
constructor(sharedService: SharedService)
this.sharedService.subject.next(data);
Child-Component
constructor(sharedService: SharedService)
this.sharedService.subject.subscribe((data)=>{
// Whenever the parent emits using the next method, you can receive the data
in here and act on it.})
Another possibility is that setting dataType: json
causes JQuery to send the Content-Type: application/json
header. This is considered a non-standard header by CORS, and requires a CORS preflight request. So a few things to try:
1) Try configuring your server to send the proper preflight responses. This will be in the form of additional headers like Access-Control-Allow-Methods
and Access-Control-Allow-Headers
.
2) Drop the dataType: json
setting. JQuery should request Content-Type: application/x-www-form-urlencoded
by default, but just to be sure, you can replace dataType: json
with contentType: 'application/x-www-form-urlencoded'
UPDATED for Swift 4: (credit to Marco Weber)
if let requestUrl = NSURL(string: "http://www.iSecurityPlus.com") {
UIApplication.shared.openURL(requestUrl as URL)
}
OR go with more of swift style using guard
:
guard let requestUrl = NSURL(string: "http://www.iSecurityPlus.com") else {
return
}
UIApplication.shared.openURL(requestUrl as URL)
Swift 3:
You can check NSURL as optional implicitly by:
if let requestUrl = NSURL(string: "http://www.iSecurityPlus.com") {
UIApplication.sharedApplication().openURL(requestUrl)
}
See the Express docs as well as the Node docs for https.createServer (which is what express recommends to use):
var privateKey = fs.readFileSync( 'privatekey.pem' );
var certificate = fs.readFileSync( 'certificate.pem' );
https.createServer({
key: privateKey,
cert: certificate
}, app).listen(port);
Other options for createServer are at: http://nodejs.org/api/tls.html#tls_tls_createserver_options_secureconnectionlistener
To go one step further, I assume you want to do something with these dtypes.
df.dtypes.to_dict()
comes in handy.
my_type = 'float64' #<---
dtypes = dataframe.dtypes.to_dict()
for col_nam, typ in dtypes.items():
if (typ != my_type): #<---
raise ValueError(f"Yikes - `dataframe['{col_name}'].dtype == {typ}` not {my_type}")
You'll find that Pandas did a really good job comparing NumPy classes and user-provided strings. For example: even things like 'double' == dataframe['col_name'].dtype
will succeed when .dtype==np.float64
.
Use the SingleOrDefault() instead of FirstOrDefault().
Note: you should use the accepted answer if possible. It's better than mine.
It's quite easy with the GD library.
It's built in usually, you probably have it (use phpinfo()
to check)
$image = imagecreatefromjpeg("http://images.websnapr.com/?size=size&key=Y64Q44QLt12u&url=http://google.com");
imagejpeg($image, "folder/file.jpg");
The above answer is better (faster) for most situations, but with GD you can also modify it in some form (cropping for example).
$image = imagecreatefromjpeg("http://images.websnapr.com/?size=size&key=Y64Q44QLt12u&url=http://google.com");
imagecopy($image, $image, 0, 140, 0, 0, imagesx($image), imagesy($image));
imagejpeg($image, "folder/file.jpg");
This only works if allow_url_fopen
is true
(it is by default)
Note: Simplest difference between sort() and sorted() is: sort() doesn't return any value while, sorted() returns an iterable list.
sort() doesn't return any value.
The sort() method just sorts the elements of a given list in a specific order - Ascending or Descending without returning any value.
The syntax of sort() method is:
list.sort(key=..., reverse=...)
Alternatively, you can also use Python's in-built function sorted() for the same purpose. sorted function return sorted list
list=sorted(list, key=..., reverse=...)
I used the below to solve this problem.
import org.apache.commons.lang.StringUtils;
StringUtils.capitalize(MyString);
Thanks to Ted Hopp for rightly pointing out that the question should have been TITLE CASE instead of modified CAMEL CASE.
Camel Case is usually without spaces between words.
How about
SELECT *
FROM Employees
WHERE PhoneNumber IN (
SELECT PhoneNumber
FROM Employees
GROUP BY PhoneNumber
HAVING COUNT(Employee_ID) > 1
)
Change:
x.length
to:
x.options.length
Link to fiddle
And I agree with Abraham - you might want to use text
instead of value
Update
The reason your fiddle didn't work was because you chose the option: "onLoad" instead of: "No wrap - in "
People seem to forget that there is also the other direction.
Why are you writing in Assembler in the first place? Why not write the program in a truly low level language?
Instead of
mov eax, 0x123
add eax, 0x456
push eax
call printInt
you could just as well write
B823010000
0556040000
50
FF15.....
That has so many advantages, you know the exact size of your program, you can reuse the value of instructions as input for other instructions and you do not even need an assembler to write it, you can use any text editor...
And the reason you still prefer Assembler about this, is the reason other people prefer C...
The SKU example used in the documentation was to provide the allowed characters in a new user-specified SKU.
The browser's native JSON API may not give you back your idOld function after you call JSON.stringify, however, if can stringify your JSON yourself (maybe use Crockford's json2.js instead of browser's API), then if you have a string of JSON e.g.
var person_json = "{ \"age:\" : 20, \"isOld:\": false, isOld: function() { return this.age > 60; } }";
then you can call
eval("(" + person + ")")
, and you will get back your function in the json object.
You just need to a add the path of your PHP
file. In case you are using wamp
or have not installed it on the C drive.
For me it was a wrong maven dependency deceleration, so here is the correct way:
for sqljdbc4 use: sqljdbc4 dependency
<dependency>
<groupId>com.microsoft.sqlserver</groupId>
<artifactId>sqljdbc4</artifactId>
<version>4.0</version>
</dependency>
for sqljdbc42 use: sqljdbc42 dependency
<dependency>
<groupId>com.microsoft.sqlserver</groupId>
<artifactId>sqljdbc42</artifactId>
<version>6.0.8112</version>
</dependency>
The recommendations from this article Extracting Data From Excel with SSIS resolved the issue for me.
I downloaded MS Access Database Engine 2010 32 bit driver from the link in that article.
Also set Project Configuration Properties for Debugging Run64BitRuntime = False
In SQL Server 2014 SSMS (Integration Service Catalog -> SSISDB -> Environments -> Projects for all Packages in Validate checked box 32 bit Runtime
.
My SSIS packages are working now in both VS 2013 and SQL Server 2014 environments.
with open("Stud.txt", "rt") as fin:
with open("out.txt", "wt") as fout:
for line in fin:
fout.write(line.replace('A', 'Orange'))
all, I solved a problem and wanted to share it:
I had this error <> The issue was in that in my statement:
alter table system_registro_de_modificacion add foreign key (usuariomodificador_id) REFERENCES Usuario(id) On delete restrict;
I had incorrectly written the CASING: it works in Windows WAMP, but in Linux MySQL it is more strict with the CASING, so writting "Usuario" instead of "usuario" (exact casing), generated the error, and was corrected simply changing the casing.
myArray.sample(x)
can also help you to get x random elements from the array.
For Laravel 8 you can also use
Route::redirect('/here', '/there');
//or
Route::permanentRedirect('/here', '/there');
This also works with external URLs
If you don't mind messing with z-index, but you want to avoid adding extra div for overlay, you can use the following approach
/* make sure ::before is positioned relative to .foo */
.foo { position: relative; }
/* overlay */
.foo::before {
content: '';
display: block;
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
background: rgba(0,0,0,0.5);
z-index: 0;
}
/* make sure all elements inside .foo placed above overlay element */
.foo > * { z-index: 1; }
Static variables are not good nor evil. They represent attributes that describe the whole class and not a particular instance. If you need to have a counter for all the instances of a certain class, a static variable would be the right place to hold the value.
Problems appear when you try to use static variables for holding instance related values.
$.each(result, function(key, value) {
console.log(key+ ':' + value);
});
unfortunately we can't use in MySQL after INSERT or UPDATE description, like in Oracle
.neon {
font-size: 20px;
color: #fff;
text-shadow: 0 0 8px yellow;
animation: blinker 6s;
animation-iteration-count: 1;
}
@keyframes blinker {
0% {
opacity: 0.2;
}
19% {
opacity: 0.2;
}
20% {
opacity: 1;
}
21% {
opacity: 1;
}
22% {
opacity: 0.2;
}
23% {
opacity: 0.2;
}
36% {
opacity: 0.2;
}
40% {
opacity: 1;
}
41% {
opacity: 0;
}
42% {
opacity: 1;
}
43% {
opacity: 0.5;
}
50% {
opacity: 1;
}
100% {
opacity: 1;
}
}
I used font-family: "Quicksand", sans-serif;
This is the import of the font (goes in the top of the style.css)
@import url("https://fonts.googleapis.com/css2?family=Quicksand:wght@300&display=swap");
@Column
is not the appropriate annotation. You don't want to store a whole User or Question in a column. You want to create an association between the entities. Start by renaming Questions
to Question
, since an instance represents a single question, and not several ones. Then create the association:
@Entity
@Table(name = "UserAnswer")
public class UserAnswer {
// this entity needs an ID:
@Id
@Column(name="useranswer_id")
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
@ManyToOne
@JoinColumn(name = "user_id")
private User user;
@ManyToOne
@JoinColumn(name = "question_id")
private Question question;
@Column(name = "response")
private String response;
//getter and setter
}
The Hibernate documentation explains that. Read it. And also read the javadoc of the annotations.
Gosha Arinich is right, you should return your <li>
element.
But, nevertheless, you should get nasty red warning in the browser console in this case
Each child in an array or iterator should have a unique "key" prop.
so, you need to add "key" to your list:
this.state.data.map(function(item, i){
console.log('test');
return <li key={i}>Test</li>
})
or drop the console.log()
and do a beautiful oneliner, using es6 arrow functions:
this.state.data.map((item,i) => <li key={i}>Test</li>)
IMPORTANT UPDATE:
The answer above is solving the current problem, but as Sergey mentioned in the comments: using the key depending on the map index is BAD if you want to do some filtering and sorting. In that case use the item.id
if id
already there, or just generate unique ids for it.
you need only Add "pthread" in proprieties=>C/C++ build=>GCC C++ Linker=>Libraries=> top part "Libraries(-l)". thats it
For me none of the packages mentioned above did help.
I finally managed to install lxml
after running:
sudo apt-get install python3.5-dev
if you state a.redLink{color:red;}
then to keep this on hover and such add a.redLink:hover{color:red;}
This will make sure no other hover states will change the color of your links
Try this tag on the pages that use the ActiveX control:
<meta http-equiv="X-UA-Compatible" content="IE=EmulateIE10">
Note: this has to be the very first element in the <head>
section.
This error occurs when you are sending JSON data to server. Maybe in your string you are trying to add new line character by using /n.
If you add / before /n, it should work, you need to escape new line character.
"Hello there //n start coding"
The result should be as following
Hello there
start coding
With the latest version of Picasso (2.71828 at the time of writing this answer), the with
method has been deprecated.
So the correct way would be-
Picasso.get().load("https://<image-url>").into(imageView);
where imageView
is the ImageView you want to load your image into.
I saw answers that provide workaround solutions by hard coding java.exe
location and x86
/ x86_64
architecture string in sdk\tools\android.bat
. Those are quick solutions but did not solve the fundamental issue that I am actually curious of.
The actual problem that I encountered is, the batch script is not able to find another script/jar file and thus is failed to proceed. I could say the script was poorly written.
After I made the following changes in sdk\tools\android.bat
, everything works like a charm.
Specifically, I added %~dp0\
:
set java_exe=
call %~dp0\lib\find_java.bat
if not defined java_exe goto :EOF
...
for /f "delims=" %%a in ('"%java_exe%" -jar %~dp0\lib\archquery.jar') do set swt_path=lib\%%a
Now, try to launch the script and SDK Manager should come out.
p.s. My installation of OS, Java 8 and Android SDK are fresh and I did not do any of the extra configuration.
p.s. You may still need to configure PATH environment variable so that the script could find the suitable java.exe
.
Using jQuery button click
$('#button_id').on('click',function(){
$('#form_id').submit();
});
In this context, stratification means that the train_test_split method returns training and test subsets that have the same proportions of class labels as the input dataset.
Well, I believe that I've solved the password configuration 'issue' - WampServer 2.2 - Windows 7.
The three steps that I did:
In the MySQL console set a new password. To make that: mysqladmin -u root password 'your_password'
In phpMyAdmin
click in users and set the same password to the user root
.
Finally, set your new password in the config.inc.php
. Don't change anything else in this file.
This worked for me. Good luck!
Daniel
You can use the HTML5 <canvas>
for it:
Create a canvas, load your image into it and then use toDataURL()
to get the Base64 representation (actually, it's a data:
URL, but it contains the Base64-encoded image).
Works if the Desktop scaling is set.
public class ScreenCapture
{
[DllImport("user32.dll")]
private static extern IntPtr GetForegroundWindow();
[DllImport("user32.dll", CharSet = CharSet.Auto, ExactSpelling = true)]
public static extern IntPtr GetDesktopWindow();
[StructLayout(LayoutKind.Sequential)]
private struct Rect
{
public int Left;
public int Top;
public int Right;
public int Bottom;
}
[DllImport("user32.dll")]
private static extern IntPtr GetWindowRect(IntPtr hWnd, ref Rect rect);
public static Image CaptureDesktop()
{
return CaptureWindow(GetDesktopWindow());
}
public static Bitmap CaptureActiveWindow()
{
return CaptureWindow(GetForegroundWindow());
}
public static Bitmap CaptureWindow(IntPtr handle)
{
var rect = new Rect();
GetWindowRect(handle, ref rect);
GetScale getScale = new GetScale();
var bounds = new Rectangle(rect.Left, rect.Top, (int)((rect.Right - rect.Left)* getScale.getScalingFactor()), (int)((rect.Bottom - rect.Top )* getScale.getScalingFactor()));
var result = new Bitmap(bounds.Width, bounds.Height);
using (var graphics = Graphics.FromImage(result))
{
graphics.CopyFromScreen(new Point(bounds.Left, bounds.Top), Point.Empty, bounds.Size);
}
return result;
}
}
in shell command:
echo "bar embarassment" | sed "s/\bbar\b/no bar/g"
or:
echo "bar embarassment" | sed "s/\<bar\>/no bar/g"
but if you are in vim, you can only use the later:
:% s/\<old\>/new/g
None of those worked for me. I was trying to clone a directory from a private git server and entered my credentials false and then it wouldn't let me try different credentials on subsequent tries, it just errored out immediately with an authentication error.
What did work was specifying the user name (mike-wise
)in the url like this:
git clone https://[email protected]/someuser/somerepo.git
A possible reason for an empty $_POST
is that the request is not POST
, or not POST
anymore... It may have started out as post, but encountered a 301
or 302
redirect somewhere, which is switched to GET
!
Inspect $_SERVER['REQUEST_METHOD']
to check if this is the case.
See https://stackoverflow.com/a/19422232/109787 for a good discussion of why this should not happen but still does.
If you include $@
in a quoted string with other characters the behavior is very odd when there are multiple arguments, only the first argument is included inside the quotes.
Example:
#!/bin/bash
set -x
bash -c "true foo $@"
Yields:
$ bash test.sh bar baz
+ bash -c 'true foo bar' baz
But assigning to a different variable first:
#!/bin/bash
set -x
args="$@"
bash -c "true foo $args"
Yields:
$ bash test.sh bar baz
+ args='bar baz'
+ bash -c 'true foo bar baz'
You can do this:
create type number_tab is table of number;
select * from table (number_tab(1,2,3,4,5,6));
The column is given the name COLUMN_VALUE by Oracle, so this works too:
select column_value from table (number_tab(1,2,3,4,5,6));
On Ubuntu, you can simply install the chromium-chromedriver
package:
apt install chromium-chromedriver
Be aware that this also installs an outdated Selenium version. To install the latest Selenium:
pip install selenium
Declare the parameter in test.ps1:
Param(
[Parameter(Mandatory=$True,Position=1)]
[string]$input_dir,
[Parameter(Mandatory=$True)]
[string]$output_dir,
[switch]$force = $false
)
Run the script from Run OR Windows Task Scheduler:
powershell.exe -command "& C:\FTP_DATA\test.ps1 -input_dir C:\FTP_DATA\IN -output_dir C:\FTP_DATA\OUT"
or,
powershell.exe -command "& 'C:\FTP DATA\test.ps1' -input_dir 'C:\FTP DATA\IN' -output_dir 'C:\FTP DATA\OUT'"
Here is an updated macro based on the answer given above. This one should allow you to wrap your code even with a return statement.
#define SUPPRESS_PERFORM_SELECTOR_LEAK_WARNING(code) \
_Pragma("clang diagnostic push") \
_Pragma("clang diagnostic ignored \"-Warc-performSelector-leaks\"") \
code; \
_Pragma("clang diagnostic pop") \
SUPPRESS_PERFORM_SELECTOR_LEAK_WARNING(
return [_target performSelector:_action withObject:self]
);
You can't. There isn't a feature in my CPAN client to do such a thing. We were talking about how we might do something like that at this weekend's Perl QA Workshop, but it's generally hard for all the reasons that Ether mentioned.
You can stringify the JSON Object with JSON.stringify(jsonObject) and receive it on controller as String.
In the Controller, you can use the javax.json to convert and manipulate this.
Download and add the .jar to the project libs and import the JsonObject.
To create an json object, you can use
JsonObjectBuilder job = Json.createObjectBuilder();
job.add("header1", foo1);
job.add("header2", foo2);
JsonObject json = job.build();
To read it from String, you can use
JsonReader jr = Json.createReader(new StringReader(jsonString));
JsonObject json = jsonReader.readObject();
jsonReader.close();
To adjust the length of the samples:
set key samplen X
(default is 4)
To adjust the vertical spacing of the samples:
set key spacing X
(default is 1.25)
and (for completeness), to adjust the fontsize:
set key font "<face>,<size>"
(default depends on the terminal)
And of course, all these can be combined into one line:
set key samplen 2 spacing .5 font ",8"
Note that you can also change the position of the key using set key at <position>
or any one of the pre-defined positions (which I'll just defer to help key
at this point)
You don't need jQuery to do this. Embrace the power of JavaScript.
window.location.reload()
It is possible to download all of the UNIX commands compiled for Windows from this GitHub repository: https://github.com/George-Ogden/UNIX
Make sure you remove any java.exe
, javaw.exe
and javaws.exe
from your Windows\System32
folder and if you have an x64 system (Win 7 64 bits) also do the same under Windows\SysWOW64
.
If you can't find them at these locations, try deleting them from C:\ProgramData\Oracle\Java\javapath
.
From man nano
:
-T cols (--tabsize=cols)
Set the size (width) of a tab to cols columns.
The value of cols must be greater than 0. The default value is 8.
-E (--tabstospaces)
Convert typed tabs to spaces.
For example, to set the tab size to 4, replace tabs with spaces, and edit the file "foo.txt", you would run the command:
nano -ET4 foo.txt
From man nanorc
:
set tabsize n
Use a tab size of n columns. The value of n must be greater than 0.
The default value is 8.
set/unset tabstospaces
Convert typed tabs to spaces.
Edit your ~/.nanorc
file (create it if it does not exist), and add those commands to it. For example:
set tabsize 4
set tabstospaces
Nano will use these settings by default whenever it is launched, but command-line flags will override them.
In a bash script, you have several ways to check if the running user is root.
As a warning, do not check if a user is root by using the root
username. Nothing guarantees that the user with ID 0 is called root
. It's a very strong convention that is broadly followed but anybody could rename the superuser another name.
I think the best way when using bash is to use $EUID
, from the man page:
EUID Expands to the effective user ID of the current user, initialized
at shell startup. This variable is readonly.
This is a better way than $UID
which could be changed and not reflect the real user running the script.
if (( $EUID != 0 )); then
echo "Please run as root"
exit
fi
A way I approach that kind of problem is by injecting sudo
in my commands when not run as root. Here is an example:
SUDO=''
if (( $EUID != 0 )); then
SUDO='sudo'
fi
$SUDO a_command
This ways my command is run by root when using the superuser or by sudo
when run by a regular user.
If your script is always to be run by root, simply set the rights accordingly (0500
).
Convert your x-axis data from text to datetime.datetime
, use datetime.strptime
:
>>> from datetime import datetime
>>> datetime.strptime("2012-may-31 19:00", "%Y-%b-%d %H:%M")
datetime.datetime(2012, 5, 31, 19, 0)
This is an example of how to plot data once you have an array of datetimes:
import matplotlib.pyplot as plt
import datetime
import numpy as np
x = np.array([datetime.datetime(2013, 9, 28, i, 0) for i in range(24)])
y = np.random.randint(100, size=x.shape)
plt.plot(x,y)
plt.show()
You can also make a class:
<span class="mychangecolor"> I am in yellow color!!!!!!</span>
then in a css file do:
.mychangecolor{ color:#ff5 /* it changes to yellow */ }
>>> command = "echo a; echo b"
>>> shlex.split(command);
['echo', 'a; echo', 'b']
so, the problem is shlex module do not handle ";"
u can use :
(function () {
var requiredResolution = 10; // ms
var checkInterval = 1000; // ms
var tolerance = 20; // percent
var counter = 0;
var expected = checkInterval / requiredResolution;
//console.log('expected:', expected);
window.setInterval(function () {
counter++;
}, requiredResolution);
window.setInterval(function () {
var deviation = 100 * Math.abs(1 - counter / expected);
// console.log('is:', counter, '(off by', deviation , '%)');
if (deviation > tolerance) {
console.warn('Timer resolution not sufficient!');
}
counter = 0;
}, checkInterval);
})();
You can use the :not
filter selector:
$('foo:not(".someClass")')
Or not()
method:
$('foo').not(".someClass")
More Info:
From my understanding of the question,this can use a fairly straight forward solution.Anyway below is the method i propose ,this method takes in a data table and then using SQL statements to insert into a table in the database.Please mind that my solution is using MySQLConnection and MySqlCommand replace it with SqlConnection and SqlCommand.
public void InsertTableIntoDB_CreditLimitSimple(System.Data.DataTable tblFormat)
{
for (int i = 0; i < tblFormat.Rows.Count; i++)
{
String InsertQuery = string.Empty;
InsertQuery = "INSERT INTO customercredit " +
"(ACCOUNT_CODE,NAME,CURRENCY,CREDIT_LIMIT) " +
"VALUES ('" + tblFormat.Rows[i]["AccountCode"].ToString() + "','" + tblFormat.Rows[i]["Name"].ToString() + "','" + tblFormat.Rows[i]["Currency"].ToString() + "','" + tblFormat.Rows[i]["CreditLimit"].ToString() + "')";
using (MySqlConnection destinationConnection = new MySqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["ConnectionString"].ToString()))
using (var dbcm = new MySqlCommand(InsertQuery, destinationConnection))
{
destinationConnection.Open();
dbcm.ExecuteNonQuery();
}
}
}//CreditLimit
Besides having to escape colons as in the original answer, I have found if the indentation is off you could potentially get the same problem. In one makefile, I had to replace spaces with a tab and that allowed me to get past the error.
Just put the condition into the lambda itself, e.g.
animalMap.entrySet().stream()
.forEach(
pair -> {
if (pair.getValue() != null) {
myMap.put(pair.getKey(), pair.getValue());
} else {
myList.add(pair.getKey());
}
}
);
Of course, this assumes that both collections (myMap
and myList
) are declared and initialized prior to the above piece of code.
Update: using Map.forEach
makes the code shorter, plus more efficient and readable, as Jorn Vernee kindly suggested:
animalMap.forEach(
(key, value) -> {
if (value != null) {
myMap.put(key, value);
} else {
myList.add(key);
}
}
);
In my case, I already was signed in. So I had to sign out
and sign in
again.
In spanish Cerrar Sesion
is sign out
.
The native JavaScript approach -
('<strong>Look just ...</strong>').replace(/</g, '<').replace(/>/g, '>');
Enjoy!
I'm not sure if you want to find duplicate files or just compare two single files. If the latter, the above approach (filecmp) is better, if the former, the following approach is better.
There are lots of duplicate files detection questions here. Assuming they are not very small and that performance is important, you can
Here's is an answer with Python implementations (I prefer the one by nosklo, BTW)
Give this a try:
<!DOCTYPE html>
<html>
<head>
<title>List Test</title>
<style>
li:hover {
cursor: hand; cursor: pointer;
}
</style>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("li").click(function(){
$('#alltext').append($(this).text());
});
});
</script>
</head>
<body>
<h2>List items</h2>
<ol>
<li>Hello</li>
<li>World</li>
<li>Earthlings</li>
</ol>
<form>
<textarea id="alltext"></textarea>
</form>
</body>
</html>
tSql escapes a double quote with another double quote. So if you wanted it to be part of your sql string literal you would do this:
declare @xml xml
set @xml = "<transaction><item value=""hi"" /></transaction>"
If you want to include a quote inside a value in the xml itself, you use an entity, which would look like this:
declare @xml xml
set @xml = "<transaction><item value=""hi "mom" lol"" /></transaction>"
After searching stackoverflow and the web a lot, I've got to conclution that the best way of doing it is like this:
- (BOOL)isEndDateIsSmallerThanCurrent:(NSDate *)checkEndDate
{
NSDate* enddate = checkEndDate;
NSDate* currentdate = [NSDate date];
NSTimeInterval distanceBetweenDates = [enddate timeIntervalSinceDate:currentdate];
double secondsInMinute = 60;
NSInteger secondsBetweenDates = distanceBetweenDates / secondsInMinute;
if (secondsBetweenDates == 0)
return YES;
else if (secondsBetweenDates < 0)
return YES;
else
return NO;
}
You can change it to difference between hours also.
Enjoy!
If you want to compare date with format of dd/MM/yyyy only, you need to add below lines between NSDate* currentdate = [NSDate date];
&& NSTimeInterval distance
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"dd/MM/yyyy"];
[dateFormatter setLocale:[[[NSLocale alloc] initWithLocaleIdentifier:@"en_US"]
autorelease]];
NSString *stringDate = [dateFormatter stringFromDate:[NSDate date]];
currentdate = [dateFormatter dateFromString:stringDate];
We had the same problem while working on an Android application for a customer and I managed to "hack" around this restriction.
I took a look at the Android Source code for the WebView class and spotted a updateZoomButtonsEnabled()
-method which was working with an ZoomButtonsController
-object to enable and disable the zoom controls depending on the current scale of the browser.
I searched for a method to return the ZoomButtonsController
-instance and found the getZoomButtonsController()
-method, that returned this very instance.
Although the method is declared public
, it is not documented in the WebView
-documentation and Eclipse couldn't find it either. So, I tried some reflection on that and created my own WebView
-subclass to override the onTouchEvent()
-method, which triggered the controls.
public class NoZoomControllWebView extends WebView {
private ZoomButtonsController zoom_controll = null;
public NoZoomControllWebView(Context context) {
super(context);
disableControls();
}
public NoZoomControllWebView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
disableControls();
}
public NoZoomControllWebView(Context context, AttributeSet attrs) {
super(context, attrs);
disableControls();
}
/**
* Disable the controls
*/
private void disableControls(){
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.HONEYCOMB) {
// Use the API 11+ calls to disable the controls
this.getSettings().setBuiltInZoomControls(true);
this.getSettings().setDisplayZoomControls(false);
} else {
// Use the reflection magic to make it work on earlier APIs
getControlls();
}
}
/**
* This is where the magic happens :D
*/
private void getControlls() {
try {
Class webview = Class.forName("android.webkit.WebView");
Method method = webview.getMethod("getZoomButtonsController");
zoom_controll = (ZoomButtonsController) method.invoke(this, null);
} catch (Exception e) {
e.printStackTrace();
}
}
@Override
public boolean onTouchEvent(MotionEvent ev) {
super.onTouchEvent(ev);
if (zoom_controll != null){
// Hide the controlls AFTER they where made visible by the default implementation.
zoom_controll.setVisible(false);
}
return true;
}
}
You might want to remove the unnecessary constructors and react on probably on the exceptions.
Although this looks hacky and unreliable, it works back to API Level 4 (Android 1.6).
As @jayellos pointed out in the comments, the private getZoomButtonsController()
-method is no longer existing on Android 4.0.4 and later.
However, it doesn't need to. Using conditional execution, we can check if we're on a device with API Level 11+ and use the exposed functionality (see @Yuttadhammo answer) to hide the controls.
I updated the example code above to do exactly that.
Do NOT loop through all cells!! There is a lot of overhead in communications between worksheets and VBA, for both reading and writing. Looping through all cells will be agonizingly slow. I'm talking hours.
Instead, load an entire sheet at once into a Variant array. In Excel 2003, this takes about 2 seconds (and 250 MB of RAM). Then you can loop through it in no time at all.
In Excel 2007 and later, sheets are about 1000 times larger (1048576 rows × 16384 columns = 17 billion cells, compared to 65536 rows × 256 columns = 17 million in Excel 2003). You will run into an "Out of memory" error if you try to load the whole sheet into a Variant; on my machine I can only load 32 million cells at once. So you have to limit yourself to the range you know has actual data in it, or load the sheet bit by bit, e.g. 30 columns at a time.
Option Explicit
Sub test()
Dim varSheetA As Variant
Dim varSheetB As Variant
Dim strRangeToCheck As String
Dim iRow As Long
Dim iCol As Long
strRangeToCheck = "A1:IV65536"
' If you know the data will only be in a smaller range, reduce the size of the ranges above.
Debug.Print Now
varSheetA = Worksheets("Sheet1").Range(strRangeToCheck)
varSheetB = Worksheets("Sheet2").Range(strRangeToCheck) ' or whatever your other sheet is.
Debug.Print Now
For iRow = LBound(varSheetA, 1) To UBound(varSheetA, 1)
For iCol = LBound(varSheetA, 2) To UBound(varSheetA, 2)
If varSheetA(iRow, iCol) = varSheetB(iRow, iCol) Then
' Cells are identical.
' Do nothing.
Else
' Cells are different.
' Code goes here for whatever it is you want to do.
End If
Next iCol
Next iRow
End Sub
To compare to a sheet in a different workbook, open that workbook and get the sheet as follows:
Set wbkA = Workbooks.Open(filename:="C:\MyBook.xls")
Set varSheetA = wbkA.Worksheets("Sheet1") ' or whatever sheet you need
You can use the following time conversion within SQL like this:
--Convert Time to Integer (Minutes)
DECLARE @timeNow datetime = '14:47'
SELECT DATEDIFF(mi,CONVERT(datetime,'00:00',108), CONVERT(datetime, RIGHT(CONVERT(varchar, @timeNow, 100),7),108))
--Convert Minutes to Time
DECLARE @intTime int = (SELECT DATEDIFF(mi,CONVERT(datetime,'00:00',108), CONVERT(datetime, RIGHT(CONVERT(varchar, @timeNow, 100),7),108)))
SELECT DATEADD(minute, @intTime, '')
Result: 887 <- Time in minutes and 1900-01-01 14:47:00.000 <-- Minutes to time
I had the same issue ,deleting the .settings folder resolved the issue
Update (as 2019):
cd ~/.vim
git clone git://github.com/tpope/vim-haml.git pack/bundle/start/haml
Explanation (from :h pack
ad :h packages
):
runtimepath
. They must be in ~/.vim/pack/whatever/start [you can only change whatever].plugins
dir in runtimepath
are sourced.So this load the plugin on start (hence the name start).
You can also get optional plugin (loaded with :packadd
) if you put them in ~/.vim/pack/bundle/opt
You want to convert html (a byte-like object) into a string using .decode
, e.g. html = response.read().decode('utf-8')
.
According to this, you need to assign a height to the element in which the div is contained in order for 100% height to work. Does that work for you?
Just use x["error_msg"]
. If the property doesn't exist, it returns null
.
You can use this comment in jsp page
<%--your comment --%>
Second way of comment declaration in jsp page you can use the comment of two typ in jsp code
single line comment
<% your code //your comment%>
multiple line comment
<% your code
/**
your another comment
**/
%>
And you can also comment on jsp page from html code for example:
<!-- your commment -->
This sounds like a ClassLoader conflict. I'd bet you have the javax.persistence api 1.x on the classpath somewhere, whereas Spring is trying to access ValidationMode
, which was only introduced in JPA 2.0.
Since you use Maven, do mvn dependency:tree
, find the artifact:
<dependency>
<groupId>javax.persistence</groupId>
<artifactId>persistence-api</artifactId>
<version>1.0</version>
</dependency>
And remove it from your setup. (See Excluding Dependencies)
AFAIK there is no such general distribution for JPA 2, but you can use this Hibernate-specific version:
<dependency>
<groupId>org.hibernate.javax.persistence</groupId>
<artifactId>hibernate-jpa-2.0-api</artifactId>
<version>1.0.1.Final</version>
</dependency>
OK, since that doesn't work, you still seem to have some JPA-1 version in there somewhere. In a test method, add this code:
System.out.println(EntityManager.class.getProtectionDomain()
.getCodeSource()
.getLocation());
See where that points you and get rid of that artifact.
Ahh, now I finally see the problem. Get rid of this:
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jpa</artifactId>
<version>2.0.8</version>
</dependency>
and replace it with
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-orm</artifactId>
<version>3.2.5.RELEASE</version>
</dependency>
On a different note, you should set all test libraries (spring-test, easymock etc.) to
<scope>test</scope>
Useful reference to get file properties using a batch file, included is the last modified time:
FOR %%? IN ("C:\somefile\path\file.txt") DO (
ECHO File Name Only : %%~n?
ECHO File Extension : %%~x?
ECHO Name in 8.3 notation : %%~sn?
ECHO File Attributes : %%~a?
ECHO Located on Drive : %%~d?
ECHO File Size : %%~z?
ECHO Last-Modified Date : %%~t?
ECHO Drive and Path : %%~dp?
ECHO Drive : %%~d?
ECHO Fully Qualified Path : %%~f?
ECHO FQP in 8.3 notation : %%~sf?
ECHO Location in the PATH : %%~dp$PATH:?
)
You can only manually delete properties of objects. Thus:
var container = {};
container.instance = new class();
delete container.instance;
However, this won't work on any other pointers. Therefore:
var container = {};
container.instance = new class();
var pointer = container.instance;
delete pointer; // false ( ie attempt to delete failed )
Furthermore:
delete container.instance; // true ( ie attempt to delete succeeded, but... )
pointer; // class { destroy: function(){} }
So in practice, deletion is only useful for removing object properties themselves, and is not a reliable method for removing the code they point to from memory.
A manually specified destroy
method could unbind any event listeners. Something like:
function class(){
this.properties = { /**/ }
function handler(){ /**/ }
something.addEventListener( 'event', handler, false );
this.destroy = function(){
something.removeEventListener( 'event', handler );
}
}
document.getElementsByName("name")
will get several elements called by same name .
document.getElementsByName("name")[Number]
will get one of them.
document.getElementsByName("name")[Number].value
will get the value of paticular element.
The key of this question is this:
The name of elements is not unique, it is usually used for several input elements in the form.
On the other hand, the id of the element is unique, which is the only definition for a particular element in a html file.
Follow these steps by the method SOAP
From the WSDL file,
create SOAP Request templates for each Request.
Then substitute the values to be passed in code.
POST this data to the service end point using DefaultHttpClient instance.
Get the response stream and finally
Parse the Response Stream using an XML Pull parser.
Just dropping a note here to say that, although using document.write
is highly frowned upon due to performance concerns (synchronous DOM injection and evaluation), there is also no actual 1:1 alternative if you are using document.write
to inject script tags on demand.
There are a lot of great ways to avoid having to do this (e.g. script loaders like RequireJS that manage your dependency chains) but they are more invasive and so are best used throughout the site/application.
All title
nodes with zipcode
or book
node as parent:
Version 1:
//title[parent::zipcode|parent::book]
Version 2:
//bookstore/book/title|//bookstore/city/zipcode/title
Version 3: (results are sorted based on source data rather than the order of book then zipcode)
//title[../../../*[book or magazine] or ../../../../*[city/zipcode]]
or - used within true/false - a Boolean operator in xpath
| - a Union operator in xpath that appends the query to the right of the operator to the result set from the left query.
Here i use the dynamic memory allocation to trim the input string to the function trimStr. First, we find how many non-empty characters exist in the input string. Then, we allocate a character array with that size and taking care of the null terminated character. When we use this function, we need to free the memory inside of main function.
#include<stdio.h>
#include<stdlib.h>
char *trimStr(char *str){
char *tmp = str;
printf("input string %s\n",str);
int nc = 0;
while(*tmp!='\0'){
if (*tmp != ' '){
nc++;
}
tmp++;
}
printf("total nonempty characters are %d\n",nc);
char *trim = NULL;
trim = malloc(sizeof(char)*(nc+1));
if (trim == NULL) return NULL;
tmp = str;
int ne = 0;
while(*tmp!='\0'){
if (*tmp != ' '){
trim[ne] = *tmp;
ne++;
}
tmp++;
}
trim[nc] = '\0';
printf("trimmed string is %s\n",trim);
return trim;
}
int main(void){
char str[] = " s ta ck ove r fl o w ";
char *trim = trimStr(str);
if (trim != NULL )free(trim);
return 0;
}
Very old thread but a simpler take :)
Sub firstBlank(c) 'as letter
MsgBox (c & Split(Range(c & ":" & c).Find("", LookIn:=xlValues).address, "$")(2))
End Sub
Sub firstBlank(c) 'as number
cLet = Split(Cells(1, c).address, "$")(1)
MsgBox (cLet & Split(Range(cLet & ":" & cLet).Find("", LookIn:=xlValues).address, "$")(2))
End Sub
int
is an alias for System.Int32
, as defined in this table:
Built-In Types Table (C# Reference)
Just in case you don't know the type of uploaded image, and you just you need to remove its base64
header:
var imageParts = model.ImageAsString.Split(',').ToList<string>();
//Exclude the header from base64 by taking second element in List.
byte[] Image = Convert.FromBase64String(imageParts[1]);
Use double quotation marks.
string foo = @"this ""word"" is escaped";
This is all you need:
background-repeat: no-repeat;
First you should learn about loops, in this case most suitable is for
loop. For instance let's initialize whole table with increasing values starting with 0:
final int SIZE = 10;
int[] array = new int[SIZE];
for (int i = 0; i < SIZE; i++) {
array[i] = i;
}
Now you can modify it to initialize your table with values as per your assignment.
But what happen if you replace condition i < SIZE
with i < 11
? Well, you will get IndexOutOfBoundException
, as you try to access (at some point) an object under index 10, but the highest index in 10-element array is 9. So you are trying, in other words, to find friend's home with number 11, but there are only 10 houses in the street.
In case of the code you presented, well, there must be more of it, as you can not get this error (exception) from that code.
I prefer This One
document.forms['idOfTheForm'].nameOfTheInputFiled.value;
I solved this simply:
<div ng-repeat="Object in List | filter: (FilterObj.FilterProperty1 ? {'ObjectProperty1': FilterObj.FilterProperty1} : '') | filter:(FilterObj.FilterProperty2 ? {'ObjectProperty2': FilterObj.FilterProperty2} : '')">
Works fine by just adding the: [IgnoreDataMember]
On top of the propertyp, like:
public class UserSettingsModel
{
public string UserName { get; set; }
[IgnoreDataMember]
public DateTime Created { get; set; }
}
This works with ApiController. The code:
[Route("api/Context/UserSettings")]
[HttpGet, HttpPost]
public UserSettingsModel UserSettings()
{
return _contextService.GetUserSettings();
}
You don't need the assignment operator. append returns None.
int no=44;
String bNo=Integer.toString(no,2);//binary output 101100
String oNo=Integer.toString(no,8);//Oct output 54
String hNo=Integer.toString(no,16);//Hex output 2C
String bNo1= Integer.toBinaryString(no);//binary output 101100
String oNo1=Integer.toOctalString(no);//Oct output 54
String hNo1=Integer.toHexString(no);//Hex output 2C
String sBNo="101100";
no=Integer.parseInt(sBNo,2);//binary to int output 44
String sONo="54";
no=Integer.parseInt(sONo,8);//oct to int output 44
String sHNo="2C";
no=Integer.parseInt(sHNo,16);//hex to int output 44
You can actually still use ".css" and apply css transitions to the div being affected. So continue using ".css" and add the below styles to your stylesheet for "#hfont1". Since ".css" allows for a lot more properties than ".animate", this is always my preferred method.
#hfont1 {
-webkit-transition: width 0.4s;
transition: width 0.4s;
}
With Java 8 Streams:
Stream.of(object).collect(Collectors.toList())
or if you need a set:
Stream.of(object).collect(Collectors.toSet())
extension Date {
func isBetween(_ date1: Date, and date2: Date) -> Bool {
return (min(date1, date2) ... max(date1, date2)).contains(self)
}
}
let resultArray = dateArray.filter { $0.dateObj!.isBetween(startDate, and: endDate) }
Now I can't help you with that, I may be able to help with a secondary question beneath it, do I want to use it? If you just want to know of the speed, just ignore my comment.
All I can say is please be very smart about when to use the ternary ? : operator. It can be a blessing as much as a curse for readability.
Ask yourself if you find this easier to read before using it
int x = x == 1 ? x = 1 : x = 1;
if (x == 1)
{
x = 1
}
else
{
x = 2
}
if (x == 1)
x = 1
else
x = 1
Yes It looks stupid to make the code 100% bogus. But that little trick helped me analyse my readability of code. It's the readability of the operator you look at in this sample, and not the content.
It LOOKS clean, but so does the average toilet seat and doorknob
In my experience, which is limited, I have seen very little people actually being able to quickly extradite information required from a ternary operator, avoid unless 100% sure it's better. It's a pain to fix when it's bugged aswell I think
Finally, I got the solution for my problem. The ASP.net account did not appear in the IIS manager, because I didn’t check its checkbox in IIS. To do this in Windows 7 follow the steps:
Now, you will see the ASP.net account on the IIS manager and by default you will see the IIS account. Now, you should move your ASP.net website from “my document” to another place where the IIS have permission to access it (i.e. to another partition on your computer). Now, browse your website from the IIS manager and it should work.
Thanks a lot for Jeff Turner for the solution.
<select id="select">_x000D_
<optgroup label="select one option">_x000D_
<option>one</option> _x000D_
<option>two</option> _x000D_
<option>three</option> _x000D_
<option>four</option> _x000D_
<option>five</option>_x000D_
</optgroup>_x000D_
</select>
_x000D_
It all sounded like a lot of hard work to me, when optgroup gives you what you need - at least I think it does.
a difference:
.cmd files are loaded into memory before being executed. .bat files execute a line, read the next line, execute that line...
you can come across this when you execute a script file and then edit it before it's done executing. bat files will be messed up by this, but cmd files won't.
built on dmark's answer to get the following, which is useful if you want the equiv of sprintf and hopefully will help someone...
def sprint(object):
result = ''
for i in [v for v in dir(object) if not callable(getattr(object, v)) and v[0] != '_']:
result += '\n%s:' % i + str(getattr(object, i, ''))
return result
Try this
COALESCE(NULLIF(Address.COUNTRY,''), 'United States')
This is the class where the connection is established and messages are recieved. Make sure to pair the devices before you run the application. If you want to have a slave/master connection, where each slave can only send messages to the master , and the master can broadcast messages to all slaves. You should only pair the master with each slave , but you shouldn't pair the slaves together.
package com.example.gaby.coordinatorv1;
import java.io.DataInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Set;
import java.util.UUID;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothServerSocket;
import android.bluetooth.BluetoothSocket;
import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.widget.Toast;
public class Piconet {
private final static String TAG = Piconet.class.getSimpleName();
// Name for the SDP record when creating server socket
private static final String PICONET = "ANDROID_PICONET_BLUETOOTH";
private final BluetoothAdapter mBluetoothAdapter;
// String: device address
// BluetoothSocket: socket that represent a bluetooth connection
private HashMap<String, BluetoothSocket> mBtSockets;
// String: device address
// Thread: thread for connection
private HashMap<String, Thread> mBtConnectionThreads;
private ArrayList<UUID> mUuidList;
private ArrayList<String> mBtDeviceAddresses;
private Context context;
private Handler handler = new Handler() {
public void handleMessage(Message msg) {
switch (msg.what) {
case 1:
Toast.makeText(context, msg.getData().getString("msg"), Toast.LENGTH_SHORT).show();
break;
default:
break;
}
};
};
public Piconet(Context context) {
this.context = context;
mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
mBtSockets = new HashMap<String, BluetoothSocket>();
mBtConnectionThreads = new HashMap<String, Thread>();
mUuidList = new ArrayList<UUID>();
mBtDeviceAddresses = new ArrayList<String>();
// Allow up to 7 devices to connect to the server
mUuidList.add(UUID.fromString("a60f35f0-b93a-11de-8a39-08002009c666"));
mUuidList.add(UUID.fromString("54d1cc90-1169-11e2-892e-0800200c9a66"));
mUuidList.add(UUID.fromString("6acffcb0-1169-11e2-892e-0800200c9a66"));
mUuidList.add(UUID.fromString("7b977d20-1169-11e2-892e-0800200c9a66"));
mUuidList.add(UUID.fromString("815473d0-1169-11e2-892e-0800200c9a66"));
mUuidList.add(UUID.fromString("503c7434-bc23-11de-8a39-0800200c9a66"));
mUuidList.add(UUID.fromString("503c7435-bc23-11de-8a39-0800200c9a66"));
Thread connectionProvider = new Thread(new ConnectionProvider());
connectionProvider.start();
}
public void startPiconet() {
Log.d(TAG, " -- Looking devices -- ");
// The devices must be already paired
Set<BluetoothDevice> pairedDevices = mBluetoothAdapter
.getBondedDevices();
if (pairedDevices.size() > 0) {
for (BluetoothDevice device : pairedDevices) {
// X , Y and Z are the Bluetooth name (ID) for each device you want to connect to
if (device != null && (device.getName().equalsIgnoreCase("X") || device.getName().equalsIgnoreCase("Y")
|| device.getName().equalsIgnoreCase("Z") || device.getName().equalsIgnoreCase("M"))) {
Log.d(TAG, " -- Device " + device.getName() + " found --");
BluetoothDevice remoteDevice = mBluetoothAdapter
.getRemoteDevice(device.getAddress());
connect(remoteDevice);
}
}
} else {
Toast.makeText(context, "No paired devices", Toast.LENGTH_SHORT).show();
}
}
private class ConnectionProvider implements Runnable {
@Override
public void run() {
try {
for (int i=0; i<mUuidList.size(); i++) {
BluetoothServerSocket myServerSocket = mBluetoothAdapter
.listenUsingRfcommWithServiceRecord(PICONET, mUuidList.get(i));
Log.d(TAG, " ** Opened connection for uuid " + i + " ** ");
// This is a blocking call and will only return on a
// successful connection or an exception
Log.d(TAG, " ** Waiting connection for socket " + i + " ** ");
BluetoothSocket myBTsocket = myServerSocket.accept();
Log.d(TAG, " ** Socket accept for uuid " + i + " ** ");
try {
// Close the socket now that the
// connection has been made.
myServerSocket.close();
} catch (IOException e) {
Log.e(TAG, " ** IOException when trying to close serverSocket ** ");
}
if (myBTsocket != null) {
String address = myBTsocket.getRemoteDevice().getAddress();
mBtSockets.put(address, myBTsocket);
mBtDeviceAddresses.add(address);
Thread mBtConnectionThread = new Thread(new BluetoohConnection(myBTsocket));
mBtConnectionThread.start();
Log.i(TAG," ** Adding " + address + " in mBtDeviceAddresses ** ");
mBtConnectionThreads.put(address, mBtConnectionThread);
} else {
Log.e(TAG, " ** Can't establish connection ** ");
}
}
} catch (IOException e) {
Log.e(TAG, " ** IOException in ConnectionService:ConnectionProvider ** ", e);
}
}
}
private class BluetoohConnection implements Runnable {
private String address;
private final InputStream mmInStream;
public BluetoohConnection(BluetoothSocket btSocket) {
InputStream tmpIn = null;
try {
tmpIn = new DataInputStream(btSocket.getInputStream());
} catch (IOException e) {
Log.e(TAG, " ** IOException on create InputStream object ** ", e);
}
mmInStream = tmpIn;
}
@Override
public void run() {
byte[] buffer = new byte[1];
String message = "";
while (true) {
try {
int readByte = mmInStream.read();
if (readByte == -1) {
Log.e(TAG, "Discarting message: " + message);
message = "";
continue;
}
buffer[0] = (byte) readByte;
if (readByte == 0) { // see terminateFlag on write method
onReceive(message);
message = "";
} else { // a message has been recieved
message += new String(buffer, 0, 1);
}
} catch (IOException e) {
Log.e(TAG, " ** disconnected ** ", e);
}
mBtDeviceAddresses.remove(address);
mBtSockets.remove(address);
mBtConnectionThreads.remove(address);
}
}
}
/**
* @param receiveMessage
*/
private void onReceive(String receiveMessage) {
if (receiveMessage != null && receiveMessage.length() > 0) {
Log.i(TAG, " $$$$ " + receiveMessage + " $$$$ ");
Bundle bundle = new Bundle();
bundle.putString("msg", receiveMessage);
Message message = new Message();
message.what = 1;
message.setData(bundle);
handler.sendMessage(message);
}
}
/**
* @param device
* @param uuidToTry
* @return
*/
private BluetoothSocket getConnectedSocket(BluetoothDevice device, UUID uuidToTry) {
BluetoothSocket myBtSocket;
try {
myBtSocket = device.createRfcommSocketToServiceRecord(uuidToTry);
myBtSocket.connect();
return myBtSocket;
} catch (IOException e) {
Log.e(TAG, "IOException in getConnectedSocket", e);
}
return null;
}
private void connect(BluetoothDevice device) {
BluetoothSocket myBtSocket = null;
String address = device.getAddress();
BluetoothDevice remoteDevice = mBluetoothAdapter.getRemoteDevice(address);
// Try to get connection through all uuids available
for (int i = 0; i < mUuidList.size() && myBtSocket == null; i++) {
// Try to get the socket 2 times for each uuid of the list
for (int j = 0; j < 2 && myBtSocket == null; j++) {
Log.d(TAG, " ** Trying connection..." + j + " with " + device.getName() + ", uuid " + i + "...** ");
myBtSocket = getConnectedSocket(remoteDevice, mUuidList.get(i));
if (myBtSocket == null) {
try {
Thread.sleep(200);
} catch (InterruptedException e) {
Log.e(TAG, "InterruptedException in connect", e);
}
}
}
}
if (myBtSocket == null) {
Log.e(TAG, " ** Could not connect ** ");
return;
}
Log.d(TAG, " ** Connection established with " + device.getName() +"! ** ");
mBtSockets.put(address, myBtSocket);
mBtDeviceAddresses.add(address);
Thread mBluetoohConnectionThread = new Thread(new BluetoohConnection(myBtSocket));
mBluetoohConnectionThread.start();
mBtConnectionThreads.put(address, mBluetoohConnectionThread);
}
public void bluetoothBroadcastMessage(String message) {
//send message to all except Id
for (int i = 0; i < mBtDeviceAddresses.size(); i++) {
sendMessage(mBtDeviceAddresses.get(i), message);
}
}
private void sendMessage(String destination, String message) {
BluetoothSocket myBsock = mBtSockets.get(destination);
if (myBsock != null) {
try {
OutputStream outStream = myBsock.getOutputStream();
final int pieceSize = 16;
for (int i = 0; i < message.length(); i += pieceSize) {
byte[] send = message.substring(i,
Math.min(message.length(), i + pieceSize)).getBytes();
outStream.write(send);
}
// we put at the end of message a character to sinalize that message
// was finished
byte[] terminateFlag = new byte[1];
terminateFlag[0] = 0; // ascii table value NULL (code 0)
outStream.write(new byte[1]);
} catch (IOException e) {
Log.d(TAG, "line 278", e);
}
}
}
}
Your main activity should be as follow :
package com.example.gaby.coordinatorv1;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
public class MainActivity extends Activity {
private Button discoveryButton;
private Button messageButton;
private Piconet piconet;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
piconet = new Piconet(getApplicationContext());
messageButton = (Button) findViewById(R.id.messageButton);
messageButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
piconet.bluetoothBroadcastMessage("Hello World---*Gaby Bou Tayeh*");
}
});
discoveryButton = (Button) findViewById(R.id.discoveryButton);
discoveryButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
piconet.startPiconet();
}
});
}
}
And here's the XML Layout :
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity" >
<Button
android:id="@+id/discoveryButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Discover"
/>
<Button
android:id="@+id/messageButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Send message"
/>
Do not forget to add the following permissions to your Manifest File :
<uses-permission android:name="android.permission.BLUETOOTH" />
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />
I might be late. Simply add a new field ID in the table with type AutoNumber. This will generate unique IDs and can utilize in Access too
Look at my code, but be aware. I use async/await, because latest Chrome beta can read any es6 code, which gets by TypeScript with compilation. So, you must replace asyns/await by .then()
.
Input change handler:
/**
* @param fileInput
*/
public psdTemplateSelectionHandler (fileInput: any){
let FileList: FileList = fileInput.target.files;
for (let i = 0, length = FileList.length; i < length; i++) {
this.psdTemplates.push(FileList.item(i));
}
this.progressBarVisibility = true;
}
Submit handler:
public async psdTemplateUploadHandler (): Promise<any> {
let result: any;
if (!this.psdTemplates.length) {
return;
}
this.isSubmitted = true;
this.fileUploadService.getObserver()
.subscribe(progress => {
this.uploadProgress = progress;
});
try {
result = await this.fileUploadService.upload(this.uploadRoute, this.psdTemplates);
} catch (error) {
document.write(error)
}
if (!result['images']) {
return;
}
this.saveUploadedTemplatesData(result['images']);
this.redirectService.redirect(this.redirectRoute);
}
FileUploadService. That service also stored uploading progress in progress$ property, and in other places, you can subscribe on it and get new value every 500ms.
import { Component } from 'angular2/core';
import { Injectable } from 'angular2/core';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/share';
@Injectable()
export class FileUploadService {
/**
* @param Observable<number>
*/
private progress$: Observable<number>;
/**
* @type {number}
*/
private progress: number = 0;
private progressObserver: any;
constructor () {
this.progress$ = new Observable(observer => {
this.progressObserver = observer
});
}
/**
* @returns {Observable<number>}
*/
public getObserver (): Observable<number> {
return this.progress$;
}
/**
* Upload files through XMLHttpRequest
*
* @param url
* @param files
* @returns {Promise<T>}
*/
public upload (url: string, files: File[]): Promise<any> {
return new Promise((resolve, reject) => {
let formData: FormData = new FormData(),
xhr: XMLHttpRequest = new XMLHttpRequest();
for (let i = 0; i < files.length; i++) {
formData.append("uploads[]", files[i], files[i].name);
}
xhr.onreadystatechange = () => {
if (xhr.readyState === 4) {
if (xhr.status === 200) {
resolve(JSON.parse(xhr.response));
} else {
reject(xhr.response);
}
}
};
FileUploadService.setUploadUpdateInterval(500);
xhr.upload.onprogress = (event) => {
this.progress = Math.round(event.loaded / event.total * 100);
this.progressObserver.next(this.progress);
};
xhr.open('POST', url, true);
xhr.send(formData);
});
}
/**
* Set interval for frequency with which Observable inside Promise will share data with subscribers.
*
* @param interval
*/
private static setUploadUpdateInterval (interval: number): void {
setInterval(() => {}, interval);
}
}
For fadeIn and fadeOut, only add this after super.onCreate(savedInstanceState) in your new Activity class. You don't need to create something else (No XML, no anim folder, no extra function).
overridePendingTransition(R.anim.abc_fade_in,R.anim.abc_fade_out);
It's possible that you've run out of memory or some space elsewhere and it prompted the system to mount an overflow filesystem, and for whatever reason, it's not going away.
Try unmounting the overflow partition:
umount /tmp
or
umount overflow
strong is the default. An object remains “alive” as long as there is a strong pointer to it.
weak specifies a reference that does not keep the referenced object alive. A weak reference is set to nil when there are no strong references to the object.
This is slightly an edge case but I think it can add some value to the other answers.
If you add more details to the graph (say an annotation or a line) you'll soon discover that it is relevant when you call legend on the axis: if you call it at the bottom of the script it will capture different handles for the legend elements, messing everything.
For instance the following script:
df = pd.DataFrame({'A':26, 'B':20}, index=['N'])
ax = df.plot(kind='bar')
ax.hlines(23, -.5,.5, linestyles='dashed')
ax.annotate('average',(-0.4,23.5))
ax.legend(["AAA", "BBB"]); #quickfix: move this at the third line
Will give you this figure, which is wrong:
While this a toy example which can be easily fixed by changing the order of the commands, sometimes you'll need to modify the legend after several operations and hence the next method will give you more flexibility. Here for instance I've also changed the fontsize and position of the legend:
df = pd.DataFrame({'A':26, 'B':20}, index=['N'])
ax = df.plot(kind='bar')
ax.hlines(23, -.5,.5, linestyles='dashed')
ax.annotate('average',(-0.4,23.5))
ax.legend(["AAA", "BBB"]);
# do potentially more stuff here
h,l = ax.get_legend_handles_labels()
ax.legend(h[:2],["AAA", "BBB"], loc=3, fontsize=12)
This is what you'll get:
You can think of serialization as the process of converting an object instance into a sequence of bytes (which may be binary or not depending on the implementation).
It is very useful when you want to transmit one object data across the network, for instance from one JVM to another.
In Java, the serialization mechanism is built into the platform, but you need to implement the Serializable interface to make an object serializable.
You can also prevent some data in your object from being serialized by marking the attribute as transient.
Finally you can override the default mechanism, and provide your own; this may be suitable in some special cases. To do this, you use one of the hidden features in java.
It is important to notice that what gets serialized is the "value" of the object, or the contents, and not the class definition. Thus methods are not serialized.
Here is a very basic sample with comments to facilitate its reading:
import java.io.*;
import java.util.*;
// This class implements "Serializable" to let the system know
// it's ok to do it. You as programmer are aware of that.
public class SerializationSample implements Serializable {
// These attributes conform the "value" of the object.
// These two will be serialized;
private String aString = "The value of that string";
private int someInteger = 0;
// But this won't since it is marked as transient.
private transient List<File> unInterestingLongLongList;
// Main method to test.
public static void main( String [] args ) throws IOException {
// Create a sample object, that contains the default values.
SerializationSample instance = new SerializationSample();
// The "ObjectOutputStream" class has the default
// definition to serialize an object.
ObjectOutputStream oos = new ObjectOutputStream(
// By using "FileOutputStream" we will
// Write it to a File in the file system
// It could have been a Socket to another
// machine, a database, an in memory array, etc.
new FileOutputStream(new File("o.ser")));
// do the magic
oos.writeObject( instance );
// close the writing.
oos.close();
}
}
When we run this program, the file "o.ser" is created and we can see what happened behind.
If we change the value of: someInteger to, for example Integer.MAX_VALUE, we may compare the output to see what the difference is.
Here's a screenshot showing precisely that difference:
Can you spot the differences? ;)
There is an additional relevant field in Java serialization: The serialversionUID but I guess this is already too long to cover it.
Referred link has correct answer, but there are written some libraries to make your work easy.
So don't write all code again, just use any of these library and get your work done in little time.
Just a simple solution that works for me. I don't know why you need the Bash script which basically does a useless step (am I wrong ?)
import os
os.system('/bin/bash --rcfile flask/bin/activate')
Which basically does what you need:
[hellsing@silence Foundation]$ python2.7 pythonvenv.py
(flask)[hellsing@silence Foundation]$
Then instead of deactivating the virtual environment, just Ctrl + D or exit. Is that a possible solution or isn't that what you wanted?
I think the best is to check if fragment is added before calling method in fragment. Do something like this to avoid null exception.
ExampleFragment fragment = (ExampleFragment) getFragmentManager().findFragmentById(R.id.example_fragment);
if(fragment.isAdded()){
fragment.<specific_function_name>();
}
You are using the wrong type. The Array(...)
function returns a Variant
, not a String
.
Thus, in the Declaration section of your module (it does not need to be a different module!), you define
Public colHeader As Variant
and somewhere at the beginning of your program code (for example, in the Workbook_Open
event) you initialize it with
colHeader = Array("A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L")
Another (simple) alternative would be to create a function that returns the array, e.g. something like
Public Function GetHeaders() As Variant
GetHeaders = Array("A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L")
End Function
This has the advantage that you do not need to initialize the global variable and the drawback that the array is created again on every function call.
Use array-like fields:
<input name="name_for_the_items[]"/>
You can loop through the fields:
foreach($_POST['name_for_the_items'] as $item)
{
//do something with $item
}
Looks like you are missing a leading slash. Perhaps try:
Scanner s = new Scanner(new File("/home/me/java/ex.txt"));
(as to where it looks for files by default, it is where the JVM is run from for relative paths like the one you have in your question)
The official language specification for XPath 2.0 on W3.org details that the language does indeed support if statements. See Section 3.8 Conditional Expressions, in particular. Along with the syntax format and explanation, it gives the following example:
if ($widget1/unit-cost < $widget2/unit-cost)
then $widget1
else $widget2
This would suggest that you shouldn't have brackets surrounding your expressions (otherwise the syntax looks correct). I'm not wholly confident, but it's surely worth a try. So you'll want to change your query to look like this:
if (fn:ends-with(//div [@id='head']/text(),': '))
then fn:substring-before(//div [@id='head']/text(),': ')
else //div [@id='head']/text()
I do strongly suspect this may fix it however, as the fact that your XPath engine seems to be trying to interpret if
as a function, where it is in fact a special construct of the language.
Finally, to point out the obvious, insure that your XPath engine does in fact support XPath 2.0 (as opposed to an earlier version)! I don't believe conditional expressions are part of previous versions of XPath.
Android seekbar custom material style, for other seekbar customizations http://www.zoftino.com/android-seekbar-and-custom-seekbar-examples
<style name="MySeekBar" parent="Widget.AppCompat.SeekBar">
<item name="android:progressBackgroundTint">#f4511e</item>
<item name="android:progressTint">#388e3c</item>
<item name="android:colorControlActivated">#c51162</item>
</style>
I had the same problem truying to connect from linux server to EC2, you have two make sure about to things that "ALL ICMP" is added from EC2 as shown above and that alone won't work, you have to update Ansible to newest version 2.4, it did not work with my previous version 2.2.
Here's some advice from someone with an environment where we have folders containing tens of millions of files.
To answer your question more directly: If you're looking at 100K entries, no worries. Go knock yourself out. If you're looking at tens of millions of entries, then either:
a) Make plans to sub-divide them into sub-folders (e.g., lets say you have 100M files. It's better to store them in 1000 folders so that you only have 100,000 files per folder than to store them into 1 big folder. This will create 1000 folder indices instead of a single big one that's more likely to hit the max # of fragments limit or
b) Make plans to run contig.exe on a regular basis to keep your big folder's index defragmented.
Read below only if you're bored.
The actual limit isn't on the # of fragment, but on the number of records of the data segment that stores the pointers to the fragment.
So what you have is a data segment that stores pointers to the fragments of the directory data. The directory data stores information about the sub-directories & sub-files that the directory supposedly stored. Actually, a directory doesn't "store" anything. It's just a tracking and presentation feature that presents the illusion of hierarchy to the user since the storage medium itself is linear.
Its Working Properly
EditText et_mobile= (EditText) findViewById(R.id.edittxt);
et_mobile.setOnFocusChangeListener(new OnFocusChangeListener() {
@Override
public void onFocusChange(View v, boolean hasFocus) {
if (!hasFocus) {
// code to execute when EditText loses focus
if (et_mobile.getText().toString().trim().length() == 0) {
CommonMethod.showAlert("Please enter name", FeedbackSubmtActivity.this);
}
}
}
});
public static void showAlert(String message, Activity context) {
final AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setMessage(message).setCancelable(false)
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
}
});
try {
builder.show();
} catch (Exception e) {
e.printStackTrace();
}
}
function deleteEmpty(obj){
for(var k in obj)
if(k == "children"){
if(obj[k]){
deleteEmpty(obj[k]);
}else{
delete obj.children;
}
}
}
for(var i=0; i< a.children.length; i++){
deleteEmpty(a.children[i])
}
If you don't want to commit, or want to commit later (commit message will still be prepared for you, which you can also edit):
git revert -n <commit>
I think this should work:
#include <time.h>
clock_t start = clock(), diff;
ProcessIntenseFunction();
diff = clock() - start;
int msec = diff * 1000 / CLOCKS_PER_SEC;
printf("Time taken %d seconds %d milliseconds", msec/1000, msec%1000);
Probably the author won't need my answer anymore. Still, for sake of completeness i feel other users might find it useful. The best and most simple solution is to use $(window).load()
inside the body of the returned function. (alternatively you can use document.ready
. It really depends if you need all the images or not).
Using $timeout
in my humble opinion is a very weak option and may fail in some cases.
Here is the complete code i'd use:
.directive('directiveExample', function(){
return {
restrict: 'A',
link: function($scope, $elem, attrs){
$(window).load(function() {
//...JS here...
});
}
}
});
I agree with @aaronasterling's answer. However, if you want a non-binary string that you can cast into an int, then you can use the canonical algorithm:
def decToBin(n):
if n==0: return ''
else:
return decToBin(n/2) + str(n%2)
Use ord
when reading reading bytes:
byte_binary = bin(ord(f.read(1))) # Add [2:] to remove the "0b" prefix
Or
Using str.format()
:
'{:08b}'.format(ord(f.read(1)))
function my_get_tags_sitemap(){
if ( !function_exists('wp_tag_cloud') || get_option('cb2_noposttags')) return;
$unlinkTags = get_option('cb2_unlinkTags');
echo '<div class="tags"><h2>Tags</h2>';
$ret = []; // here you need to add array which you call inside implode function
if($unlinkTags)
{
$tags = get_tags();
foreach ($tags as $tag){
$ret[]= $tag->name;
}
//ERROR OCCURS HERE
echo implode(', ', $ret);
}
else
{
wp_tag_cloud('separator=, &smallest=11&largest=11');
}
echo '</div>';
}
The other answers goes deep and give great explanations. For those who look for quick answer,
$a ?: 'fallback'
is $a ? $a : 'fallback'
while
$a ?? 'fallback'
is $a = isset($a) ? $a : 'fallback'
The main difference would be when the left operator is either:
0
, ''
, false
, []
, ...) Because cron is "stateless", it cannot accurately express "frequencies", only "patterns" which it (apparently) continuously matches against the current time.
Rephrasing your question makes this more obvious: "is it possible to run a cronjob at 00:01am every night except skip nights when it had run within 2 nights?" When cron is comparing the current time to job request time patterns, there's no way cron can know if it ran your job in the past.
(it certainly is possible to write a stateful cron that records past jobs and thus includes patterns for matching against this state, but that's not the standard cron included in most operating systems. Such a system would get complicated by requiring the introduction of the concept of when such patterns "reset". For example, is the pattern reset when the time is changed (i.e. the crontab entry is revised)? Look to your favorite calendar app to see how complicated it can get to express Repeating patterns of scheduled events, and note that they don't have the reset problem because the starting calendar event has a natural "start" a/k/a "reset" date. Try rescheduling an every-other-week recurring calendar event to postpone by a week, over christmas for example. Usually you have to terminate that recurring event and restart a completely new one; this illustrates the limited expressivity of how even complicated calendar apps represent repeating patterns. And of course Calendars have a lot of state-- each individual event can be deleted or rescheduled independently [in most calendar apps]).
Further, you probably want to do your job every 3rd night if successful, but if the last one failed, to try again immediately, perhaps the next night (not wait 3 more days) or even sooner, like an hour later (but stop retrying upon morning's arrival). Clearly, cron couldn't possibly know if your job succeeded and the pattern can't also express an alternate more frequent "retry" schedule.
ANYWAY-- You can do what you want yourself. Write a script, tell cron to run it nightly at 00:01am. This script could check the timestamp of something* which records the "last run", and if it was >3 days ago**, perform the job and reset the "last run" timestamp.
(*that timestamped indicator is a bit of persisted state which you can manipulate and examine, but which cron cannot)
**be careful with time arithmetic if you're using human-readable clock time-- twice a year, some days have 23 or 25 hours in their day, and 02:00-02:59 occurs twice in one day or not at all. Use UTC to avoid this.
If you use the $.ajax
function, you can simply add the csrf
token in the data body:
$.ajax({
data: {
somedata: 'somedata',
moredata: 'moredata',
csrfmiddlewaretoken: '{{ csrf_token }}'
},
Take a look at the Decimal module
Decimal “is based on a floating-point model which was designed with people in mind, and necessarily has a paramount guiding principle – computers must provide an arithmetic that works in the same way as the arithmetic that people learn at school.” – excerpt from the decimal arithmetic specification.
and
Decimal numbers can be represented exactly. In contrast, numbers like 1.1 and 2.2 do not have an exact representations in binary floating point. End users typically would not expect 1.1 + 2.2 to display as 3.3000000000000003 as it does with binary floating point.
Decimal provides the kind of operations that make it easy to write apps that require floating point operations and also need to present those results in a human readable format, e.g., accounting.
Java Primitive Specializations Generator supports /* with */
, /* define */
and /* if */ ... /* elif */ ... /* endif */
blocks which allow to do some kind of macro generation in Java code, similar to java-comment-preprocessor mentioned in this answer.
JPSG has Maven and Gradle plugins.
A really simple line of Javascript can get the "non-taggy" text in all main browsers...
var myElement = document.getElementById('anyElementId');
var myText = (myElement.innerText || myElement.textContent);
jQuery might be missing.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.0/jquery.min.js"></script>
If you know the key which you unset then put directly by comma separated
unset($attr['placeholder'], $attr['autocomplete']);
You can deploy an images folder as a separate webapp and define the location of that folder to be anywhere in the file system.
Create a Context element in an XML file in the directory $CATALINA_HOME/conf/[enginename]/[hostname]/
where enginename might be 'Catalina' and hostname might be 'localhost'.
Name the file based on the path URL you want the images to be viewed from, so if your webapp has path 'blog', you might name the XML file blog#images.xml
and so that your images would be visible at example.com/blog/images/
The content of the XML file should be <Context docBase="/filesystem/path/to/images"/>
Be careful not to undeploy this webapp, as that could delete all your images!
You need the "correlation id" (the "AS SS" thingy) on the sub-select to reference the fields in the "ON" condition. The id's assigned inside the sub select are not usable in the join.
SELECT
cs.CUSID
,dp.DEPID
FROM
CUSTMR cs
LEFT OUTER JOIN (
SELECT
DEPID
,DEPNAME
FROM
DEPRMNT
WHERE
dp.DEPADDRESS = 'TOKYO'
) ss
ON (
ss.DEPID = cs.CUSID
AND ss.DEPNAME = cs.CUSTNAME
)
WHERE
cs.CUSID != ''
myArray = [_x000D_
{group: "one", color: "red"},_x000D_
{group: "two", color: "blue"},_x000D_
{group: "one", color: "green"},_x000D_
{group: "one", color: "black"}_x000D_
];_x000D_
_x000D_
_x000D_
let group = myArray.map((item)=> item.group ).filter((item, i, ar) => ar.indexOf(item) === i).sort((a, b)=> a - b).map(item=>{_x000D_
let new_list = myArray.filter(itm => itm.group == item).map(itm=>itm.color);_x000D_
return {group:item,color:new_list}_x000D_
});_x000D_
console.log(group);
_x000D_
you can use the package manager to query installed version of gitlab-ce. if it happens to be debian or ubuntu, like this:
dpkg -l | grep gitlab-ce | tr -s [:space:] | cut -d" " -f3
should work similarly with other distributions, assuming you used package manager to install.
I do it like this:
CREATE UNIQUE INDEX index_name ON TableName (Column1, Column2, Column3);
My convention for a unique index_name
is TableName_Column1_Column2_Column3_uindex
.
$("#filter").click(function(){
//Put your code here
});
My issue was with multiple targets. I solved it with below links: configure pod file right way and fix build settings
Hope some one will find it helpful.
In the hope of providing clarity over common cinfusion...
I have written many python <--> bash <--> elfbin toolchains and the proper way to see it is such as this:
Each process (originator) has a state of the environment inherited from whatever invoked it. Any change remains lokal to that process. Transfering an environment state is a function by itself and runs in two directions, each with it's own caveats. The most common thing is to modify environment before running a sub-process. To go down to the metal, look at the exec() - call in C. There is a variant that takes a pointer to environment data. This is the only actually supported transfer of environment in typical OS'es.
Shell scripts will create a state to pass when running children when you do an export. Otherwise it just uses that which it got in the first place.
In all other cases it will be some generic mechanism used to pass a set of data to allow the calling process itself to update it's environment based on the result of the child-processes output.
Ex:
ENVUPDATE = $(CMD_THAT_OUTPUTS_KEYVAL_LISTS)
echo $ENVUPDATE > $TMPFILE
source $TMPFILE
The same can of course be done using json, xml or other things as long as you have the tools to interpret and apply.
The need for this may be (50% chance) a sign of misconstruing the basic primitives and that you need a better config or parameter interchange in your solution.....
Oh, in python I would do something like... (need improvement depending on your situation)
import re
RE_KV=re.compile('([a-z][\w]*)\s*=\s*(.*)')
OUTPUT=RunSomething(...) (Assuming 'k1=v1 k2=v2')
for kv in OUTPUT.split(' ')
try:
k,v=RE_KV.match(kv).groups()
os.environ[k]=str(v)
except:
#The not a property case...
pass
Use the RIGHT()
function: http://msdn.microsoft.com/en-us/library/ms177532(v=sql.105).aspx
SELECT RIGHT( '1234567890', 4 ); -- returns '7890'
I'm not super fond of the interval thingies. When I want to defer jquery, or anything actually, it usually goes something like this.
Start with:
<html>
<head>
<script>var $d=[];var $=(n)=>{$d.push(n)}</script>
</head>
Then:
<body>
<div id="thediv"></div>
<script>
$(function(){
$('#thediv').html('thecode');
});
</script>
<script src="http://code.jquery.com/jquery-3.2.1.min.js" type="text/javascript"></script>
Then finally:
<script>for(var f in $d){$d[f]();}</script>
</body>
<html>
Or the less mind-boggling version:
<script>var def=[];function defer(n){def.push(n)}</script>
<script>
defer(function(){
$('#thediv').html('thecode');
});
</script>
<script src="http://code.jquery.com/jquery-3.2.1.min.js" type="text/javascript"></script>
<script>for(var f in def){def[f]();}</script>
And in the case of async you could execute the pushed functions on jquery onload.
<script async onload="for(var f in def){def[f]();}"
src="jquery.min.js" type="text/javascript"></script>
Alternatively:
function loadscript(src, callback){
var script = document.createElement('script');
script.src = src
script.async = true;
script.onload = callback;
document.body.appendChild(script);
};
loadscript("jquery.min", function(){for(var f in def){def[f]();}});
Yet another approach by using lambda above java 8
Arrays.stream(new Integer[nodelist.size()]).map(e ->
Integer.MAX_VALUE).toArray(Integer[]::new);
A POST request can include a query string, however normally it doesn't - a standard HTML form with a POST action will not normally include a query string for example.
go to python/scripts folder, open a command window to this path, type the following:
C:\python34\scripts> python -m pip install pygame
To test it, open python IDE and type
import pygame
print (pygame.ver)
It worked for me...
I couldn't get any of the above solutions to work. However, I found a hack:
body {_x000D_
background-color: #ccc;_x000D_
}_x000D_
_x000D_
.container {_x000D_
width: 300px;_x000D_
background-color: white;_x000D_
}_x000D_
_x000D_
table {_x000D_
width: 100%;_x000D_
border-collapse: collapse;_x000D_
}_x000D_
_x000D_
td {_x000D_
border: 1px solid black;_x000D_
}_x000D_
_x000D_
/* try removing the "hack" below to see how the table overflows the .body */_x000D_
.hack1 {_x000D_
display: table;_x000D_
table-layout: fixed;_x000D_
width: 100%;_x000D_
}_x000D_
_x000D_
.hack2 {_x000D_
display: table-cell;_x000D_
overflow-x: auto;_x000D_
width: 100%;_x000D_
}
_x000D_
<div class="container">_x000D_
_x000D_
<div class="hack1">_x000D_
<div class="hack2">_x000D_
_x000D_
<table>_x000D_
<tr>_x000D_
<td>table or other arbitrary content</td>_x000D_
<td>that will cause your page to stretch</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>uncontrollably</td>_x000D_
<td>xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx</td>_x000D_
</tr>_x000D_
</table>_x000D_
_x000D_
</div>_x000D_
</div>_x000D_
_x000D_
</div>
_x000D_
<!DOCTYPE html>
<html>
<body>
<span style="white-space:pre-wrap;">
Line no one
Line no two
And many more line.
This is Manik
End of Line
</span>
</body>
</html>
UCanAccess is a pure Java JDBC driver that allows us to read from and write to Access databases without using ODBC. It uses two other packages, Jackcess and HSQLDB, to perform these tasks. The following is a brief overview of how to get it set up.
If your project uses Maven you can simply include UCanAccess via the following coordinates:
groupId: net.sf.ucanaccess
artifactId: ucanaccess
The following is an excerpt from pom.xml
, you may need to update the <version>
to get the most recent release:
<dependencies>
<dependency>
<groupId>net.sf.ucanaccess</groupId>
<artifactId>ucanaccess</artifactId>
<version>4.0.4</version>
</dependency>
</dependencies>
As mentioned above, UCanAccess requires Jackcess and HSQLDB. Jackcess in turn has its own dependencies. So to use UCanAccess you will need to include the following components:
UCanAccess (ucanaccess-x.x.x.jar)
HSQLDB (hsqldb.jar, version 2.2.5 or newer)
Jackcess (jackcess-2.x.x.jar)
commons-lang (commons-lang-2.6.jar, or newer 2.x version)
commons-logging (commons-logging-1.1.1.jar, or newer 1.x version)
Fortunately, UCanAccess includes all of the required JAR files in its distribution file. When you unzip it you will see something like
ucanaccess-4.0.1.jar
/lib/
commons-lang-2.6.jar
commons-logging-1.1.1.jar
hsqldb.jar
jackcess-2.1.6.jar
All you need to do is add all five (5) JARs to your project.
NOTE: Do not add
loader/ucanload.jar
to your build path if you are adding the other five (5) JAR files. TheUcanloadDriver
class is only used in special circumstances and requires a different setup. See the related answer here for details.
Eclipse: Right-click the project in Package Explorer and choose Build Path > Configure Build Path...
. Click the "Add External JARs..." button to add each of the five (5) JARs. When you are finished your Java Build Path should look something like this
NetBeans: Expand the tree view for your project, right-click the "Libraries" folder and choose "Add JAR/Folder...", then browse to the JAR file.
After adding all five (5) JAR files the "Libraries" folder should look something like this:
IntelliJ IDEA: Choose File > Project Structure...
from the main menu. In the "Libraries" pane click the "Add" (+
) button and add the five (5) JAR files. Once that is done the project should look something like this:
Now "U Can Access" data in .accdb and .mdb files using code like this
// assumes...
// import java.sql.*;
Connection conn=DriverManager.getConnection(
"jdbc:ucanaccess://C:/__tmp/test/zzz.accdb");
Statement s = conn.createStatement();
ResultSet rs = s.executeQuery("SELECT [LastName] FROM [Clients]");
while (rs.next()) {
System.out.println(rs.getString(1));
}
At the time of writing this Q&A I had no involvement in or affiliation with the UCanAccess project; I just used it. I have since become a contributor to the project.
1st: goto the drive where your eclipse reside and goto sdk and platform tool in my case C:\adt-bundle-windows-x86_64-20140702\sdk\platform-tools
2nd:copy that address for ease of access
3:open command prompt win+r and type cmd hit enter
4:paste the address in cmd and hit enter thats all
You can transform array of strings to array of numbers in one line:
const arrayOfNumbers = arrayOfStrings.map(e => +e);
Assuming we're talking SQL Server DateTime
Note: BETWEEN includes both ends of the range, so technically this pattern will be wrong:
errorDate BETWEEN '12/20/2008' AND '12/21/2008'
My preferred method for a time range like that is:
'20081220' <= errorDate AND errordate < '20081221'
Works with common indexes (range scan, SARGable, functionless) and correctly clips off midnight of the next day, without relying on SQL Server's time granularity (e.g. 23:59:59.997)
The 403 error may also be caused by an encrypted file system, e.g. a symlink to an encrypted home folder.
If your symlink points into the encrypted folder, the apache user (e.g. www-data) cannot access the contents, even if apache and file/folder permissions are set correctly. Access of the www-data user can be tested with such a call:
sudo -u www-data ls -l /var/www/html/<your symlink>/
There are workarounds/solutions to this, e.g. adding the www-data user to your private group (exposes the encrypted data to the web user) or by setting up an unencrypted rsynced folder (probably rather secure). I for myself will probably go for an rsync solution during development.
https://askubuntu.com/questions/633625/public-folder-in-an-encrypted-home-directory
A convenient tool for my purposes is lsyncd. This allows me to work directly in my encrypted home folder and being able to see changes almost instantly in the apache web page. The synchronization is triggered by changes in the file system, calling an rsync. As I'm only working on rather small web pages and scripts, the syncing is very fast. I decided to use a short delay of 1 second before the rsync is started, even though it is possible to set a delay of 0 seconds.
Installing lsyncd (in Ubuntu):
sudo apt-get install lsyncd
Starting the background service:
lsyncd -delay 1 -rsync /home/<me>/<work folder>/ /var/www/html/<web folder>/
DECLARE @min INT = 3;
DECLARE @max INT = 6;
SELECT @min + ROUND(RAND() * (@max - @min), 0);
Step by step
DECLARE @min INT = 3;
DECLARE @max INT = 6;
DECLARE @rand DECIMAL(19,4) = RAND();
DECLARE @difference INT = @max - @min;
DECLARE @chunk INT = ROUND(@rand * @difference, 0);
DECLARE @result INT = @min + @chunk;
SELECT @result;
Note that a user-defined function thus not allow the use of RAND(). A workaround for this (source: http://blog.sqlauthority.com/2012/11/20/sql-server-using-rand-in-user-defined-functions-udf/) is to create a view first.
CREATE VIEW [dbo].[vw_RandomSeed]
AS
SELECT RAND() AS seed
and then create the random function
CREATE FUNCTION udf_RandomNumberBetween
(
@min INT,
@max INT
)
RETURNS INT
AS
BEGIN
RETURN @min + ROUND((SELECT TOP 1 seed FROM vw_RandomSeed) * (@max - @min), 0);
END
You need text()
or html()
for label not val()
The function should not be called for label instead it is used to get values of input like text or checkbox etc.
Change
value = $("#telefon").val();
To
value = $("#telefon").text();
Lazy exceptions occur when you fetch an object typically containing a collection which is lazily loaded, and try to access that collection.
You can avoid this problem by
Hibernate.initialize(obj);
Fetch profiles
to select lazy/non-lazy fetching runtimeFurther I would recommend looking at the related
links to your right where this question has been answered many times before. Also see Hibernate lazy-load application design.
http://connect.microsoft.com/VisualStudio/feedback/ViewFeedback.aspx?FeedbackID=367077
Problem Statement
It's possible to write LINQ to SQL that gets all rows that have either null or an empty string in a given field, but it's not possible to use string.IsNullOrEmpty to do it, even though many other string methods map to LINQ to SQL.
Proposed Solution
Allow string.IsNullOrEmpty in a LINQ to SQL where clause so that these two queries have the same result:
var fieldNullOrEmpty =
from item in db.SomeTable
where item.SomeField == null || item.SomeField.Equals(string.Empty)
select item;
var fieldNullOrEmpty2 =
from item in db.SomeTable
where string.IsNullOrEmpty(item.SomeField)
select item;
Other Reading:
1. DevArt
2. Dervalp.com
3. StackOverflow Post
INSERT INTO action_2_members (campaign_id, mobile, vote, vote_date)
SELECT campaign_id, from_number, received_msg, date_received
FROM `received_txts`
WHERE `campaign_id` = '8'
You can run ruby commands in one line with the -e
flag:
ruby -e "puts 'hi'"
Check the man page for more information.
There are lots of different things about static and dynamic languages. For me, the main difference is that in dynamic languages the variables don't have fixed types; instead, the types are tied to values. Because of this, the exact code that gets executed is undetermined until runtime.
In early or naïve implementations this is a huge performance drag, but modern JITs get tantalizingly close to the best you can get with optimizing static compilers. (in some fringe cases, even better than that).
As Tyler points out, there's no way to do what you require "directly and reliably", since a given FD may correspond to 0 filenames (in various cases) or > 1 (multiple "hard links" is how the latter situation is generally described). If you do still need the functionality with all the limitations (on speed AND on the possibility of getting 0, 2, ... results rather than 1), here's how you can do it: first, fstat the FD -- this tells you, in the resulting struct stat
, what device the file lives on, how many hard links it has, whether it's a special file, etc. This may already answer your question -- e.g. if 0 hard links you will KNOW there is in fact no corresponding filename on disk.
If the stats give you hope, then you have to "walk the tree" of directories on the relevant device until you find all the hard links (or just the first one, if you don't need more than one and any one will do). For that purpose, you use readdir (and opendir &c of course) recursively opening subdirectories until you find in a struct dirent
thus received the same inode number you had in the original struct stat
(at which time if you want the whole path, rather than just the name, you'll need to walk the chain of directories backwards to reconstruct it).
If this general approach is acceptable, but you need more detailed C code, let us know, it won't be hard to write (though I'd rather not write it if it's useless, i.e. you cannot withstand the inevitably slow performance or the possibility of getting != 1 result for the purposes of your application;-).
To angular version 4, you can use this:
this.heroForm.reset();
But, you could need a initial value like:
ngOnChanges() {
this.heroForm.reset({
name: this.hero.name, //Or '' to empty initial value.
address: this.hero.addresses[0] || new Address()
});
}
It is important to resolve null problem in your object reference.
reference link, Search for "reset the form flags".
All executable files from Visual Studio should be located in the debug folder of your project, e.g:
Visual Studio Directory: c:\users\me\documents\visual studio
Then the project which was called 'hello world' would be in the directory:
c:\users\me\documents\visual studio\hello world
And your exe would be located in:
c:\users\me\documents\visual studio\hello world\Debug\hello world.exe
Note the exe being named the same as the project.
Otherwise, you could publish it to a specified folder of your choice which comes with an installation, which would be good if you wanted to distribute it quickly
EDIT:
Everytime you build your project in VS, the exe is updated with the new one according to the code (as long as it builds without errors). When you publish it, you can choose the location, aswell as other factors, and the setup exe will be in that location, aswell as some manifest files and other files about the project.
I have found that from version 1.8.4 on, the libraries can be found in ~/Arduino/Libraries. Hope this helps anyone else.
This happened to me when I tried to git pull
. Some analysis showed that somebody had commited with root in the past, thereby creating some objects with root ownership in .git/objects
.
So I ran
cd <repo>
la .git/objects/
and that showed root
ownership for some objects (directories) like this:
user@host:/repo> la .git/objects/
total 540
drwxr-xr-x 135 user user 4096 Jun 16 16:29 .
drwxr-xr-x 8 user user 4096 Jun 16 16:33 ..
drwxr-xr-x 2 user user 4096 Mar 1 17:28 01
drwxr-xr-x 2 user user 4096 Mar 1 17:28 02
drwxr-xr-x 2 user user 4096 Jun 16 16:27 03
drwxr-xr-x 2 user user 4096 Mar 3 13:22 04
drwxr-xr-x 2 root root 4096 Jun 16 16:29 05
drwxr-xr-x 2 user user 4096 Jun 16 16:28 07
drwxr-xr-x 2 root root 4096 Jun 16 16:29 08
Then I ran
sudo chown -R user:user .git/objects/
and it worked!
I was replacing user with my real user, of course.
set height: auto;
If you want to have minimum height to x then you can write
height:auto;
min-height:30px;
height:auto !important; /* for IE as it does not support min-height */
height:30px; /* for IE as it does not support min-height */
one thing I want to add , before you try to install
apt-get install php5-sqlite
or
apt-get install php5-sqlite3
search the given package is available or not :-
# apt-cache search 'php5'
After that you get :-
php5-rrd - rrd module for PHP 5
php5-sasl - Cyrus SASL extension for PHP 5
php5-snmp - SNMP module for php5
**php5-sqlite - SQLite module for php5**
php5-svn - PHP Bindings for the Subversion Revision control system
php5-sybase - Sybase / MS SQL Server module for php5
Here you get an idea about whether your version support or not .. in my system I get php5-sqlite - SQLite module for php5 so I prefer to install
**apt-get install php5-sqlite**
Define set
a = set()
Use add to append single values
a.add(1)
a.add(2)
Use update to add elements from tuples, sets, lists or frozen-sets
a.update([3,4])
>> print(a)
{1, 2, 3, 4}
If you want to add a tuple or frozen-set itself, use add
a.add((5, 6))
>> print(a)
{1, 2, 3, 4, (5, 6)}
Note: Since set elements must be hashable, and lists are considered mutable, you cannot add a list to a set. You also cannot add other sets to a set. You can however, add the elements from lists and sets as demonstrated with the ".update" method.
I have the following add.. I need to separate out the dns suffix from the hostname.. and I only "know" the servers alias shortname... and want to know what the dns suffix is
#example:
#serveralias: MyAppServer.us.fred.com
#actualhostname: server01.us.fred.com
#I "know": "MyAppServer" .. I pass this on as an env var called myjumpbox .. this could also be $env:computername
$forname = $env:myjumpbox
$fqdn = [System.Net.Dns]::GetHostByName($forname).Hostname
$shortname = $fqdn.split('.')[0]
$domainname = $fqdn -split $fqdn.split('.')[0]+"."
$dnssuf = $domainname[1]
" name parts are- alias: " + $forname + " actual hostname: " + $shortname + " suffix: " + $dnssuf
#returns
name parts are- alias: MyAppServer actual hostname: server01 suffix: us.fred.com
You have some variables that are different types in Java language like that:
message of type string
timestamp of type time
count of type integer
version of type integer
If you use a HashMap like:
HashMap<String,Object> yourHash = new HashMap<String,Object>();
yourHash.put("message","message");
yourHash.put("timestamp",timestamp);
yourHash.put("count ",count);
yourHash.put("version ",version);
If you want to use the yourHash:
for(String key : yourHash.keySet()){
String message = (String) yourHash.get(key);
Datetime timestamp= (Datetime) yourHash.get(key);
int timestamp= (int) yourHash.get(key);
}
You should use double instead of float for precise calculations, and float instead of double when using less accurate calculations. Float contains only decimal numbers, but double contains an IEEE754 double-precision floating point number, making it easier to contain and computate numbers more accurately. Hope this helps.
<select name="name">
<option <?php if ($_GET['name'] == 'a') { ?>selected="true" <?php }; ?>value="a">a</option>
<option <?php if ($_GET['name'] == 'b') { ?>selected="true" <?php }; ?>value="b">b</option>
</select>
For the record, this is documented in How do I add resources to my JAR? (illustrated for unit tests but the same applies for a "regular" resource):
To add resources to the classpath for your unit tests, you follow the same pattern as you do for adding resources to the JAR except the directory you place resources in is
${basedir}/src/test/resources
. At this point you would have a project directory structure that would look like the following:my-app |-- pom.xml `-- src |-- main | |-- java | | `-- com | | `-- mycompany | | `-- app | | `-- App.java | `-- resources | `-- META-INF | |-- application.properties `-- test |-- java | `-- com | `-- mycompany | `-- app | `-- AppTest.java `-- resources `-- test.properties
In a unit test you could use a simple snippet of code like the following to access the resource required for testing:
... // Retrieve resource InputStream is = getClass().getResourceAsStream("/test.properties" ); // Do something with the resource ...
If "partly cherry picking" means "within files, choosing some changes but discarding others", it can be done by bringing in git stash
:
git reset HEAD^
to convert the entire cherry-picked commit into unstaged working changes.git stash save --patch
: interactively select unwanted material to stash.git commit
git stash drop
. Tip: if you give the stash of unwanted changes a name: git stash save --patch junk
then if you forget to do (6) now, later you will recognize the stash for what it is.
When the browser puts something in its cache, it also stores the Last-Modified
or ETag
header from the server.
The browser then sends a request with the If-Modified-Since
or If-None-Match
header, telling the server to send a 304 if the content still has that date or ETag.
The server needs some way of calculating a date-modified or ETag for each version of each resource; this typically comes from the filesystem or a separate database column.
Have your tried using the 'return' keyword?
def rps():
return True
The original order is in fact backwards. Certs should be followed by the issuing cert until the last cert is issued by a known root per IETF's RFC 5246 Section 7.4.2
This is a sequence (chain) of certificates. The sender's certificate MUST come first in the list. Each following certificate MUST directly certify the one preceding it.
See also SSL: error:0B080074:x509 certificate routines:X509_check_private_key:key values mismatch for troubleshooting techniques.
But I still don't know why they wrote the spec so that the order matters.
Its probably due to a version conflict, try to run this, it will remove the older pip somehow.
sudo apt remove python pip
I used the code that provided Erik, works great, but i have a complex custom adapter for my listview and i was confronted with twice implementation of the code that updates the UI. I've tried to get the new view from my adapters getView method(the arraylist that holds the listview data has allready been updated/changed):
View cell = lvOptim.getChildAt(index - lvOptim.getFirstVisiblePosition());
if(cell!=null){
cell = adapter.getView(index, cell, lvOptim); //public View getView(final int position, View convertView, ViewGroup parent)
cell.startAnimation(animationLeftIn());
}
It's working well, but i dont know if this is a good practice. So i don't need to implement the code that updates the list item two times.
In my case, I solved it changing the @Id field type from long to Long.
Try this
from threading import Thread
def fun1():
print("Working1")
def fun2():
print("Working2")
t1 = Thread(target=fun1)
t2 = Thread(target=fun2)
t1.start()
t2.start()
Managed to get answer after do some google..
echo "deb http://ppa.launchpad.net/webupd8team/java/ubuntu precise main" | tee -a /etc/apt/sources.list
echo "deb-src http://ppa.launchpad.net/webupd8team/java/ubuntu precise main" | tee -a /etc/apt/sources.list
apt-key adv --keyserver hkp://keyserver.ubuntu.com:80 --recv-keys EEA14886
apt-get update
# Java 7
apt-get install oracle-java7-installer
# For Java 8 command is:
apt-get install oracle-java8-installer
Before you begin to curse your application you need to check this:
Is your application the only one using that instance of SQL Server. a. If the answer to that is NO then you need to investigate how the other applications are consuming resources on your SQl Server.run b. If the answer is yes then you must investigate your application.
Run SQL Server Profiler and check what activity is happening in other applications (1a) using SQL Server and check your application as well (1b).
If indeed your application is starved off of resources then you need to make farther investigations. For more read on this http://sqlserverplanet.com/troubleshooting/sql-server-slowness
This little example shows how the $rootScope
emit a event that will be listen by a children scope in another controller.
(function(){
angular
.module('ExampleApp',[]);
angular
.module('ExampleApp')
.controller('ExampleController1', Controller1);
Controller1.$inject = ['$rootScope'];
function Controller1($rootScope) {
var vm = this,
message = 'Hi my children scope boy';
vm.sayHi = sayHi;
function sayHi(){
$rootScope.$broadcast('greeting', message);
}
}
angular
.module('ExampleApp')
.controller('ExampleController2', Controller2);
Controller2.$inject = ['$scope'];
function Controller2($scope) {
var vm = this;
$scope.$on('greeting', listenGreeting)
function listenGreeting($event, message){
alert(['Message received',message].join(' : '));
}
}
})();
http://codepen.io/gpincheiraa/pen/xOZwqa
The answer of @gayathri bottom explain technically the differences of all those methods in the scope angular concept and their implementations $scope
and $rootScope
.
Here you go. :D
"??".split("").reduce((hex,c)=>hex+=c.charCodeAt(0).toString(16).padStart(4,"0"),"")
"6f225b57"
for non unicode
"hi".split("").reduce((hex,c)=>hex+=c.charCodeAt(0).toString(16).padStart(2,"0"),"")
"6869"
ASCII (utf-8) binary HEX string to string
"68656c6c6f20776f726c6421".match(/.{1,2}/g).reduce((acc,char)=>acc+String.fromCharCode(parseInt(char, 16)),"")
String to ASCII (utf-8) binary HEX string
"hello world!".split("").reduce((hex,c)=>hex+=c.charCodeAt(0).toString(16).padStart(2,"0"),"")
--- unicode ---
String to UNICODE (utf-16) binary HEX string
"hello world!".split("").reduce((hex,c)=>hex+=c.charCodeAt(0).toString(16).padStart(4,"0"),"")
UNICODE (utf-16) binary HEX string to string
"00680065006c006c006f00200077006f0072006c00640021".match(/.{1,4}/g).reduce((acc,char)=>acc+String.fromCharCode(parseInt(char, 16)),"")
<html>
<head>
<title>Example Using Google Complete API</title>
</head>
<body>
<form>
<input id="geocomplete" type="text" placeholder="Type an address/location"/>
</form>
<script src="http://maps.googleapis.com/maps/api/js?sensor=false&libraries=places"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script src="http://ubilabs.github.io/geocomplete/jquery.geocomplete.js"></script>
<script>
$(function(){
$("#geocomplete").geocomplete();
});
</script>
</body>
</html>
For more information visit this link