Shahar's answer was really helpful, but I found it quite tedious to do this all myself, so I made a nifty little Python program:
import re
import urllib2
import string
url1 = raw_input("Please enter a URL from Tunein Radio: ");
open_file = urllib2.urlopen(url1);
raw_file = open_file.read();
API_key = re.findall(r"StreamUrl\":\"(.*?),",raw_file);
#print API_key;
#print "The API key is: " + API_key[0];
use_key = urllib2.urlopen(str(API_key[0]));
key_content = use_key.read();
raw_stream_url = re.findall(r"Url\": \"(.*?)\"",key_content);
bandwidth = re.findall(r"Bandwidth\":(.*?),", key_content);
reliability = re.findall(r"lity\":(.*?),", key_content);
isPlaylist = re.findall(r"HasPlaylist\":(.*?),",key_content);
codec = re.findall(r"MediaType\": \"(.*?)\",", key_content);
tipe = re.findall(r"Type\": \"(.*?)\"", key_content);
total = 0
for element in raw_stream_url:
total = total + 1
i = 0
print "I found " + str(total) + " streams.";
for element in raw_stream_url:
print "Stream #" + str(i + 1);
print "Stream stats:";
print "Bandwidth: " + str(bandwidth[i]) + " kilobytes per second."
print "Reliability: " + str(reliability[i]) + "%"
print "HasPlaylist: " + str(isPlaylist[i]) + "."
print "Stream codec: " + str(codec[i]) + "."
print "This audio stream is " + tipe[i].lower() + "."
print "Pure streaming URL: " + str(raw_stream_url[i]) + ".";
i = i + 1
raw_input("Press enter to close TMUS.")
It's basically Shahar's solution automated.
An optimized version of the implementation of the reverse function proposed by @michieljoris (according to the comments of @Beterraba and @Mala):
function a2hex(str) {_x000D_
var hex = '';_x000D_
for (var i = 0, l = str.length; i < l; i++) {_x000D_
var hexx = Number(str.charCodeAt(i)).toString(16);_x000D_
hex += (hexx.length > 1 && hexx || '0' + hexx);_x000D_
}_x000D_
return hex;_x000D_
}_x000D_
alert(a2hex('2460')); // display 32343630
_x000D_
Use
res.sendFile()
instead of
res.render()
.
What your trying to do is send a whole file.
This worked for me.
Easiest way is used the Date Using Date() and getTime()
Date dte=new Date();
long milliSeconds = dte.getTime();
String strLong = Long.toString(milliSeconds);
System.out.println(milliSeconds)
In a Windows Forms project:
For the full path (filename included): string exePath = Application.ExecutablePath;
For the path only: string appPath = Application.StartupPath;
As described in this article,
Abstract classes versus interfaces in Java 8
After introducing Default Method, it seems that interfaces and abstract classes are same. However, they are still different concept in Java 8.
Abstract class can define constructor. They are more structured and can have a state associated with them. While in contrast, default method can be implemented only in the terms of invoking other interface methods, with no reference to a particular implementation's state. Hence, both use for different purposes and choosing between two really depends on the scenario context.
You can mark properties with readonly
modifier in your declaration:
export class MyClass {
public static readonly MY_PUBLIC_CONSTANT = 10;
private static readonly myPrivateConstant = 5;
}
I found the solution!
Follow these steps:
After that, execute:
flutter build apk --debug
flutter build apk --profile
flutter build apk --release
and then, run app! it works for me!
Using awk.
i starts at 0, i++
will increment the value of i, but return the original value that i held before being incremented.
awk '{print i++ "," $0}' file
I think it's better to use pure JavaScript, which we can run on the DOM of the Browser.
Here is the functional way to use it. I have used ES6 but feel free to use ES5 and function expression or function definition, whichever suits your JavaScript StyleGuide.
'use strict'_x000D_
_x000D_
const oldAdd = (element, className) => {_x000D_
let classes = element.className.split(' ')_x000D_
if (classes.indexOf(className) < 0) {_x000D_
classes.push(className)_x000D_
}_x000D_
element.className = classes.join(' ')_x000D_
}_x000D_
_x000D_
const oldRemove = (element, className) => {_x000D_
let classes = element.className.split(' ')_x000D_
const idx = classes.indexOf(className)_x000D_
if (idx > -1) {_x000D_
classes.splice(idx, 1)_x000D_
}_x000D_
element.className = classes.join(' ')_x000D_
}_x000D_
_x000D_
const addClass = (element, className) => {_x000D_
if (element.classList) {_x000D_
element.classList.add(className)_x000D_
} else {_x000D_
oldAdd(element, className)_x000D_
}_x000D_
}_x000D_
_x000D_
const removeClass = (element, className) => {_x000D_
if (element.classList) {_x000D_
element.classList.remove(className)_x000D_
} else {_x000D_
oldRemove(element, className)_x000D_
}_x000D_
}
_x000D_
To get the moving average in pandas we can use cum_sum and then divide by count.
Here is the working example:
import pandas as pd
import numpy as np
df = pd.DataFrame({'id': range(5),
'value': range(100,600,100)})
# some other similar statistics
df['cum_sum'] = df['value'].cumsum()
df['count'] = range(1,len(df['value'])+1)
df['mov_avg'] = df['cum_sum'] / df['count']
# other statistics
df['rolling_mean2'] = df['value'].rolling(window=2).mean()
print(df)
id value cum_sum count mov_avg rolling_mean2
0 0 100 100 1 100.0 NaN
1 1 200 300 2 150.0 150.0
2 2 300 600 3 200.0 250.0
3 3 400 1000 4 250.0 350.0
4 4 500 1500 5 300.0 450.0
You need to set
WindowStyle="None"
, AllowsTransparency="True"
and optionally ResizeMode="NoResize"
and then set the Style
property of the window to your custom window style, where you design the appearance of the window (title bar, buttons, border) to anything you want and display the window contents in a ContentPresenter
.
This seems to be a good article on how you can achieve this, but there are many other articles on the internet.
console.log is only available after you have opened the Developer Tools (F12 to toggle it open and closed). Funny thing is that after you've opened it, you can close it, then still post to it via console.log calls, and those will be seen when you reopen it. I'm thinking that is a bug of sorts, and may be fixed, but we shall see.
I'll probably just use something like this:
function trace(s) {
if ('console' in self && 'log' in console) console.log(s)
// the line below you might want to comment out, so it dies silent
// but nice for seeing when the console is available or not.
else alert(s)
}
and even simpler:
function trace(s) {
try { console.log(s) } catch (e) { alert(s) }
}
just simple:
.navbar{
width:65% !important;
margin:0px auto;
left:0;
right:0;
padding:0;
}
or,
.navbar.navbar-fixed-top{
width:65% !important;
margin:0px auto;
left:0;
right:0;
padding:0;
}
Hope it works (at least, for future searchers)
You can use jquery.form.js plugin to upload image via ajax to the server.
http://malsup.com/jquery/form/
Here is the sample jQuery ajax image upload script
(function() {
$('form').ajaxForm({
beforeSubmit: function() {
//do validation here
},
beforeSend:function(){
$('#loader').show();
$('#image_upload').hide();
},
success: function(msg) {
///on success do some here
}
}); })();
If you have any doubt, please refer following ajax image upload tutorial here
http://www.smarttutorials.net/ajax-image-upload-using-jquery-php-mysql/
Great Answer by Jon.
I'm lazy though and I hate typing, so I created a simple cut and paste example for all the other people who are like me. Enjoy!
import java.util.ArrayList;
import java.util.List;
public class Main {
public static void main(String[] args) {
List<String> animals = new ArrayList<>();
animals.add("Lion");
animals.add("Tiger");
animals.add("Cat");
animals.add("Dog");
System.out.println(animals); // [Lion, Tiger, Cat, Dog]
// add() -> push(): Add items to the end of an array
animals.add("Elephant");
System.out.println(animals); // [Lion, Tiger, Cat, Dog, Elephant]
// remove() -> pop(): Remove an item from the end of an array
animals.remove(animals.size() - 1);
System.out.println(animals); // [Lion, Tiger, Cat, Dog]
// add(0,"xyz") -> unshift(): Add items to the beginning of an array
animals.add(0, "Penguin");
System.out.println(animals); // [Penguin, Lion, Tiger, Cat, Dog]
// remove(0) -> shift(): Remove an item from the beginning of an array
animals.remove(0);
System.out.println(animals); // [Lion, Tiger, Cat, Dog]
}
}
This an old question but for people still looking. In JS you can now use the title
property.
button.title = ("Popup text here");
In python
Using built in method
driver.refresh()
or, executing JavaScript
driver.execute_script("location.reload()")
Should you want to add a new column (say 'count_column') containing the groups' counts into the dataframe:
df.count_column=df.groupby(['col5','col2']).col5.transform('count')
(I picked 'col5' as it contains no nan)
You Can use this header
header('Content-type: text/html; charset=UTF-8');
and after decoding the string
$page = utf8_decode(curl_exec($ch));
It worked for me
For those that are googling this and ended up here like me, this is how you currently do it in EF5 and EF6:
context.Database.ExecuteSqlCommand("TRUNCATE TABLE [TableName]");
Assuming context is a System.Data.Entity.DbContext
I created a new option in the select tag that has a value of empty string ("") and used:
$("form.query").find('select#topic').val("");
To get first word of string you can do this:
let myStr = "Hello World"
let firstWord = myStr.split(" ")[0]
A port denotes a communication endpoint in the TCP and UDP transports for the IP network protocol. A socket is a software abstraction for a communication endpoint commonly used in implementations of these protocols (socket API). An alternative implementation is the XTI/TLI API.
See also:
Stevens, W. R. 1998, UNIX Network Programming: Networking APIs: Sockets and XTI; Volume 1, Prentice Hall.
Stevens, W. R., 1994, TCP/IP Illustrated, Volume 1: The Protocols, Addison-Wesley.
In general, you want to go from XML to regular objects of your language (since there are usually reasonable tools to do this, and it's the harder conversion). And then from Plain Old Object produce JSON -- there are tools for this, too, and it's a quite simple serialization (since JSON is "Object Notation", natural fit for serializing objects). I assume Python has its set of tools.
I'm using python 2.7.13 with scandir and here's my one-liner recursive function to get the total size of a folder:
from scandir import scandir
def getTotFldrSize(path):
return sum([s.stat(follow_symlinks=False).st_size for s in scandir(path) if s.is_file(follow_symlinks=False)]) + \
+ sum([getTotFldrSize(s.path) for s in scandir(path) if s.is_dir(follow_symlinks=False)])
>>> print getTotFldrSize('.')
1203245680
You can use re.match()
or re.search()
.
Python offers two different primitive operations based on regular expressions: re.match()
checks for a match only at the beginning of the string, while re.search()
checks for a match anywhere in the string (this is what Perl does by default). refer this
As shell command:
< /dev/zero head -c 1048576 > output
In the XML file set the android:checkedButton
field in your RadioGroup
, with the id of your default RadioButton
:
<RadioGroup
....
android:checkedButton="@+id/button_1">
<RadioButton
android:id="@+id/button_1"
...../>
<RadioButton
android:id="@+id/button_2"
...../>
<RadioButton
android:id="@+id/button_3"
...../>
</RadioGroup>
public class shuffleCards{
public static void main(String[] args) {
String[] cardsType ={"club","spade","heart","diamond"};
String [] cardValue = {"Ace","2","3","4","5","6","7","8","9","10","King", "Queen", "Jack" };
List<String> cards = new ArrayList<String>();
for(int i=0;i<=(cardsType.length)-1;i++){
for(int j=0;j<=(cardValue.length)-1;j++){
cards.add(cardsType[i] + " " + "of" + " " + cardValue[j]) ;
}
}
Collections.shuffle(cards);
System.out.print("Enter the number of cards within:" + cards.size() + " = ");
Scanner data = new Scanner(System.in);
Integer inputString = data.nextInt();
for(int l=0;l<= inputString -1;l++){
System.out.print( cards.get(l)) ;
}
}
}
You can use it to transform some aggregate functions into analytic:
SELECT MAX(date)
FROM mytable
will return 1
row with a single maximum,
SELECT MAX(date) OVER (ORDER BY id)
FROM mytable
will return all rows with a running maximum.
completed = (id) => {
var details = {
'id': id,
};
var formBody = [];
for (var property in details) {
var encodedKey = encodeURIComponent(property);
var encodedValue = encodeURIComponent(details[property]);
formBody.push(encodedKey + "=" + encodedValue);
}
formBody = formBody.join("&");
fetch(markcompleted, {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/x-www-form-urlencoded'
},
body: formBody
})
.then((response) => response.json())
.then((responseJson) => {
console.log(responseJson, 'res JSON');
if (responseJson.status == "success") {
console.log(this.state);
alert("your todolist is completed!!");
}
})
.catch((error) => {
console.error(error);
});
};
In Visual Studio 2015 (Soulution is under source control, MVC-Project), csano's Update-Package -Reinstall -ProjectName Your.Project.Name
worked, but it messed up with some write locks.
I had to delete the "packages"-Folder manually before. (It seemed to be locked because of the source control).
Also, I had to re-install the MVC-Package from the NuGet Package Manager.
I tried the following code that seemed to work:
if(open(my $FILE, "<File.txt")) {
while(<$FILE>){
print "$_";}
} else {
print "File could not be opened or did not exists\n";
}
Have you tried with the custom format "#,##0.##"
?
Integer class implements Comparable.So we can easily get the max or min value of the Integer list.
public int maxOfNumList() {
List<Integer> numList = new ArrayList<>();
numList.add(1);
numList.add(10);
return Collections.max(numList);
}
If a class does not implements Comparable and we have to find max and min value then we have to write our own Comparator.
List<MyObject> objList = new ArrayList<MyObject>();
objList.add(object1);
objList.add(object2);
objList.add(object3);
MyObject maxObject = Collections.max(objList, new Comparator<MyObject>() {
@Override
public int compare(MyObject o1, MyObject o2) {
if (o1.getValue() == o2.getValue()) {
return 0;
} else if (o1.getValue() > o2.getValue()) {
return -1;
} else if (o1.getValue() < o2.getValue()) {
return 1;
}
return 0;
}
});
Try using xmltype.createxml(xml)
.
As in,
select extract(xmltype.createxml(xml), '//fax').getStringVal() from mytab;
It worked for me.
If you want to improve or manipulate even further.
Try something like this.
Select *
from xmltable(xmlnamespaces('some-name-space' as "ns",
'another-name-space' as "ns1",
),
'/ns/ns1/foo/bar'
passing xmltype.createxml(xml)
columns id varchar2(10) path '//ns//ns1/id',
idboss varchar2(500) path '//ns0//ns1/idboss',
etc....
) nice_xml_table
Hope it helps someone.
Solution for Java 8. A bit longer than the Guava one, but at least you don't have to install a library.
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
//...
List<Integer> integers = Arrays.asList(1, 2, 3, 4);
List<String> strings = integers.stream().map(Object::toString)
.collect(Collectors.toList());
Before considering making Read Call Log or Read SMS permissions a part of your application I strongly advise you to have a look at this policy of Google Play Market: https://support.google.com/googleplay/android-developer/answer/9047303?hl=en
Those permissions are very sensitive and you will have to prove that your application needs them. But even if it really needs them Google Play Support team may easily reject your request without proper explanations.
This is what happened to me. After providing all the needed information along with the Demonstration video of my application it was rejected with the explanation that my "account is not authorized to provide a certain use case solution in my application" (the list of use cases they may consider as an exception is listed on that Policy page). No link to any policy statement was provided to explain what it all means. Basically they just judged my app as not to go without proper explanation.
I wish you good luck of cause with your applications guys but be careful.
SQL Server allows the following (be careful to use single quotes instead of double)
UPDATE User
SET UserId = 12345
, Name = 'J Doe'
, Location = 'USA'
, Bio='my bio
spans
multiple
lines!'
WHERE UserId = 12345
No, there is no way to do this yet. I wish they add a future like this in browsers.
EDIT:
Now there is a Full Screen API for the web You can requestFullscreen
on an Video or Canvas element to ask user to give you permisions and make it full screen.
Let's consider this element:
<video controls id="myvideo">
<source src="somevideo.webm"></source>
<source src="somevideo.mp4"></source>
</video>
We can put that video into fullscreen mode with script like this:
var elem = document.getElementById("myvideo");
if (elem.requestFullscreen) {
elem.requestFullscreen();
} else if (elem.mozRequestFullScreen) {
elem.mozRequestFullScreen();
} else if (elem.webkitRequestFullscreen) {
elem.webkitRequestFullscreen();
} else if (elem.msRequestFullscreen) {
elem.msRequestFullscreen();
}
A solution that works in WinForms:
var w = new Form() { Size = new Size(0, 0) };
Task.Delay(TimeSpan.FromSeconds(10))
.ContinueWith((t) => w.Close(), TaskScheduler.FromCurrentSynchronizationContext());
MessageBox.Show(w, message, caption);
Based on the effect that closing the form that owns the message box will close the box as well.
Windows Forms controls have a requirement that they must be accessed on the same thread that created them. Using TaskScheduler.FromCurrentSynchronizationContext()
will ensure that, assuming that the example code above is executed on the UI thread, or an user-created thread. The example will not work correctly if the code is executed on a thread from a thread pool (e.g. a timer callback) or a task pool (e.g. on a task created with TaskFactory.StartNew
or Task.Run
with default parameters).
For me it's not important to play audio in the background like for others here, my problem was that I had some animations and they acted like crazy when you were in other tabs and coming back to them. My solution was putting these animations inside if that is preventing inactive tab:
if (!document.hidden){ //your animation code here }
thanks to that my animation was running only if tab was active. I hope this will help someone with my case.
Unless you enabled innodb_file_per_table
option, InnoDB
keeps all data in one file, usually called ibdata1
.
Check the size of that file and check you have enough disk space in the drive it resides on.
If you know that you always want the string between "my" and "is", then you can always perform the following:
string message = "This is an example string and my data is here";
//Get the string position of the first word and add two (for it's length)
int pos1 = message.IndexOf("my") + 2;
//Get the string position of the next word, starting index being after the first position
int pos2 = message.IndexOf("is", pos1);
//use substring to obtain the information in between and store in a new string
string data = message.Substring(pos1, pos2 - pos1).Trim();
In most cases it is better to check whether a given functionality is present or not. For example: if the function pipe()
exists or not.
Read here
$('#example').dataTable({
"aoColumns": [
null,
null,
{ "bSortable": false }, // <-- disable sorting for column 3
null
]
});
http://datatables.net/usage/columns under bSortable
You can specify which columns to disable using aoColumnDefs
and aTargets
$('#example').dataTable({
"aoColumnDefs": [
{
"bSortable": false,
"aTargets": [ -1 ] // <-- gets last column and turns off sorting
}
]
});
As others already noted, you have seen the grep process. If you want to restrict the output to tomcat itself, you have two alternatives
wrap the first searched character in a character class
ps -ef | grep '[t]omcat'
This searches for tomcat too, but misses the grep [t]omcat
entry, because it isn't matched by [t]omcat
.
use a custom output format with ps
ps -e -o pid,comm | grep tomcat
This shows only the pid and the name of the process without the process arguments. So, grep is listed as grep
and not as grep tomcat
.
Another way to understand the relationship between these concepts is to interpret a ROLE as a container of Authorities.
Authorities are fine-grained permissions targeting a specific action coupled sometimes with specific data scope or context. For instance, Read, Write, Manage, can represent various levels of permissions to a given scope of information.
Also, authorities are enforced deep in the processing flow of a request while ROLE are filtered by request filter way before reaching the Controller. Best practices prescribe implementing the authorities enforcement past the Controller in the business layer.
On the other hand, ROLES are coarse grained representation of an set of permissions. A ROLE_READER would only have Read or View authority while a ROLE_EDITOR would have both Read and Write. Roles are mainly used for a first screening at the outskirt of the request processing such as http. ... .antMatcher(...).hasRole(ROLE_MANAGER)
The Authorities being enforced deep in the request's process flow allows a finer grained application of the permission. For instance, a user may have Read Write permission to first level a resource but only Read to a sub-resource. Having a ROLE_READER would restrain his right to edit the first level resource as he needs the Write permission to edit this resource but a @PreAuthorize interceptor could block his tentative to edit the sub-resource.
Jake
Generally speaking, a software product isn't your "property already", as you said in the comment. Most of the times (I won't be irresponsible to say anything in open), it's licensed to you. A license to use some thing is not the same thing as owning (property rights) that very same thing.
That's because there are authorship, copyright, intellectual property rights applicable to it. I don't know how things work in United States (or in your country), but it's generally accepted that the work of a mind, a creative work, must not be changed in its nature as such to make the expression of art to be different than that expression that the author intended. That applies for example, in some cases, to architectural work (in most countries, you can't change the appearance of a building to "desfigure" the work of art of the architect, without his prior consent). Exceptions are made, obviously, when the author expressly authorizes such changes (e.g., Creative Commons licenses, open source licenses etc.).
Anyway, that's why you see in most EULAs the typical sentence: "this software is licensed, not sold". That's the purpose and reason why.
Now that you understand the reasons why you can't wander around changing other people's art, let me be technical.
There are possible ways to decompile Java programs. You can use dex2jar
, it provides a somewhat good start for you to start looking for things and changes. And perhaps rebuild the code by mounting back the pieces together. Good luck, as most people obfuscate their codes to make that harder.
However, let me say that it's still forbidden to change programs, as I said above. And it's extremely unethical. It makes me sad that people do that with no scruples (not saying it's your case, just warning you). It shouldn't need people to be at the other side to understand that. Or maybe that's just me, who lives in a country where piracy is rampant.
The tools are always out there. But the conscience, unfortunately, not always.
edit: in case it isn't clear enough already, I do NOT approve the use of these programs. I use them myself to check how hard my own applications are to be reverse engineered. But I also think that explaning is always better than denial (better be here).
DELETE FROM table1
where id IN
(SELECT id FROM table2..INNER JOIN..INNER JOIN WHERE etc)
Minimize use of DML queries with Joins. You should be able to do most of all DML queries with subqueries like above.
In general, joins should only be used when you need to SELECT or GROUP by columns in 2 or more tables. If you're only touching multiple tables to define a population, use subqueries. For DELETE queries, use correlated subquery.
Yes, contains is case sensitive. You can use java.util.regex.Pattern with the CASE_INSENSITIVE flag for case insensitive matching:
Pattern.compile(Pattern.quote(wantedStr), Pattern.CASE_INSENSITIVE).matcher(source).find();
EDIT: If s2 contains regex special characters (of which there are many) it's important to quote it first. I've corrected my answer since it is the first one people will see, but vote up Matt Quail's since he pointed this out.
This should work:
<script type="text/javascript">
var testing='this is d23553 test 32533\n31203 not 333';
var r = new RegExp(/(?:^|[^\d])(\d{5})(?:$|[^\d])/mg);
var matches = [];
while ((match = r.exec(testing))) matches.push(match[1]);
alert('Found: '+matches.join(', '));
</script>
You can get a free cheap code signing certificate from Certum if you're doing open source development.
I've been using their certificate for over a year, and it does get rid of the unknown publisher message from Windows.
As far as signing code I use signtool.exe from a script like this:
signtool.exe sign /t http://timestamp.verisign.com/scripts/timstamp.dll /f "MyCert.pfx" /p MyPassword /d SignedFile.exe SignedFile.exe
You can put a TextBlock inside the label:
<Label>
<TextBlock Text="Long Text . . . ." TextWrapping="Wrap" />
</Label>
In Mac OSX 10.5 or later, Apple recommends to set the $JAVA_HOME variable to /usr/libexec/java_home
, just export $JAVA_HOME
in file ~/. bash_profile
or ~/.profile
.
Open the terminal and run the below command.
$ vim .bash_profile
export JAVA_HOME=$(/usr/libexec/java_home)
save and exit from vim editor, then run the source command on .bash_profile
$ source .bash_profile
$ echo $JAVA_HOME
/Library/Java/JavaVirtualMachines/1.7.0.jdk/Contents/Home
For future visitors: In the new HttpClient
(Angular 4.3+), the response
object is JSON by default, so you don't need to do response.json().data
anymore. Just use response
directly.
Example (modified from the official documentation):
import { HttpClient } from '@angular/common/http';
@Component(...)
export class YourComponent implements OnInit {
// Inject HttpClient into your component or service.
constructor(private http: HttpClient) {}
ngOnInit(): void {
this.http.get('https://api.github.com/users')
.subscribe(response => console.log(response));
}
}
Don't forget to import it and include the module under imports in your project's app.module.ts:
...
import { HttpClientModule } from '@angular/common/http';
@NgModule({
imports: [
BrowserModule,
// Include it under 'imports' in your application module after BrowserModule.
HttpClientModule,
...
],
...
I had the same issue but solved it by using Ubuntu.
python -m pip install pyaudio
brew install portaudio
brew link portaudio
You can inherit @Input, @Output, @ViewChild, etc. Look at the sample:
@Component({
template: ''
})
export class BaseComponent {
@Input() someInput: any = 'something';
@Output() someOutput: EventEmitter<void> = new EventEmitter<void>();
}
@Component({
selector: 'app-derived',
template: '<div (click)="someOutput.emit()">{{someInput}}</div>',
providers: [
{ provide: BaseComponent, useExisting: DerivedComponent }
]
})
export class DerivedComponent {
}
Right Click on the server tab, go for NEW-> Server. then choose recent version of tomcat server. Click on next, and then give path for your tomcat server.(You can download tomcat server from this link https://tomcat.apache.org/download-80.cgi#8.5.32). Click on finish.
You can start your server now..!!
Go to Environment Variable and paste the following:
Under System Variable: Step 1: New --> New User Variable 1. Variable name: MAVEN_HOME 2. Variable_value : D:\apache-maven-3.5.2
Step 2: 1. Go to the path --> and paste this - %MAVEN_HOME%\bin
If you are looking for a scripted solution:
.vsix
files (see example below)unzip
the binary into ~/.vscode/extensions/
: you need to modify unzipped directory name, remove one file and move/rename another one.For API start by looking at following example, and for hints how to modify request head to https://github.com/Microsoft/vscode/blob/master/src/vs/platform/extensionManagement/common/extensionGalleryService.ts.
POST https://marketplace.visualstudio.com/_apis/public/gallery/extensionquery?api-version=5.1-preview HTTP/1.1
content-type: application/json
{
"filters": [
{
"criteria": [
{
"filterType": 8,
"value": "Microsoft.VisualStudio.Code",
},
{
"filterType": 7,
"value": "ms-python.python",
}
],
"pageNumber": 1,
"pageSize": 10,
"sortBy": 0,
"sortOrder": 0,
}
],
"assetTypes": ["Microsoft.VisualStudio.Services.VSIXPackage"],
"flags": 514,
}
Explanations to the above example:
"filterType": 8
- FilterType.Target
more FilterTypes"filterType": 7
- FilterType.ExtensionName
more FilterTypes"flags": 514
- 0x2 | 0x200
- Flags.IncludeFiles | Flags.IncludeLatestVersionOnly
- more Flags
python -c "print(0x2|0x200)"
"assetTypes": ["Microsoft.VisualStudio.Services.VSIXPackage"]
- to get only link to .vsix
file more AssetTypesIs 'UTC' a valid timezone identifier on your system?
<?php
if (date_default_timezone_set('UTC')){
echo "UTC is a valid time zone";
}else{
echo "The system doesn't know WTFUTC. Maybe try updating tzinfo with your package manager?";
}
Dim numberOfButtons As Integer
Dim buttons() as Button
Private Sub MyForm_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Redim buttons(numberOfbuttons)
for counter as integer = 0 to numberOfbuttons
With buttons(counter)
.Size = (10, 10)
.Visible = False
.Location = (55, 33 + counter*13)
.Text = "Button "+(counter+1).ToString ' or some name from an array you pass from main
'any other property
End With
'
next
End Sub
If you want to check which of the textboxes have information, or which radio button was clicked, you can iterate through a loop in an OK button.
If you want to be able to click individual array items and have them respond to events, add in the Form_load loop the following:
AddHandler buttons(counter).Clicked AddressOf All_Buttons_Clicked
then create
Private Sub All_Buttons_Clicked(ByVal sender As System.Object, ByVal e As System.EventArgs)
'some code here, can check to see which checkbox was changed, which button was clicked, by number or text
End Sub
when you call: objectYouCall.numberOfButtons = initial_value_from_main_program
response_yes_or_no_or_other = objectYouCall.ShowDialog()
For radio buttons, textboxes, same story, different ending.
Use Windows Job Objects. Jobs are like process groups and can limit memory usage and process priority.
public Integer binaryToInteger(String binary){
char[] numbers = binary.toCharArray();
Integer result = 0;
int count = 0;
for(int i=numbers.length-1;i>=0;i--){
if(numbers[i]=='1')result+=(int)Math.pow(2, count);
count++;
}
return result;
}
I guess I'm even more bored! Modified Hassan's answer to function correctly.
I really liked this answer, with ngBind, your default text can just live in the element body, and then if the ngBind evaluates to something non-null/undefined, your content is replaced automatically, and everythings happy
angularjs setting default values to display before evaluation
Update 2019 - Bootstrap 4
You can simply use the SASS mixin to change the number of cards across in each breakpoint / grid tier.
.card-columns {
@include media-breakpoint-only(xl) {
column-count: 5;
}
@include media-breakpoint-only(lg) {
column-count: 4;
}
@include media-breakpoint-only(md) {
column-count: 3;
}
@include media-breakpoint-only(sm) {
column-count: 2;
}
}
SASS Demo: http://www.codeply.com/go/FPBCQ7sOjX
Or, CSS only like this...
@media (min-width: 576px) {
.card-columns {
column-count: 2;
}
}
@media (min-width: 768px) {
.card-columns {
column-count: 3;
}
}
@media (min-width: 992px) {
.card-columns {
column-count: 4;
}
}
@media (min-width: 1200px) {
.card-columns {
column-count: 5;
}
}
CSS-only Demo: https://www.codeply.com/go/FIqYTyyWWZ
Shell scripts, no matter how they are executed, execute one command after the other. So your code will execute results.sh
after the last command of st_new.sh
has finished.
Now there is a special command which messes this up: &
cmd &
means: "Start a new background process and execute cmd
in it. After starting the background process, immediately continue with the next command in the script."
That means &
doesn't wait for cmd
to do it's work. My guess is that st_new.sh
contains such a command. If that is the case, then you need to modify the script:
cmd &
BACK_PID=$!
This puts the process ID (PID) of the new background process in the variable BACK_PID
. You can then wait for it to end:
while kill -0 $BACK_PID ; do
echo "Process is still active..."
sleep 1
# You can add a timeout here if you want
done
or, if you don't want any special handling/output simply
wait $BACK_PID
Note that some programs automatically start a background process when you run them, even if you omit the &
. Check the documentation, they often have an option to write their PID to a file or you can run them in the foreground with an option and then use the shell's &
command instead to get the PID.
HTML:
<div data-uid="aaa" data-name="bbb", data-value="ccc" onclick="fun(this)">
JavaScript:
function fun(obj) {
var uid= $(obj).attr('data-uid');
var name= $(obj).attr('data-name');
var value= $(obj).attr('data-value');
}
but I'm using jQuery.
from: Outline effect to text
.strokeme
{
color: white;
text-shadow:
-1px -1px 0 #000,
1px -1px 0 #000,
-1px 1px 0 #000,
1px 1px 0 #000;
}
Here is code for Multiple Client to one Server Working Fine .. Give it a try :)
Server.java:
import java.io.DataInputStream;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.logging.Level;
import java.util.logging.Logger;
class Multi extends Thread{
private Socket s=null;
DataInputStream infromClient;
Multi() throws IOException{
}
Multi(Socket s) throws IOException{
this.s=s;
infromClient = new DataInputStream(s.getInputStream());
}
public void run(){
String SQL=new String();
try {
SQL = infromClient.readUTF();
} catch (IOException ex) {
Logger.getLogger(Multi.class.getName()).log(Level.SEVERE, null, ex);
}
System.out.println("Query: " + SQL);
try {
System.out.println("Socket Closing");
s.close();
} catch (IOException ex) {
Logger.getLogger(Multi.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
public class Server {
public static void main(String args[]) throws IOException,
InterruptedException{
while(true){
ServerSocket ss=new ServerSocket(11111);
System.out.println("Server is Awaiting");
Socket s=ss.accept();
Multi t=new Multi(s);
t.start();
Thread.sleep(2000);
ss.close();
}
}
}
Client1.java:
import java.io.DataOutputStream;
import java.io.ObjectInputStream;
import java.net.Socket;
public class client1 {
public static void main(String[] arg) {
try {
Socket socketConnection = new Socket("127.0.0.1", 11111);
//QUERY PASSING
DataOutputStream outToServer = new DataOutputStream(socketConnection.getOutputStream());
String SQL="I am client 1";
outToServer.writeUTF(SQL);
} catch (Exception e) {System.out.println(e); }
}
}
Client2.java
import java.io.DataOutputStream;
import java.net.Socket;
public class client2 {
public static void main(String[] arg) {
try {
Socket socketConnection = new Socket("127.0.0.1", 11111);
//QUERY PASSING
DataOutputStream outToServer = new DataOutputStream(socketConnection.getOutputStream());
String SQL="I am Client 2";
outToServer.writeUTF(SQL);
} catch (Exception e) {System.out.println(e); }
}
}
In onMapReady() Method
change the zoomLevel to any desired value.
float zoomLevel = (float) 18.0;
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(latLng, zoomLevel));
I think the docs aren't wonderful at exposing how to do this. It has been a supported feature for some time, however, and there are some details in this pull request.
So there are three different ways to do this:
Option A) Create a new session with the profile
dev = boto3.session.Session(profile_name='dev')
Option B) Change the profile of the default session in code
boto3.setup_default_session(profile_name='dev')
Option C) Change the profile of the default session with an environment variable
$ AWS_PROFILE=dev ipython
>>> import boto3
>>> s3dev = boto3.resource('s3')
Try this one:
p.pos_fixed {
position:fixed;
top:30px;
right:5px;
}
You should get your data in a specific format by melting your data (see below for how melted data looks like) before you plot. Otherwise, what you have done seems to be okay.
require(reshape2)
df <- read.csv("TestData.csv", header=T)
# melting by "Label". `melt is from the reshape2 package.
# do ?melt to see what other things it can do (you will surely need it)
df.m <- melt(df, id.var = "Label")
> df.m # pasting some rows of the melted data.frame
# Label variable value
# 1 Good F1 0.64778924
# 2 Good F1 0.54608791
# 3 Good F1 0.46134200
# 4 Good F1 0.79421221
# 5 Good F1 0.56919951
# 6 Good F1 0.73568570
# 7 Good F1 0.65094207
# 8 Good F1 0.45749702
# 9 Good F1 0.80861929
# 10 Good F1 0.67310067
# 11 Good F1 0.68781739
# 12 Good F1 0.47009455
# 13 Good F1 0.95859182
# 14 Good F1 1.00000000
# 15 Good F1 0.46908343
# 16 Bad F1 0.57875528
# 17 Bad F1 0.28938046
# 18 Bad F1 0.68511766
require(ggplot2)
ggplot(data = df.m, aes(x=variable, y=value)) + geom_boxplot(aes(fill=Label))
Edit: I realise that you might need to facet. Here's an implementation of that as well:
p <- ggplot(data = df.m, aes(x=variable, y=value)) +
geom_boxplot(aes(fill=Label))
p + facet_wrap( ~ variable, scales="free")
Edit 2: How to add x-labels
, y-labels
, title
, change legend heading
, add a jitter
?
p <- ggplot(data = df.m, aes(x=variable, y=value))
p <- p + geom_boxplot(aes(fill=Label))
p <- p + geom_jitter()
p <- p + facet_wrap( ~ variable, scales="free")
p <- p + xlab("x-axis") + ylab("y-axis") + ggtitle("Title")
p <- p + guides(fill=guide_legend(title="Legend_Title"))
p
Edit 3: How to align geom_point()
points to the center of box-plot? It could be done using position_dodge
. This should work.
require(ggplot2)
p <- ggplot(data = df.m, aes(x=variable, y=value))
p <- p + geom_boxplot(aes(fill = Label))
# if you want color for points replace group with colour=Label
p <- p + geom_point(aes(y=value, group=Label), position = position_dodge(width=0.75))
p <- p + facet_wrap( ~ variable, scales="free")
p <- p + xlab("x-axis") + ylab("y-axis") + ggtitle("Title")
p <- p + guides(fill=guide_legend(title="Legend_Title"))
p
A bit more readable and simple approach could be achieved with the script below:
$Directory = "./"
Get-ChildItem $Directory -Recurse | % {
if ($_.Attributes -eq "Directory") {
Write-Host $_.FullName
}
}
Hope this helps!
//if(data="undefined"){
This is an assignment statement, not a comparison. Also, "undefined"
is a string, it's a property. Checking it is like this: if (data === undefined)
(no quotes, otherwise it's a string value)
If it's not defined, you may be returning an empty string. You could try checking for a falsy
value like if (!data)
as well
I was annoyed to find out that UIWebView is not a scroll view, so I made a custom subclass to get at the web view's scroll view. This suclass contains a scroll view so you can customize the behavior of your web view. The punchlines of this class are:
@class CustomWebView : UIWebview
...
- (id) initWithFrame:(CGRect)frame{
self = [super initWithFrame:frame];
// WebViews are subclass of NSObject and not UIScrollView and therefore don't allow customization.
// However, a UIWebView is a UIScrollViewDelegate, so it must CONTAIN a ScrollView somewhere.
// To use a web view like a scroll view, let's traverse the view hierarchy to find the scroll view inside the web view.
for (UIView* v in self.subviews){
if ([v isKindOfClass:[UIScrollView class]]){
_scrollView = (UIScrollView*)v;
break;
}
}
return self;
}
Then, when you create a custom web view, you can disable bouncing with:
customWebView.scrollView.bounces = NO; //(or customWebView.scrollView.alwaysBounceVertically = NO)
This is a great general purpose way to make a web view with customizable scrolling behavior. There are just a few things to watch out for:
When you use df.apply()
, each row of your DataFrame will be passed to your lambda function as a pandas Series. The frame's columns will then be the index of the series and you can access values using series[label]
.
So this should work:
df['D'] = (df.apply(lambda x: myfunc(x[colNames[0]], x[colNames[1]]), axis=1))
Imho one of the simplest Solutions is: -
//MIN NUMBER
Collections.sort(listOfNumbers);
listOfNumbers.get(0);
//MAX NUMBER
Collections.sort(listOfNumbers);
Collections.reverse(listOfNumbers);
listOfNumbers.get(0);
I faced the same problem when i tried to open my old c# project into visual studio 2017 version. This problem arises typically when you try to open a project that you made with previous version of VS and open it with latest version. what i did is,i opened my project and delete the reference from my project,then added Microsoft outlook 12.0 object library and Microsoft office 12.0 object libraryMicrosoft outlook 12.0 object library
request.args
is a MultiDict with the parsed contents of the query string.
From the documentation of get
method:
get(key, default=None, type=None)
Return the default value if the requested data doesn’t exist. If type is provided and is a callable it should convert the value, return it or raise a ValueError if that is not possible.
This is super old, but I came across it and this worked for me.
<?php
//Get absolute path
$path = getcwd();
//strip the path at your root dir name and everything that follows it
$path = substr($path, 0, strpos($path, "root"));
echo "This Is Your Absolute Path: ";
echo $path; //This will output /home/public_html/
?>
Try this simple query. It works perfectly.
select * from Table1 where (FirstName,LastName,BirthDate) not in (select * from Table2);
First, Update your last perfect migration via this command :
Update-Database –TargetMigration
Example:
Update-Database -20180906131107_xxxx_xxxx
And, then delete your unused migration manually.
To answer your question literally, here's how to get the next value of a sequence without incrementing it:
SELECT
CASE WHEN is_called THEN
last_value + 1
ELSE
last_value
END
FROM sequence_name
Obviously, it is not a good idea to use this code in practice. There is no guarantee that the next row will really have this ID. However, for debugging purposes it might be interesting to know the value of a sequence without incrementing it, and this is how you can do it.
This query was very useful for me. It shows all values that don't have any matches
select FK_column from FK_table
WHERE FK_column NOT IN
(SELECT PK_column from PK_table)
You can do this in many way.
- Using
display: flex
#block_container {_x000D_
display: flex;_x000D_
justify-content: center;_x000D_
}
_x000D_
<div id="block_container">_x000D_
<div id="bloc1">Copyright © All Rights Reserved.</div>_x000D_
<div id="bloc2"><img src="..."></div>_x000D_
</div>
_x000D_
- Using
display: inline-block
#block_container {_x000D_
text-align: center;_x000D_
}_x000D_
#block_container > div {_x000D_
display: inline-block;_x000D_
vertical-align: middle;_x000D_
}
_x000D_
<div id="block_container">_x000D_
<div id="bloc1">Copyright © All Rights Reserved.</div>_x000D_
<div id="bloc2"><img src="..."></div>_x000D_
</div>
_x000D_
- using
table
<div>_x000D_
<table align="center">_x000D_
<tr>_x000D_
<td>_x000D_
<div id="bloc1">Copyright © All Rights Reserved.</div>_x000D_
</td>_x000D_
<td>_x000D_
<div id="bloc2"><img src="..."></div>_x000D_
</td>_x000D_
</tr>_x000D_
</table>_x000D_
</div>
_x000D_
Is there any better way than just looping through and manually comparing the two fields for each object and then breaking when found? That just seems so messy, looking for a better way.
If your concern is maintainability you could do what Fabian Steeg suggest ( that's what I would do ) although it probably isn't the "most efficient" ( because you have to sort the array first and then perform the binary search ) but certainly the cleanest and better option.
If you're really concerned with efficiency, you can create a custom List implementation that uses the field in your object as the hash and use a HashMap as storage. But probably this would be too much.
Then you have to change the place where you fill the data from ArrayList to YourCustomList.
Like:
List list = new ArrayList();
fillFromSoap( list );
To:
List list = new MyCustomSpecialList();
fillFromSoap( list );
The implementation would be something like the following:
class MyCustomSpecialList extends AbstractList {
private Map<Integer, YourObject> internalMap;
public boolean add( YourObject o ) {
internalMap.put( o.getThatFieldYouKnow(), o );
}
public boolean contains( YourObject o ) {
return internalMap.containsKey( o.getThatFieldYouKnow() );
}
}
Pretty much like a HashSet, the problem here is the HashSet relies on the good implementation of the hashCode method, which probably you don't have. Instead you use as the hash "that field you know" which is the one that makes one object equals to the other.
Of course implementing a List from the scratch lot more tricky than my snippet above, that's why I say the Fabian Steeg suggestion would be better and easier to implement ( although something like this would be more efficient )
Tell us what you did at the end.
The commands your are looking for are editor.action.copyLinesDownAction
and editor.action.copyLinesUpAction
.
You can see the associated keybindings by picking: File > Preferences > Keyboard Shortcuts
Windows:
Shift+Alt+Down and Shift+Alt+Up
Mac:
Shift+Option+Down and Shift+OptionUp
Linux:
Ctrl+Shift+Alt+Down and Ctrl+Shift+Alt+Up
(Might need to use numpad Down and Up for Linux)
Furthermore, commands editor.action.moveLinesUpAction
and editor.action.moveLinesDownAction
are the ones to move lines and they are bound to Alt+Down and Alt+Up on Windows and Mac and Ctrl+Down and Ctrl+Up on Linux.
to remove your current version you could just run:
sudo gem uninstall cocoapods
you can install a specific version of cocoa pods via the following command:
sudo gem install cocoapods -v 0.25.0
You can use older installed versions with following command:
pod _0.25.0_ setup
Visual Studio requires that DDEX Providers (Data Designer Extensibility) be registered by adding certain entries in the Windows Registry during installation (HKLM\SOFTWARE\Microsoft\VisualStudio\{version}\DataProviders
) . See DDEX Provider Registration in MSDN for more details.
similar to dhw's answer but you don't have to worry about setting the link as global in all the function because that is kind of difficult:
just use this code in your config file:
$sv_connection = mysqli_connect($dbhost, $dbuser, $dbpass, $dbname);
$db_connection = mysqli_select_db ($sv_connection, $dbname);
mysqli_set_charset($sv_connection, 'utf8'); //optional
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
exit();
}
function mysqljx_query($q){
global $sv_connection;
return mysqli_query($sv_connection, $q);
}
function mysqljx_fetch_array($r){
return mysqli_fetch_array($r);
}
function mysqljx_fetch_assoc($r){
return mysqli_fetch_assoc($r);
}
function mysqljx_num_rows($r){
return mysqli_num_rows($r);
}
function mysqljx_insert_id(){
global $sv_connection;
return mysqli_insert_id($sv_connection);
}
function mysqljx_real_escape_string($string){
global $sv_connection;
return mysqli_real_escape_string($sv_connection, $string);
}
-now do a search for php files that contain "mysql_" (i used total commander for that - Alt+F7, search for "*.php", find text "mysql_", Start search, Feed to listbox)
-drag&drop them all in Notepad++, there u press CTRL+H, Find what: "mysql_", Replace with "mysqljx_", "Replace All in All Opened Documents"
if you are worried that you have other functions than the ones listed above just replace one by one ("mysql_query" with "mysqljx_query", then mysql_fetch_array with "mysqljx_fetch_array" etc..) and then search again for "mysql_" and if its still there its a uncovered function and you can just add it same as the rest..
that is it
The self
name is used as the instance reference in class instances. It is only used in class method definitions. Don't use it in functions.
You also cannot reference local variables from other functions or methods with it. You can only reference instance or class attributes using it.
you can use valign="top"
on the td tag it is working perfectly for me.
Close
When you have finished using a socket, you can simply close its file descriptor with close; If there is still data waiting to be transmitted over the connection, normally close tries to complete this transmission. You can control this behavior using the SO_LINGER socket option to specify a timeout period; see Socket Options.
ShutDown
You can also shut down only reception or transmission on a connection by calling shutdown.
The shutdown function shuts down the connection of socket. Its argument how specifies what action to perform: 0 Stop receiving data for this socket. If further data arrives, reject it. 1 Stop trying to transmit data from this socket. Discard any data waiting to be sent. Stop looking for acknowledgement of data already sent; don’t retransmit it if it is lost. 2 Stop both reception and transmission.
The return value is 0 on success and -1 on failure.
There is a much easier way to run Java, no configuration needed:
Ctrl+Alt+N
, or press F1
and then select/type Run Code
, or right click the Text Editor and then click Run Code
in context menu, the code will be compiled and run, and the output will be shown in the Output Window.I don't know why this answer hasn't already been given:
Different callers of the same library will, in general, use different configurations. This implies that the configuration must reside in the executable application, and not in the class library.
You may create an app.config within the class library project. It will contain default configurations for items you create within the library. For instance, it will contain connection strings if you create an Entity Framework model within the class library.
However, these settings will not be used by the executable application calling the library. Instead, these settings may be copied from the library.dll.config file into the app.config or web.config of the caller, so that they may be changed to be specific to the caller, and to the environment into which the caller is deployed.
This is how it has been with .NET since Day 1.
// on your branch that holds the commit you want to pass
$ git log
// copy the commit hash found
$ git checkout [branch that will copy the commit]
$ git reset --hard [hash of the commit you want to copy from the other branch]
// remove the [brackets]
Other more useful commands here with explanation: Git Guide
I wanted something where I have access to base64 value to store into a list and for me adding event listener worked. You just need the FileReader which will read the image blob and return the base64 in the result.
createImageFromBlob(image: Blob) {
const reader = new FileReader();
const supportedImages = []; // you can also refer to some global variable
reader.addEventListener(
'load',
() => {
// reader.result will have the required base64 image
const base64data = reader.result;
supportedImages.push(base64data); // this can be a reference to global variable and store the value into that global list so as to use it in the other part
},
false
);
// The readAsDataURL method is used to read the contents of the specified Blob or File.
if (image) {
reader.readAsDataURL(image);
}
}
Final part is the readAsDataURL which is very important is being used to read the content of the specified Blob
rows and cols are required attributes, so you should have them whether you really need them or not. They set the number of rows and number of columns respectively.
EDIT: the name "lock" is a tricky one, its NPM trying to catch up with Yarn. It isn't a locked file whatsoever. package.json
is a user-fixed file, that once "installed" will generate node_modules folder tree and that tree will then be written in package-lock.json
. So you see, its the other way around - dependency versions will be pulled from package.json
as always, and package-lock.json
should be called package-tree.json
(hope this made my answer clearer, after so many downvotes)
A simplistic answer: package.json
have your dependencies as usual, while package-lock.json
is "an exact, and more importantly reproducible node_modules tree" (taken from npm docs itself).
As for the tricky name, its NPM trying to catch up with Yarn.
var str = " \n this is a string \n \n \n"_x000D_
_x000D_
console.log(str);_x000D_
console.log(str.trim());
_x000D_
String.trim()
removes whitespace from the beginning and end of strings... including newlines.
const myString = " \n \n\n Hey! \n I'm a string!!! \n\n";
const trimmedString = myString.trim();
console.log(trimmedString);
// outputs: "Hey! \n I'm a string!!!"
Here's an example fiddle: http://jsfiddle.net/BLs8u/
NOTE! it only trims the beginning and end of the string, not line breaks or whitespace in the middle of the string.
Hi sorry the code for the second one should be:
private static void getAll(CarList c1) {
ArrayList <Car> cars = c1.getAll(); // error incompatible type
for(Car item : cars)
{
System.out.println(item.getMake()
+ " "
+ item.getReg()
);
}
}
I have a class called CarList which contains the arraylist and its method, so in the tester class, i have basically this code to use that CarList class:
CarList c1; c1 = new CarList();
everything else works, such as adding and removing cars and displaying an inidividual car, i just need a code to display all cars in the arraylist.
If you want to do the validation for several functions you can add the logic inside a decorator like this:
def deco(func):
def wrapper(a,b,c):
if not isinstance(a, int)\
or not isinstance(b, int)\
or not isinstance(c, str):
raise TypeError
if not 0 < b < 10:
raise ValueError
if c == '':
raise ValueError
return func(a,b,c)
return wrapper
and use it:
@deco
def foo(a,b,c):
print 'ok!'
Hope this helps!
-- Sql Server 2005 Management studio
use Master
go
DECLARE @MyVar bigint
SET @myvar = (SELECT count(*) FROM spt_values);
SELECT @myvar
Result: 2346 (in my db)
-- Note: @myvar = @Myvar
Simple:
public static String decToHex(int dec)
{
return Integer.toHexString(dec);
}
As mentioned here: Java Convert integer to hex integer
All answers below have fixed width and height, which makes solution "not responsive".
To achieve the result but keep image responsive I used following:
HTML:
<div class="container">
<img style="background-image: url("https://i.imgur.com/XOmNCwY.jpg");" src="img/blank.gif">
</div>
.container img{
width: 100%;
height: auto;
background-size: cover;
background-repeat: no-repeat;
background-position: center;
}?
If you want midnight (0:00am) for the current date, you can just use the default constructor and zero out the time portions:
Date today = new Date();
today.setHours(0); today.setMinutes(0); today.setSeconds(0);
edit: update with Calendar
since those methods are deprecated
Calendar today = Calendar.getInstance();
today.clear(Calendar.HOUR); today.clear(Calendar.MINUTE); today.clear(Calendar.SECOND);
Date todayDate = today.getTime();
A cleaner way to specify the Gradle compiler arguments follow:
compileJava.options.compilerArgs = ['-Xlint:unchecked','-Xlint:deprecation']
I had an issue with github missing out on some case sensitive changes to folders. I needed to keep migration history so an example of how I changed "basicApp" folder in github to "basicapp"
$ git ls-files
$ git mv basicApp basicapp_temp
$ git add .
$ git commit -am "temporary change"
$ git push origin master
$ git mv basicapp_temp basicapp
$ git add .
$ git commit -am "change to desired name"
$ git push origin master
PS: git ls-files
will show you how github sees your folder name
Plain and simple:
If Jenkins sees the build step (which is a script too) exits with non-zero code, the build is marked with a red ball (= failed).
Why exactly that happens depends on your build script.
I wrote something similar from another point-of-view but maybe it will help to read it anyway: Why does Jenkins think my build succeeded?
You need to define the server instance in the Servers view.
In the box at the right bottom, press the Servers tab and add the server there. You by the way don't necessarily need to add it through global IDE preferences. It will be automagically added when you define it in Servers view. The preference you've modified just defines default locations, not the whole server instance itself. If you for instance upgrade/move the server, you can change the physical location there.
Once defining the server in the Servers view, you need to add the newly created server instance to the project through its Server and Targeted runtime preference.
The path is in the registry but usually you edit through this interface:
Control Panel
-> System
-> System settings
-> Environment Variables
.PATH
.c:\path;c:\path2
You can use pd.Series.isin
.
For "IN" use: something.isin(somewhere)
Or for "NOT IN": ~something.isin(somewhere)
As a worked example:
import pandas as pd
>>> df
country
0 US
1 UK
2 Germany
3 China
>>> countries_to_keep
['UK', 'China']
>>> df.country.isin(countries_to_keep)
0 False
1 True
2 False
3 True
Name: country, dtype: bool
>>> df[df.country.isin(countries_to_keep)]
country
1 UK
3 China
>>> df[~df.country.isin(countries_to_keep)]
country
0 US
2 Germany
Question is asking for two different things:
Second question has been already answered. For the first one, I would do it this way:
if($("#someElement").is(".test")){
// Has class test assigned, eventually combined with other classes
}
else{
// Does not have it
}
If String.Compare(string1,string2,True) Then
'perform operation
EndIf
Visual Studio 2008 does have a designer that allows you to add FK's. Just right-click the table... Table Properties, then go to the "Add Relations" section.
Use the format()
function with a '02x'
format.
>>> format(255, '02x')
'ff'
>>> format(2, '02x')
'02'
The 02
part tells format()
to use at least 2 digits and to use zeros to pad it to length, x
means lower-case hexadecimal.
The Format Specification Mini Language also gives you X
for uppercase hex output, and you can prefix the field width with #
to include a 0x
or 0X
prefix (depending on wether you used x
or X
as the formatter). Just take into account that you need to adjust the field width to allow for those extra 2 characters:
>>> format(255, '02X')
'FF'
>>> format(255, '#04x')
'0xff'
>>> format(255, '#04X')
'0XFF'
If in addition you want to pipe the output to a separate file, you can do:
On a Sun JVM:
-Xloggc:C:\whereever\jvm.log -verbose:gc -XX:+PrintGCDateStamps
ON an IBM JVM:
-Xverbosegclog:C:\whereever\jvm.log
I Found the esiest soltuion just wrap the button with div and put text-center align-items-center in it like this :
<div text-center align-items-center>
<buttonion-button block class="button-design " text-center>Sign In </button>
</div>
I have a workaround using jquery... although we cannot style a particular option, we can style the select itself - and use javascript to change the class of the select based on what is selected. It works sufficiently for simple cases.
$('select.potentially_red').on('change', function() {_x000D_
if ($(this).val()=='red') {_x000D_
$(this).addClass('option_red');_x000D_
} else {_x000D_
$(this).removeClass('option_red');_x000D_
}_x000D_
});_x000D_
$('select.potentially_red').each( function() {_x000D_
if ($(this).val()=='red') {_x000D_
$(this).addClass('option_red');_x000D_
} else {_x000D_
$(this).removeClass('option_red');_x000D_
}_x000D_
});
_x000D_
.option_red {_x000D_
background-color: #cc0000; _x000D_
font-weight: bold; _x000D_
font-size: 12px; _x000D_
color: white;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>_x000D_
<!-- The js will affect all selects which have the class 'potentially_red' -->_x000D_
<select name="color" class="potentially_red">_x000D_
<option value="red">Red</option>_x000D_
<option value="white">White</option>_x000D_
<option value="blue">Blue</option>_x000D_
<option value="green">Green</option>_x000D_
</select>
_x000D_
Note that the js is in two parts, the each
part for initializing everything on the page correctly, the .on('change', ...
part for responding to change. I was unable to mangle the js into a function to DRY it up, it breaks it for some reason
All answers contain part of the answer. Let me try to combine all in one.
Quick setup "file browser" mode on freshly installed nginx server:
Edit default config for nginx:
sudo vim /etc/nginx/sites-available/default
Add following to config section:
location /myfolder { # new url path
alias /home/username/myfolder/; # directory to list
autoindex on;
}
Create folder and sample file there:
mkdir -p /home/username/myfolder/
ls -la >/home/username/myfolder/mytestfile.txt
Restart nginx
sudo systemctl restart nginx
Check result: http://<your-server-ip>/myfolder
for example http://192.168.0.10/myfolder/
READ AT LEAST THE FIRST PARA HERE!
I know this is 3 years too late, but Matt's (accepted) answer is incomplete and will eventually get you into trouble. The key here is that, if you choose to use multipart/form-data
, the boundary must not appear in the file data that the server eventually receives.
This is not a problem for application/x-www-form-urlencoded
, because there is no boundary. x-www-form-urlencoded
can also always handle binary data, by the simple expedient of turning one arbitrary byte into three 7BIT
bytes. Inefficient, but it works (and note that the comment about not being able to send filenames as well as binary data is incorrect; you just send it as another key/value pair).
The problem with multipart/form-data
is that the boundary separator must not be present in the file data (see RFC 2388; section 5.2 also includes a rather lame excuse for not having a proper aggregate MIME type that avoids this problem).
So, at first sight, multipart/form-data
is of no value whatsoever in any file upload, binary or otherwise. If you don't choose your boundary correctly, then you will eventually have a problem, whether you're sending plain text or raw binary - the server will find a boundary in the wrong place, and your file will be truncated, or the POST will fail.
The key is to choose an encoding and a boundary such that your selected boundary characters cannot appear in the encoded output. One simple solution is to use base64
(do not use raw binary). In base64 3 arbitrary bytes are encoded into four 7-bit characters, where the output character set is [A-Za-z0-9+/=]
(i.e. alphanumerics, '+', '/' or '='). =
is a special case, and may only appear at the end of the encoded output, as a single =
or a double ==
. Now, choose your boundary as a 7-bit ASCII string which cannot appear in base64
output. Many choices you see on the net fail this test - the MDN forms docs, for example, use "blob" as a boundary when sending binary data - not good. However, something like "!blob!" will never appear in base64
output.
Thanks to thetalkingwalnut with answer Windows batch command(s) to read first line from text file I came up with the following solution:
@echo off
for /f "delims=" %%a in ('type sample.txt') do (
echo %%a
exit /b
)
You can resave the image and literally find the src file of your project and add it to that when you save. For me I had to go to netbeans and found my project and when that comes up it had 3 files src was the last. Don't click on any of them just save your pic there. That should work. Now resizing it may be a different issue and one I'm working on now lol
Here's a cross browser working function (usable for other than click handlers too):
function eventFire(el, etype){
if (el.fireEvent) {
el.fireEvent('on' + etype);
} else {
var evObj = document.createEvent('Events');
evObj.initEvent(etype, true, false);
el.dispatchEvent(evObj);
}
}
It is possible to get your second example (i.e., the one using a scoped enum) to work using the same syntax as unscoped enums. Furthermore, the solution is generic and will work for all scoped enums, versus writing code for each scoped enum (as shown in the answer provided by @ForEveR).
The solution is to write a generic operator<<
function which will work for any scoped enum. The solution employs SFINAE via std::enable_if
and is as follows.
#include <iostream>
#include <type_traits>
// Scoped enum
enum class Color
{
Red,
Green,
Blue
};
// Unscoped enum
enum Orientation
{
Horizontal,
Vertical
};
// Another scoped enum
enum class ExecStatus
{
Idle,
Started,
Running
};
template<typename T>
std::ostream& operator<<(typename std::enable_if<std::is_enum<T>::value, std::ostream>::type& stream, const T& e)
{
return stream << static_cast<typename std::underlying_type<T>::type>(e);
}
int main()
{
std::cout << Color::Blue << "\n";
std::cout << Vertical << "\n";
std::cout << ExecStatus::Running << "\n";
return 0;
}
cpp
is the preprocessor.
Run cpp filename.c
to output the preprocessed code, or better, redirect it to a file with
cpp filename.c > filename.preprocessed
.
This problem explained in MSDN Library and as I understand installing Microsoft's Redistributable Package can help.
But sometimes the following solution can be used (as developer's side solution):
In your Visual Studio, open Project properties -> Configuration properties -> C/C++ -> Code generation
and change option Runtime Library
to /MT
instead of /MD
In my case, the lines appended to the apache config file after installing passenger were as follows:
LoadModule passenger_module /usr/lib/ruby/gems/1.8/gems/passenger-.0.24/buildout/apache2/mod_passenger.so
PassengerRoot /usr/lib/ruby/gems/1.8/gems/passenger-4.0.24
PassengerDefaultRuby /usr/bin/ruby1.8
But the app requires Ruby 2.0.0 so it took me a while but finally, the error was resolved after specifying a different path using 'PassengerRuby' below, within the Apache virtual host config file for the app:
...
VirtualHost *:80>
ServerName www.yourhost.com
**PassengerRuby /home/user/.rvm/gems/ruby-2.0.0-p247**
# !!! Be sure to point DocumentRoot to 'public'!
DocumentRoot /somewhere/public
<Directory /somewhere/public>
# This relaxes Apache security settings.
AllowOverride all
# MultiViews must be turned off.
Options -MultiViews
</Directory>
</VirtualHost...
It's just like you did. And I'll give you a small tip for these kind of silly things: just use the browser url box to try js syntax. for example, write this: javascript:alert("test"+5)
and you have your answer.
The problem in your code is probably that this element does not exist in your document... maybe it's inside a form or something. You can test this too by writing in the url: javascript:alert(document.horseThumb_5)
to check where your mistake is.
In Visual Studio, go to the Tools menu, select Options, expand Source Control, (In a TFS environment, click Visual Studio Team Foundation Server), and click on the Configure User Tools button.
Click the Add button.
Enter/select the following options for Compare:
.*
Compare
C:\Program Files\Beyond Compare 3\BComp.exe
(replace with the proper path for your machine, including version number)%1 %2 /title1=%6 /title2=%7
If using Beyond Compare Professional (3-way Merge):
.*
Merge
C:\Program Files\Beyond Compare 3\BComp.exe
(replace with the proper path for your machine, including version number)%1 %2 %3 %4 /title1=%6 /title2=%7 /title3=%8 /title4=%9
If using Beyond Compare v3/v4 Standard or Beyond Compare v2 (2-way Merge):
.*
Merge
C:\Program Files\Beyond Compare 3\BComp.exe
(replace with the proper path for your machine, including version number)%1 %2 /savetarget=%4 /title1=%6 /title2=%7
If you use tabs in Beyond Compare
If you run Beyond Compare in tabbed mode, it can get confused when you diff or merge more than one set of files at a time from Visual Studio. To fix this, you can add the argument /solo
to the end of the arguments; this ensures each comparison opens in a new window, working around the issue with tabs.
If you want to remove all instances of 4 without needing to know the index:
LINQ: (.NET Framework 3.5)
int[] numbers = { 1, 3, 4, 9, 2 };
int numToRemove = 4;
numbers = numbers.Where(val => val != numToRemove).ToArray();
Non-LINQ: (.NET Framework 2.0)
static bool isNotFour(int n)
{
return n != 4;
}
int[] numbers = { 1, 3, 4, 9, 2 };
numbers = Array.FindAll(numbers, isNotFour).ToArray();
If you want to remove just the first instance:
LINQ: (.NET Framework 3.5)
int[] numbers = { 1, 3, 4, 9, 2, 4 };
int numToRemove = 4;
int numIndex = Array.IndexOf(numbers, numToRemove);
numbers = numbers.Where((val, idx) => idx != numIndex).ToArray();
Non-LINQ: (.NET Framework 2.0)
int[] numbers = { 1, 3, 4, 9, 2, 4 };
int numToRemove = 4;
int numIdx = Array.IndexOf(numbers, numToRemove);
List<int> tmp = new List<int>(numbers);
tmp.RemoveAt(numIdx);
numbers = tmp.ToArray();
Edit: Just in case you hadn't already figured it out, as Malfist pointed out, you need to be targetting the .NET Framework 3.5 in order for the LINQ code examples to work. If you're targetting 2.0 you need to reference the Non-LINQ examples.
<div class="modal show">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h4 class="modal-title">Modal title</h4>
</div>
<div class="modal-body">
<p>One fine body…</p>
</div>
</div><!-- /.modal-content -->
</div><!-- /.modal-dialog -->
i think this codepen can help you prevent modal close css and bootstrap
In C++ the std::string class implements the comparison operators, so you can perform the comparison using ==
just as you would expect:
if (string == "add") { ... }
When used properly, operator overloading is an excellent C++ feature.
I encountered the same thing. In package.json, change mongodb line to "mongodb": "^2.2.33". You will need to npm uninstall mongodb; then npm install to install this version.
This resolved the issue for me. Seems to be a bug or docs need to be updated.
Use \Q
to autoescape any potentially problematic characters in your variable.
if($text_to_search =~ m/\Q$search_string/) print "wee";
If I use the following query,
INSERT INTO xx_BLOB(ID,IMAGE)
VALUES(1,LOAD_FILE('E:/Images/xxx.png'));
Error: no such function: LOAD_FILE
Alejandro nailed it, adding clarification to the exception (Ubuntu or Debian) - I don't have the rep to add to the answer itself:
sudoers file:
sudo visudo
exception added:
www-data ALL=(ALL) NOPASSWD: ALL
You can use getContentAsString
method to get the response data as string.
String payload = "....";
String apiToTest = "....";
MvcResult mvcResult = mockMvc.
perform(post(apiToTest).
content(payload).
contentType(MediaType.APPLICATION_JSON)).
andReturn();
String responseData = mvcResult.getResponse().getContentAsString();
You can refer this link for test application.
You also use this below to expand the memory
export _JAVA_OPTIONS="-Xms512m -Xmx1024m -Xss512m -XX:MaxPermSize=1024m"
Xmx
specifies the maximum memory allocation pool for a Java virtual machine (JVM)
Xms
specifies the initial memory allocation pool.
Xss
setting memory size of thread stack
XX:MaxPermSize
: the maximum permanent generation size
You have a typo.
Change: headers.append('authentication', ${student.token});
To: headers.append('Authentication', student.token);
NOTE the Authentication is capitalized
you may also want to npm remove gulp-sass
and re-install gulp-sass if you've switched node versions.
The TableModel
behind the JTable handles all of the data behind the table. In order to add and remove rows from a table, you need to use a DefaultTableModel
To create the table with this model:
JTable table = new JTable(new DefaultTableModel(new Object[]{"Column1", "Column2"}));
To add a row:
DefaultTableModel model = (DefaultTableModel) table.getModel();
model.addRow(new Object[]{"Column 1", "Column 2", "Column 3"});
You can also remove rows with this method.
Full details on the DefaultTableModel can be found here
When we have a big/lengthy class say more than couple 100 lines of code we can't see everything on Monitor screen, hence we can't see overview (also called document items) of our class. Sometime we want to see overview of our class; its all methods, constants, properties etc at a glance. You can press Ctrl+6 in XCode to see overview of your class. You'll get a pop-up kind of Window aka Jump Bar.
By default, this jump bar doesn't have any buckets/sections. It's just one long list. (Though we can just start typing when jump Bar appears and it will search among jump bar items). Here comes the need of pragma mark
If you want to create sections in your Jump Bar then you can use pragma marks with relevant description. Now refer snapshot attached in question. There 'View lifeCycle' and 'A section dedicated ..' are sections created by pragma mark
s
just remove this because constructor don't have a return type like void it will be like this :
private Flow()
{
X = x;
Y = y;
}
Use the FileSystemObject
object, namely, its CreateFolder
and CopyFile
methods. Basically, this is what your script will look like:
Dim oFSO
Set oFSO = CreateObject("Scripting.FileSystemObject")
' Create a new folder
oFSO.CreateFolder "C:\MyFolder"
' Copy a file into the new folder
' Note that the destination folder path must end with a path separator (\)
oFSO.CopyFile "\\server\folder\file.ext", "C:\MyFolder\"
You may also want to add additional logic, like checking whether the folder you want to create already exists (because CreateFolder
raises an error in this case) or specifying whether or not to overwrite the file being copied. So, you can end up with this:
Const strFolder = "C:\MyFolder\", strFile = "\\server\folder\file.ext"
Const Overwrite = True
Dim oFSO
Set oFSO = CreateObject("Scripting.FileSystemObject")
If Not oFSO.FolderExists(strFolder) Then
oFSO.CreateFolder strFolder
End If
oFSO.CopyFile strFile, strFolder, Overwrite
To make it simple, remember slice has only one form:
s[start:end:step]
and here is how it works:
s
: an object that can be slicedstart
: first index to start iterationend
: last index, NOTE that end
index will not be included in the resulted slicestep
: pick element every step
indexAnother import thing: all start
,end
, step
can be omitted! And if they are omitted, their default value will be used: 0
,len(s)
,1
accordingly.
So possible variations are:
# Mostly used variations
s[start:end]
s[start:]
s[:end]
# Step-related variations
s[:end:step]
s[start::step]
s[::step]
# Make a copy
s[:]
NOTE: If start >= end
(considering only when step>0
), Python will return a empty slice []
.
The above part explains the core features on how slice works, and it will work on most occasions. However, there can be pitfalls you should watch out, and this part explains them.
The very first thing that confuses Python learners is that an index can be negative! Don't panic: a negative index means count backwards.
For example:
s[-5:] # Start at the 5th index from the end of array,
# thus returning the last 5 elements.
s[:-5] # Start at index 0, and end until the 5th index from end of array,
# thus returning s[0:len(s)-5].
Making things more confusing is that step
can be negative too!
A negative step means iterate the array backwards: from the end to start, with the end index included, and the start index excluded from the result.
NOTE: when step is negative, the default value for start
is len(s)
(while end
does not equal to 0
, because s[::-1]
contains s[0]
). For example:
s[::-1] # Reversed slice
s[len(s)::-1] # The same as above, reversed slice
s[0:len(s):-1] # Empty list
Be surprised: slice does not raise an IndexError when the index is out of range!
If the index is out of range, Python will try its best to set the index to 0
or len(s)
according to the situation. For example:
s[:len(s)+5] # The same as s[:len(s)]
s[-len(s)-5::] # The same as s[0:]
s[len(s)+5::-1] # The same as s[len(s)::-1], and the same as s[::-1]
Let's finish this answer with examples, explaining everything we have discussed:
# Create our array for demonstration
In [1]: s = [i for i in range(10)]
In [2]: s
Out[2]: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
In [3]: s[2:] # From index 2 to last index
Out[3]: [2, 3, 4, 5, 6, 7, 8, 9]
In [4]: s[:8] # From index 0 up to index 8
Out[4]: [0, 1, 2, 3, 4, 5, 6, 7]
In [5]: s[4:7] # From index 4 (included) up to index 7(excluded)
Out[5]: [4, 5, 6]
In [6]: s[:-2] # Up to second last index (negative index)
Out[6]: [0, 1, 2, 3, 4, 5, 6, 7]
In [7]: s[-2:] # From second last index (negative index)
Out[7]: [8, 9]
In [8]: s[::-1] # From last to first in reverse order (negative step)
Out[8]: [9, 8, 7, 6, 5, 4, 3, 2, 1, 0]
In [9]: s[::-2] # All odd numbers in reversed order
Out[9]: [9, 7, 5, 3, 1]
In [11]: s[-2::-2] # All even numbers in reversed order
Out[11]: [8, 6, 4, 2, 0]
In [12]: s[3:15] # End is out of range, and Python will set it to len(s).
Out[12]: [3, 4, 5, 6, 7, 8, 9]
In [14]: s[5:1] # Start > end; return empty list
Out[14]: []
In [15]: s[11] # Access index 11 (greater than len(s)) will raise an IndexError
---------------------------------------------------------------------------
IndexError Traceback (most recent call last)
<ipython-input-15-79ffc22473a3> in <module>()
----> 1 s[11]
IndexError: list index out of range
You can consider shapely:
from shapely.geometry import Point
from shapely.geometry.polygon import Polygon
point = Point(0.5, 0.5)
polygon = Polygon([(0, 0), (0, 1), (1, 1), (1, 0)])
print(polygon.contains(point))
From the methods you've mentioned I've only used the second, path.contains_points
, and it works fine. In any case depending on the precision you need for your test I would suggest creating a numpy bool grid with all nodes inside the polygon to be True (False if not). If you are going to make a test for a lot of points this might be faster (although notice this relies you are making a test within a "pixel" tolerance):
from matplotlib import path
import matplotlib.pyplot as plt
import numpy as np
first = -3
size = (3-first)/100
xv,yv = np.meshgrid(np.linspace(-3,3,100),np.linspace(-3,3,100))
p = path.Path([(0,0), (0, 1), (1, 1), (1, 0)]) # square with legs length 1 and bottom left corner at the origin
flags = p.contains_points(np.hstack((xv.flatten()[:,np.newaxis],yv.flatten()[:,np.newaxis])))
grid = np.zeros((101,101),dtype='bool')
grid[((xv.flatten()-first)/size).astype('int'),((yv.flatten()-first)/size).astype('int')] = flags
xi,yi = np.random.randint(-300,300,100)/100,np.random.randint(-300,300,100)/100
vflag = grid[((xi-first)/size).astype('int'),((yi-first)/size).astype('int')]
plt.imshow(grid.T,origin='lower',interpolation='nearest',cmap='binary')
plt.scatter(((xi-first)/size).astype('int'),((yi-first)/size).astype('int'),c=vflag,cmap='Greens',s=90)
plt.show()
, the results is this:
After trying and reading carefully, I solved it myself. Solution is to add the following line in build.gradle.
flavorDimensions "versionCode"
android {
compileSdkVersion 24
.....
flavorDimensions "versionCode"
}
Save code below as command.sql
USE restaurant
TRUNCATE `orders`;
TRUNCATE `order_items`;
Then run
mysql -u root <comands.sql> output.tab
With jquery
$("div#id").append('<a href=#>Your LINK TITLE</a>')
With javascript
var new_a = document.createElement('a');
new_a.setAttribute("href", "link url here");
new_a.innerHTML = "your link text";
//add new link to the DOM
document.appendChild(new_a);
Explanation in German but the code is a well-tested in-place implementation:
Private Sub QuickSort(ByRef Field() As String, ByVal LB As Long, ByVal UB As Long)
Dim P1 As Long, P2 As Long, Ref As String, TEMP As String
P1 = LB
P2 = UB
Ref = Field((P1 + P2) / 2)
Do
Do While (Field(P1) < Ref)
P1 = P1 + 1
Loop
Do While (Field(P2) > Ref)
P2 = P2 - 1
Loop
If P1 <= P2 Then
TEMP = Field(P1)
Field(P1) = Field(P2)
Field(P2) = TEMP
P1 = P1 + 1
P2 = P2 - 1
End If
Loop Until (P1 > P2)
If LB < P2 Then Call QuickSort(Field, LB, P2)
If P1 < UB Then Call QuickSort(Field, P1, UB)
End Sub
Invoked like this:
Call QuickSort(MyArray, LBound(MyArray), UBound(MyArray))
I just ran into this. As mentioned in this answer, using mode: "no-cors"
will give you an opaque response
, which doesn't seem to return data in the body.
opaque: Response for “no-cors” request to cross-origin resource. Severely restricted.
In my case I was using Express
. After I installed cors for Express and configured it and removed mode: "no-cors"
, I was returned a promise. The response data will be in the promise, e.g.
fetch('http://example.com/api/node', {
// mode: 'no-cors',
method: 'GET',
headers: {
Accept: 'application/json',
},
},
).then(response => {
if (response.ok) {
response.json().then(json => {
console.log(json);
});
}
});
untested.cmd
;@echo off
;Findstr -rbv ; %0 | powershell -c -
;goto:sCode
set-location "HKCU:\Software\Microsoft\Windows\CurrentVersion\Internet Settings"
set-location ZoneMap\Domains
new-item TESTSERVERNAME
set-location TESTSERVERNAME
new-itemproperty . -Name http -Value 2 -Type DWORD
;:sCode
;echo done
;pause & goto :eof
This depends on implementation, but the general rule is that the domain is checked against all SANs and the common name. If the domain is found there, then the certificate is ok for connection.
RFC 5280, section 4.1.2.6 says "The subject name MAY be carried in the subject field and/or the subjectAltName extension". This means that the domain name must be checked against both SubjectAltName extension and Subject property (namely it's common name parameter) of the certificate. These two places complement each other, and not duplicate it. And SubjectAltName is a proper place to put additional names, such as www.domain.com or www2.domain.com
Update: as per RFC 6125, published in 2011, the validator must check SAN first, and if SAN exists, then CN should not be checked. Note that RFC 6125 is relatively recent and there still exist certificates and CAs that issue certificates, which include the "main" domain name in CN and alternative domain names in SAN. I.e. by excluding CN from validation if SAN is present, you can deny some otherwise valid certificate.
This is a very common case in DataTables when it's not able to find the request field define in DataTable configuration.
For Example:
"aoColumns": [{
mData: 'mobile', sWidth: "149px;"
}, {
mData: 'name', sWidth: "121px;"
}, {
mData: 'productName', sWidth: "116px;"
}
}];
Here, If DataTable doesn't receive above mentioned properties. It'll generate this warning:
DataTables warning: Requested unknown parameter '0' from the data source for row '0'
To overcome this you just need to simply set a default value in "aoColumns"
For Example:
"aoColumns": [{
mData: 'mobile',sDefaultContent : '',sWidth: "149px;"
}, {
mData: 'name',sDefaultContent : '', sWidth: "121px;"
}, {
mData: 'productName',sDefaultContent : '', sWidth: "116px;"
}
}];
sDefaultContent will supress the warning.
Note: This property could be changed based on version of dataTables you are using.
SELECT STR_TO_DATE(dateString, '%d/%m/%y') FROM yourTable...
fmod
is the standard C function for handling floating-point modulus; I imagine your source was saying that Java handles floating-point modulus the same as C's fmod
function. In Java you can use the %
operator on doubles the same as on integers:
int x = 5 % 3; // x = 2
double y = .5 % .3; // y = .2
This could be the possible solution
var str = 'RACK NO:Stock;PRODUCT TYPE:Stock Sale;PART N0:0035719061;INDEX NO:21A627 042;PART NAME:SPRING;';
var newstr = str.split(':')[1].split(';')[0]; // return value as 'Stock'
console.log('stringvalue',newstr)
It is not possible yet to search for content using multiple tags, for now only single tags are supported.
Firstly, the Instagram API endpoint "tags" required OAuth authentication.
This is not quite true, you only need an API-Key. Just register an application and add it to your requests. Example:
https://api.instagram.com/v1/users/userIdYouWantToGetMediaFrom/media/recent?client_id=yourAPIKey
Also note that the username is not the user-id. You can look up user-Id`s here.
A workaround for searching multiple keywords would be if you start one request for each tag and compare the results on your server. Of course this could slow down your site depending on how much keywords you want to compare.
For inserting a separator:
df$x <- paste(df$n, "-", df$s)
For plaintext email using JavaScript, you may also use \r
with encodeURIComponent()
.
For example, this message:
hello\rthis answer is now well formated\rand it contains good knowleadge\rthat is why I am up voting
URI Encoded, results in:
hello%0Dthis%20answer%20is%20now%20well%20formated%0Dand%20it%20contains%20good%20knowleadge%0Dthat%20is%20why%20I%20am%20up%20voting
And, using the href:
mailto:[email protected]?body=hello%0Dthis%20answer%20is%20now%20well%20formated%0Dand%20it%20contains%20good%20knowleadge%0Dthat%20is%20why%20I%20am%20up%20voting
Will result in the following email body text:
hello
this answer is now well formated
and it contains good knowleadge
that is why I am up voting
inputString = input("Enter a String:")
countedArray = {}
for char in inputString:
if char in countedArray:
countedArray[char] += 1
else:
countedArray[char] = 1
print(countedArray)
Put these permission outside the <application>
tag preferable before the tag, I tried it and it works for me.
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
To use the fastboot command you first need to put your device in fastboot mode:
$ adb reboot bootloader
Once the device is in fastboot mode, you can boot it with your own kernel, for example:
$ fastboot boot myboot.img
The above will only boot your kernel once and the old kernel will be used again when you reboot the device. To replace the kernel on the device, you will need to flash it to the device:
$ fastboot flash boot myboot.img
Hope that helps.
the term "smart pointer" includes shared pointers, auto pointers, locking pointers and others. you meant to say auto pointer (more ambiguously known as "owning pointer"), not smart pointer.
Dumb pointers (T*) are never the best solution. They make you do explicit memory management, which is verbose, error prone, and sometimes nigh impossible. But more importantly, they don't signal your intent.
Auto pointers delete the pointee at destruction. For arrays, prefer encapsulations like vector and deque. For other objects, there's very rarely a need to store them on the heap - just use locals and object composition. Still the need for auto pointers arises with functions that return heap pointers -- such as factories and polymorphic returns.
Shared pointers delete the pointee when the last shared pointer to it is destroyed. This is useful when you want a no-brainer, open-ended storage scheme where expected lifetime and ownership can vary widely depending on the situation. Due to the need to keep an (atomic) counter, they're a bit slower than auto pointers. Some say half in jest that shared pointers are for people who can't design systems -- judge for yourself.
For an essential counterpart to shared pointers, look up weak pointers too.
String jsonErrorString=((HttpClientErrorException)exception).getResponseBodyAsString();
JSONObject jsonObj=null;
String errorDetails=null;
String status=null;
try {
jsonObj = new JSONObject(jsonErrorString);
int index =jsonObj.getString("detail").indexOf(":");
errorDetails=jsonObj.getString("detail").substring(index);
status=jsonObj.getString("status");
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
item.put("status", status);
item.put("errordetailMsg", errorDetails);
sudo apt-get install php-mbstring
# if your are using php 7.1
sudo apt-get install php7.1-mbstring
# if your are using php 7.2
sudo apt-get install php7.2-mbstring
Pre-ES6
Always 2 bytes per character. UTF-16 is not allowed because the spec says "values must be 16-bit unsigned integers". Since UTF-16 strings can use 3 or 4 byte characters, it would violate 2 byte requirement. Crucially, while UTF-16 cannot be fully supported, the standard does require that the two byte characters used are valid UTF-16 characters. In other words, Pre-ES6 JavaScript strings support a subset of UTF-16 characters.
ES6 and later
2 bytes per character, or 5 or more bytes per character. The additional sizes come into play because ES6 (ECMAScript 6) adds support for Unicode code point escapes. Using a unicode escape looks like this: \u{1D306}
Practical notes
This doesn't relate to the internal implemention of a particular engine. For example, some engines use data structures and libraries with full UTF-16 support, but what they provide externally doesn't have to be full UTF-16 support. Also an engine may provide external UTF-16 support as well but is not mandated to do so.
For ES6, practically speaking characters will never be more than 5 bytes long (2 bytes for the escape point + 3 bytes for the Unicode code point) because the latest version of Unicode only has 136,755 possible characters, which fits easily into 3 bytes. However this is technically not limited by the standard so in principal a single character could use say, 4 bytes for the code point and 6 bytes total.
Most of the code examples here for calculating byte size don't seem to take into account ES6 Unicode code point escapes, so the results could be incorrect in some cases.
You can also remove the line
require: 'ngModel',
if you don't need ngModel
in this directive. Removing ngModel
will allow you to make a directive without thatngModel
error.
I found solution from here. And its working for me.
Check this, it may help you.
<key>NSAppTransportSecurity</key>
<dict>
<key>NSExceptionDomains</key>
<dict>
<key>myDomain.com</key>
<dict>
<!--Include to allow subdomains-->
<key>NSIncludesSubdomains</key>
<true/>
<!--Include to allow HTTP requests-->
<key>NSTemporaryExceptionAllowsInsecureHTTPLoads</key>
<true/>
<!--Include to specify minimum TLS version-->
<key>NSTemporaryExceptionMinimumTLSVersion</key>
<string>TLSv1.1</string>
</dict>
</dict>
</dict>
In Swift
extension String {
var isPhoneNumber: Bool {
let PHONE_REGEX = "^[7-9][0-9]{9}$";
let phoneTest = NSPredicate(format: "SELF MATCHES %@", PHONE_REGEX)
let result = phoneTest.evaluate(with: self)
return result
}
}
The files in your working copy might look exactly the same after, but they are still very different actions -- the repository is in a completely different state, and you will have different options available to you after reverting than "updating" to an old revision.
Briefly, "update to" only affects your working copy, but "reverse merge and commit" will affect the repository.
If you "update" to an old revision, then the repository has not changed: in your example, the HEAD revision is still 100. You don't have to commit anything, since you are just messing around with your working copy. If you make modifications to your working copy and try to commit, you will be told that your working copy is out-of-date, and you will need to update before you can commit. If someone else working on the same repository performs an "update", or if you check out a second working copy, it will be r100.
However, if you "reverse merge" to an old revision, then your working copy is still based on the HEAD (assuming you are up-to-date) -- but you are creating a new revision to supersede the unwanted changes. You have to commit these changes, since you are changing the repository. Once done, any updates or new working copies based on the HEAD will show r101, with the contents you just committed.
If you are actually looking for the index number (and not the value) of the selected option then it would be
document.forms[0].elements["CCards"].selectedIndex
/* You may need to change document.forms[0] to reference the correct form */
or using jQuery
$('select[name="CCards"]')[0].selectedIndex
I had also similar problem. In my case brokerUrl was not configured properly. So that's way I received following Error:
Cause: Error While attempting to add new Connection to the pool: nested exception is javax.jms.JMSException: Could not connect to broker URL : tcp://localhost:61616. Reason: java.net.ConnectException: Connection refused
& I resolved it following way.
ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory();
connectionFactory.setBrokerURL("tcp://hostname:61616");
connectionFactory.setUserName("admin");
connectionFactory.setPassword("admin");
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>
I know this is an older post, but someone will stumble across it in a Google search and it also looks like some questions the OP asked in comments weren't specifically addressed. Also, please go easy on me since this is my first answer posted on SO. :)
To redirect the output to a file using a dynamically generated file name, my go-to (read: quick & dirty) approach is the second solution offered by @dbenham. So for example, this:
@echo off
> filename_prefix-%DATE:~-4%-%DATE:~4,2%-%DATE:~7,2%_%time:~0,2%%time:~3,2%%time:~6,2%.log (
echo Your Name Here
echo Beginning Date/Time: %DATE:~-4%-%DATE:~4,2%-%DATE:~7,2%_%time:~0,2%%time:~3,2%%time:~6,2%.log
REM do some stuff here
echo Your Name Here
echo Ending Date/Time: %DATE:~-4%-%DATE:~4,2%-%DATE:~7,2%_%time:~0,2%%time:~3,2%%time:~6,2%.log
)
Will create a file like what you see in this screenshot of the file in the target directory
That will contain this output:
Your Name Here
Beginning Date/Time: 2016-09-16_141048.log
Your Name Here
Ending Date/Time: 2016-09-16_141048.log
Also keep in mind that this solution is locale-dependent, so be careful how/when you use it.
JPA translates entity state transitions to SQL statements, like INSERT, UPDATE or DELETE.
When you persist
an entity, you are scheduling the INSERT statement to be executed when the EntityManager
is flushed, either automatically or manually.
when you remove
an entity, you are scheduling the DELETE statement, which will be executed when the Persistence Context is flushed.
For convenience, JPA allows you to propagate entity state transitions from parent entities to child one.
So, if you have a parent Post
entity that has a @OneToMany
association with the PostComment
child entity:
The comments
collection in the Post
entity is mapped as follows:
@OneToMany(
mappedBy = "post",
cascade = CascadeType.ALL,
orphanRemoval = true
)
private List<Comment> comments = new ArrayList<>();
The cascade
attribute tells the JPA provider to pass the entity state transition from the parent Post
entity to all PostComment
entities contained in the comments
collection.
So, if you remove the Post
entity:
Post post = entityManager.find(Post.class, 1L);
assertEquals(2, post.getComments().size());
entityManager.remove(post);
The JPA provider is going to remove the PostComment
entity first, and when all child entities are deleted, it will delete the Post
entity as well:
DELETE FROM post_comment WHERE id = 1
DELETE FROM post_comment WHERE id = 2
DELETE FROM post WHERE id = 1
When you set the orphanRemoval
attribute to true
, the JPA provider is going to schedule a remove
operation when the child entity is removed from the collection.
So, in our case,
Post post = entityManager.find(Post.class, 1L);
assertEquals(2, post.getComments().size());
PostComment postComment = post.getComments().get(0);
assertEquals(1L, postComment.getId());
post.getComments().remove(postComment);
The JPA provider is going to remove the associated post_comment
record since the PostComment
entity is no longer referenced in the comments
collection:
DELETE FROM post_comment WHERE id = 1
The ON DELETE CASCADE
is defined at the FK level:
ALTER TABLE post_comment
ADD CONSTRAINT fk_post_comment_post_id
FOREIGN KEY (post_id) REFERENCES post
ON DELETE CASCADE;
Once you do that, if you delete a post
row:
DELETE FROM post WHERE id = 1
All the associated post_comment
entities are removed automatically by the database engine. However, this can be a very dangerous operation if you delete a root entity by mistake.
The advantage of the JPA cascade
and orphanRemoval
options is that you can also benefit from optimistic locking to prevent lost updates.
If you use the JPA cascading mechanism, you don't need to use DDL-level ON DELETE CASCADE
, which can be a very dangerous operation if you remove a root entity that has many child entities on multiple levels.
My own implementation of generic restTemplate call:
private <REQ, RES> RES queryRemoteService(String url, HttpMethod method, REQ req, Class reqClass) {
RES result = null;
try {
long startMillis = System.currentTimeMillis();
// Set the Content-Type header
HttpHeaders requestHeaders = new HttpHeaders();
requestHeaders.setContentType(new MediaType("application","json"));
// Set the request entity
HttpEntity<REQ> requestEntity = new HttpEntity<>(req, requestHeaders);
// Create a new RestTemplate instance
RestTemplate restTemplate = new RestTemplate();
// Add the Jackson and String message converters
restTemplate.getMessageConverters().add(new MappingJackson2HttpMessageConverter());
restTemplate.getMessageConverters().add(new StringHttpMessageConverter());
// Make the HTTP POST request, marshaling the request to JSON, and the response to a String
ResponseEntity<RES> responseEntity = restTemplate.exchange(url, method, requestEntity, reqClass);
result = responseEntity.getBody();
long stopMillis = System.currentTimeMillis() - startMillis;
Log.d(TAG, method + ":" + url + " took " + stopMillis + " ms");
} catch (Exception e) {
Log.e(TAG, e.getMessage());
}
return result;
}
To add some context, I'm consuming RESTful service with this, hence all requests and responses are wrapped into small POJO like this:
public class ValidateRequest {
User user;
User checkedUser;
Vehicle vehicle;
}
and
public class UserResponse {
User user;
RequestResult requestResult;
}
Method which calls this is the following:
public User checkUser(User user, String checkedUserName) {
String url = urlBuilder()
.add(USER)
.add(USER_CHECK)
.build();
ValidateRequest request = new ValidateRequest();
request.setUser(user);
request.setCheckedUser(new User(checkedUserName));
UserResponse response = queryRemoteService(url, HttpMethod.POST, request, UserResponse.class);
return response.getUser();
}
And yes, there's a List dto-s as well.
Instead of using a bat file, you can simply create a Scheduled Task. Most of the time you define just one action. In this case, create two actions with the NET
command. The first one to stop the service, the second one to start the service. Give them a STOP
and START
argument, followed by the service name.
In this example we restart the Printer Spooler service.
NET STOP "Print Spooler"
NET START "Print Spooler"
Note: unfortunately NET RESTART <service name>
does not exist.
I don't think you can, and CSS is supposed to describe how the page looks not what it does, so even if you could, it's not really how you should be using it.
Perhaps you should think about using JQuery to apply common functionality to your form components?
Use this to get an array with the local users and the groups they are member of:
Get-LocalUser |
ForEach-Object {
$user = $_
return [PSCustomObject]@{
"User" = $user.Name
"Groups" = Get-LocalGroup | Where-Object { $user.SID -in ($_ | Get-LocalGroupMember | Select-Object -ExpandProperty "SID") } | Select-Object -ExpandProperty "Name"
}
}
To get an array with the local groups and their members:
Get-LocalGroup |
ForEach-Object {
$group = $_
return [PSCustomObject]@{
"Group" = $group.Name
"Members" = $group | Get-LocalGroupMember | Select-Object -ExpandProperty "Name"
}
}
Keep in mind that search spiders don't index JS code. So, if you put your URL
inside JS code and make sure to also include it inside a traditional HTML link elsewhere on the page.
That is, if you want the linked pages to be indexed by Google, etc.
The above solution left blue border around each cell in my case.
This is the solution that worked for me. It is very simple, just add this to your DataGrid
. You can change it from a SolidColorBrush
to any other brush such as linear gradient.
<DataGrid.Resources>
<SolidColorBrush x:Key="{x:Static SystemColors.HighlightBrushKey}"
Color="#FF0000"/>
</DataGrid.Resources>
If you want to distinguish between empty values and missing values you can use jQuery to check like this.
<div id="element" data-foo="bar" data-empty=""></div>
<script>
"foo" in $('#element').data(); // true
"empty" in $('#element').data(); // true
"other" in $('#element').data(); // false
</script>
So from the original question you'd do this.
if("timer" in $("#dataTable").data()) {
// code
}
A tree in Python is quite simple. Make a class that has data and a list of children. Each child is an instance of the same class. This is a general n-nary tree.
class Node(object):
def __init__(self, data):
self.data = data
self.children = []
def add_child(self, obj):
self.children.append(obj)
Then interact:
>>> n = Node(5)
>>> p = Node(6)
>>> q = Node(7)
>>> n.add_child(p)
>>> n.add_child(q)
>>> n.children
[<__main__.Node object at 0x02877FF0>, <__main__.Node object at 0x02877F90>]
>>> for c in n.children:
... print c.data
...
6
7
>>>
This is a very basic skeleton, not abstracted or anything. The actual code will depend on your specific needs - I'm just trying to show that this is very simple in Python.
It's a pity to use .NET and not use collections and lambda to save your time and code lines This is an example of how this works: Transform yourDataTable to Enumerable, filter it if you want , according a "FILTER_ROWS_FIELD" column, and if you want, group your data by a "A_GROUP_BY_FIELD". Then get the count, the sum, or whatever you wish. If you want a count and a sum without grouby don't group the data
var groupedData = from b in yourDataTable.AsEnumerable().Where(r=>r.Field<int>("FILTER_ROWS_FIELD").Equals(9999))
group b by b.Field<string>("A_GROUP_BY_FIELD") into g
select new
{
tag = g.Key,
count = g.Count(),
sum = g.Sum(c => c.Field<double>("rvMoney"))
};
Sometimes it may happen that you run multiple applications on the same java VM. In Case you have tried all the other solutions described above and it didnt work. Try Running your process by running it on a newly created java VM by passing vmargs
-agentlib:jdwp=transport=dt_socket,server=y,address=10049,suspend=n .
Here address is what the vm takes.
There are a few things wrong here:
First, terminology. "Epoch" refers to the starting point of something. The "Unix Epoch" is Midnight, January 1st 1970 UTC. You can't convert an arbitrary "date string to epoch". You probably meant "Unix Time", which is often erroneously called "Epoch Time".
.unix()
returns Unix Time in whole seconds, but the default moment
constructor accepts a timestamp in milliseconds. You should instead use .valueOf()
to return milliseconds. Note that calling .unix()*1000
would also work, but it would result in a loss of precision.
You're parsing a string without providing a format specifier. That isn't a good idea, as values like 1/2/2014 could be interpreted as either February 1st or as January 2nd, depending on the locale of where the code is running. (This is also why you get the deprecation warning in the console.) Instead, provide a format string that matches the expected input, such as:
moment("10/15/2014 9:00", "M/D/YYYY H:mm")
.calendar()
has a very specific use. If you are near to the date, it will return a value like "Today 9:00 AM". If that's not what you expected, you should use the .format()
function instead. Again, you may want to pass a format specifier.
To answer your questions in comments, No - you don't need to call .local()
or .utc()
.
Putting it all together:
var ts = moment("10/15/2014 9:00", "M/D/YYYY H:mm").valueOf();
var m = moment(ts);
var s = m.format("M/D/YYYY H:mm");
alert("Values are: ts = " + ts + ", s = " + s);
On my machine, in the US Pacific time zone, it results in:
Values are: ts = 1413388800000, s = 10/15/2014 9:00
Since the input value is interpreted in terms of local time, you will get a different value for ts
if you are in a different time zone.
Also note that if you really do want to work with whole seconds (possibly losing precision), moment has methods for that as well. You would use .unix()
to return the timestamp in whole seconds, and moment.unix(ts)
to parse it back to a moment.
var ts = moment("10/15/2014 9:00", "M/D/YYYY H:mm").unix();
var m = moment.unix(ts);
You can also add a file handler or rotating file handler to send your logs to a local file: http://docs.python.org/2/library/logging.handlers.html
I recommend you start reading the documentation (4.6.18. Formatting cells). When applying a lot of formatting it's better to use applyFromArray()
According to the documentation this method is also suppose to be faster when you're setting many style properties. There's an annex where you can find all the possible keys for this function.
This will work for you:
$phpExcel = new PHPExcel();
$styleArray = array(
'font' => array(
'bold' => true,
'color' => array('rgb' => 'FF0000'),
'size' => 15,
'name' => 'Verdana'
));
$phpExcel->getActiveSheet()->getCell('A1')->setValue('Some text');
$phpExcel->getActiveSheet()->getStyle('A1')->applyFromArray($styleArray);
To apply font style to complete excel document:
$styleArray = array(
'font' => array(
'bold' => true,
'color' => array('rgb' => 'FF0000'),
'size' => 15,
'name' => 'Verdana'
));
$phpExcel->getDefaultStyle()
->applyFromArray($styleArray);
This is your dataArray
:
[
{
"id":28,
"Title":"Sweden"
},
{
"id":56,
"Title":"USA"
},
{
"id":89,
"Title":"England"
}
]
Then parseJson
can be used:
$(jQuery.parseJSON(JSON.stringify(dataArray))).each(function() {
var ID = this.id;
var TITLE = this.Title;
});