Partial dependence is solved for arriving to a relation in 2NF but 2NF is a "stepping stone" (C. Date) for solving any transitive dependency and arriving to a relation in 3NF (which is the operational target). However, the most interested thing on partial dependence is that it is a particular case of the own transitive dependency. This was demostrated by P. A. Berstein in 1976: IF {(x•y)?z but y?z} THEN {(x•y)?y & y?z}. The 3NF synthesizer algorithm of Berstein does not need doing distintions among these two type of relational defects.
This is html part
<a href="{{route('download',$details->report_id)}}" type="button" class="btn btn-primary download" data-report_id="{{$details->report_id}}" >Download</a>
This is Route :
Route::get('/download/{id}', 'users\UserController@getDownload')->name('download')->middleware('auth');
This is function :
public function getDownload(Request $request,$id)
{
$file= public_path(). "/pdf/"; //path of your directory
$headers = array(
'Content-Type: application/pdf',
);
return Response::download($file.$pdfName, 'filename.pdf', $headers);
}
Suppose the data is in the B column, write in the C column the formula:
=SUBSTITUTE(B1," ","")
Copy&Paste the formula in the whole C column.
edit: using commas or semicolons as parameters separator depends on your regional settings (I have to use the semicolons). This is weird I think. Thanks to @tocallaghan and @pablete for pointing this out.
You can use subList(int fromIndex, int toIndex)
to get a view of a portion of the original list.
From the API:
Returns a view of the portion of this list between the specified
fromIndex
, inclusive, andtoIndex
, exclusive. (IffromIndex
andtoIndex
are equal, the returned list is empty.) The returned list is backed by this list, so non-structural changes in the returned list are reflected in this list, and vice-versa. The returned list supports all of the optional list operations supported by this list.
Example:
List<Integer> numbers = new ArrayList<Integer>(
Arrays.asList(5,3,1,2,9,5,0,7)
);
List<Integer> head = numbers.subList(0, 4);
List<Integer> tail = numbers.subList(4, 8);
System.out.println(head); // prints "[5, 3, 1, 2]"
System.out.println(tail); // prints "[9, 5, 0, 7]"
Collections.sort(head);
System.out.println(numbers); // prints "[1, 2, 3, 5, 9, 5, 0, 7]"
tail.add(-1);
System.out.println(numbers); // prints "[1, 2, 3, 5, 9, 5, 0, 7, -1]"
If you need these chopped lists to be NOT a view, then simply create a new List
from the subList
. Here's an example of putting a few of these things together:
// chops a list into non-view sublists of length L
static <T> List<List<T>> chopped(List<T> list, final int L) {
List<List<T>> parts = new ArrayList<List<T>>();
final int N = list.size();
for (int i = 0; i < N; i += L) {
parts.add(new ArrayList<T>(
list.subList(i, Math.min(N, i + L)))
);
}
return parts;
}
List<Integer> numbers = Collections.unmodifiableList(
Arrays.asList(5,3,1,2,9,5,0,7)
);
List<List<Integer>> parts = chopped(numbers, 3);
System.out.println(parts); // prints "[[5, 3, 1], [2, 9, 5], [0, 7]]"
parts.get(0).add(-1);
System.out.println(parts); // prints "[[5, 3, 1, -1], [2, 9, 5], [0, 7]]"
System.out.println(numbers); // prints "[5, 3, 1, 2, 9, 5, 0, 7]" (unmodified!)
One possible reason is that you have multiple python executables in your environment, for example 2.6.x, 2.7.x or virtaulenv. You might install the package into one of them and run your script with another.
Type python in the prompt, and press the tab key to see what versions of Python in your environment.
Ctrl-Alt-Down: copies current line or selected lines to below
Ctrl-Alt-Up:: copies current line or selected lines to above
Ctrl-Shift-L: brings up a List of shortcut keys
See Windows/Preference->General->Keys.
Because the SCHEDULER_ADMIN role is a powerful role allowing a grantee to execute code as any user, you should consider granting individual Scheduler system privileges instead. Object and system privileges are granted using regular SQL grant syntax. An example is if the database administrator issues the following statement:
GRANT CREATE JOB TO scott;
After this statement is executed, scott can create jobs, schedules, or programs in his schema.
copied from http://docs.oracle.com/cd/B19306_01/server.102/b14231/schedadmin.htm#i1006239
CHARINDEX is what you are looking for
select CHARINDEX('@', '[email protected]')
-----------
8
(1 row(s) affected)
-or-
select CHARINDEX('c', 'abcde')
-----------
3
(1 row(s) affected)
One more way -
select * from <table> where id=(select max(id) from <table>)
Also you can check on this link -
"py -m pip install requests" works fine with Windows and its up gradation. Just change the path after installing Python 3.4 in the command prompt and type in "py -m pip install requests"command prompt. pip install
If you're converting an HTML doc into a PDF page, but the page spills onto two pages, try reducing the font size. Of course you can also decrease the spacing between paragraphs (with the CSS margin-top/margin-bottom styles), or even the left and right gutters with margins. But to my eye, keep things in proportion and just make the text a little smaller:
p { font-size: 90%; }
or
body { font-size: 9.5pt }
You are not passing the array as copy. It is only a pointer pointing to the address where the first element of the array is in memory.
You could use following method to do that:
public static Output GetEnumItem<Output, Input>(Input input)
{
//Output type checking...
if (typeof(Output).BaseType != typeof(Enum))
throw new Exception("Exception message...");
//Input type checking: string type
if (typeof(Input) == typeof(string))
return (Output)Enum.Parse(typeof(Output), (dynamic)input);
//Input type checking: Integer type
if (typeof(Input) == typeof(Int16) ||
typeof(Input) == typeof(Int32) ||
typeof(Input) == typeof(Int64))
return (Output)(dynamic)input;
throw new Exception("Exception message...");
}
Note:this method only is a sample and you can improve it.
As the previous comment mentioned you can't do this in Postman. however, I found this Chrome app in the web store. It is very simple, but it's working really well with my local web socket connections.
I do this to make sure they remember to print landscape, which is necessary for a lot of pages on a lot of printers.
<a href="javascript:alert('Please be sure to set your printer to Landscape.');window.print();">Print Me...</a>
or
<body onload="alert('Please be sure to set your printer to Landscape.');window.print();">
etc.
</body>
Replace double quotes with single ones:
INSERT
INTO MY.LOGFILE
(id,severity,category,logdate,appendername,message,extrainfo)
VALUES (
'dee205e29ec34',
'FATAL',
'facade.uploader.model',
'2013-06-11 17:16:31',
'LOGDB',
NULL,
NULL
)
In SQL, double quotes are used to mark identifiers, not string constants.
I use this to correct names. It basically works on the concept of changing a character to uppercase if it follows a specific pattern, in this case I've gone for space, dash of "Mc".
private String CorrectName(String name)
{
List<String> StringsToCapitalizeAfter = new List<String>() { " ", "-", "Mc" };
StringBuilder NameBuilder = new StringBuilder();
name.Select(c => c.ToString()).ToList().ForEach(c =>
{
c = c.ToLower();
StringsToCapitalizeAfter.ForEach(s =>
{
if(String.IsNullOrEmpty(NameBuilder.ToString()) || NameBuilder.ToString().EndsWith(s))
{
c = c.ToUpper();
}
});
NameBuilder.Append(c);
});
return NameBuilder.ToString();
}
The accepted answer using button.tag
as information carrier which button has actually been pressed is solid and widely accepted but rather limited since a tag can only hold Int
s.
You can make use of Swift's awesome closure-capabilities to have greater flexibility and cleaner code.
I recommend this article: How to properly do buttons in table view cells using Swift closures by Jure Zove.
Applied to your problem:
Declare a variable that can hold a closure in your tableview cell like
var buttonTappedAction : ((UITableViewCell) -> Void)?
Add an action when the button is pressed that only executes the closure. You did it programmatically with cell.yes.targetForAction("connected", withSender: self)
but I would prefer an @IBAction
outlet :-)
@IBAction func buttonTap(sender: AnyObject) {
tapAction?(self)
}
func connected(sender: UIButton!) { ... }
as a closure to cell.tapAction = {<closure content here...>}
. Please refer to the article for a more precise explanation and please don't forget to break reference cycles when capturing variables from the environment.Check out this solution VBA Compact Current Database.
Basically it says this should work
Public Sub CompactDB()
CommandBars("Menu Bar").Controls("Tools").Controls ("Database utilities"). _
Controls("Compact and repair database...").accDoDefaultAction
End Sub
If you need to store the ZIP Code in a character array, zipcode[]
, you can use this:
snprintf(zipcode, 6, "%05.5d", atoi(zipcode));
You can also use query
which is very readable in my opinion and straightforward to use:
import pandas as pd
df = pd.DataFrame({'A': [1, 2, 3, 4], 'B': [10, 20, 50, 80], 'C': [6, 7, 8, 9]})
df = df.set_index(['A', 'B'])
C
A B
1 10 6
2 20 7
3 50 8
4 80 9
For what you had in mind you can now simply do:
df.query('A == 1')
C
A B
1 10 6
You can also have more complex queries using and
df.query('A >= 1 and B >= 50')
C
A B
3 50 8
4 80 9
and or
df.query('A == 1 or B >= 50')
C
A B
1 10 6
3 50 8
4 80 9
You can also query on different index levels, e.g.
df.query('A == 1 or C >= 8')
will return
C
A B
1 10 6
3 50 8
4 80 9
If you want to use variables inside your query, you can use @
:
b_threshold = 20
c_threshold = 8
df.query('B >= @b_threshold and C <= @c_threshold')
C
A B
2 20 7
3 50 8
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
$services = $this->Service->find('all', array(
'limit' =>4,
'fields' => array('Service.*','ServiceImage.*'),
'joins' => array(
array(
'table' => 'services_images',
'alias' => 'ServiceImage',
'type' => 'INNER',
'conditions' => array(
'ServiceImage.service_id' =>'Service.id'
)
),
),
)
);
It goges to array is null.
Only thing that comes even close is the :contains
pseudo class in CSS3, but that only selects textual content, not tags or elements, so you're out of luck.
A simpler way to select a parent with specific children in jQuery can be written as (with :has()
):
$('#parent:has(#child)');
As you want to exclude both words, you need a conjuction:
^/(?!ignoreme$)(?!ignoreme2$)[a-z0-9]+$
Now both conditions must be true (neither ignoreme nor ignoreme2 is allowed) to have a match.
To find all configurations, you just write this command:
git config --list
In my local i run this command .
Md Masud@DESKTOP-3HTSDV8 MINGW64 ~
$ git config --list
core.symlinks=false
core.autocrlf=true
core.fscache=true
color.diff=auto
color.status=auto
color.branch=auto
color.interactive=true
help.format=html
rebase.autosquash=true
http.sslcainfo=C:/Program Files/Git/mingw64/ssl/certs/ca-bundle.crt
http.sslbackend=openssl
diff.astextplain.textconv=astextplain
filter.lfs.clean=git-lfs clean -- %f
filter.lfs.smudge=git-lfs smudge -- %f
filter.lfs.process=git-lfs filter-process
filter.lfs.required=true
credential.helper=manager
[email protected]
filter.lfs.smudge=git-lfs smudge -- %f
filter.lfs.process=git-lfs filter-process
filter.lfs.required=true
filter.lfs.clean=git-lfs clean -- %f
There are two ways. One is to aggregate:
SELECT array_agg(column_name::TEXT)
FROM information.schema.columns
WHERE table_name = 'aean'
The other is to use an array constructor:
SELECT ARRAY(
SELECT column_name
FROM information.schema.columns
WHERE table_name = 'aean')
I'm presuming this is for plpgsql. In that case you can assign it like this:
colnames := ARRAY(
SELECT column_name
FROM information.schema.columns
WHERE table_name='aean'
);
I ran into the same error.
NAME READY STATUS RESTARTS AGE pod/webapp 0/1 CrashLoopBackOff 5 47h
My problem was that I was trying to run two different pods with the same metadata name.
kind: Pod metadata: name: webapp labels: ...
To find all the names of your pods run: kubectl get pods
NAME READY STATUS RESTARTS AGE webapp 1/1 Running 15 47h
then I changed the conflicting pod name and everything worked just fine.
NAME READY STATUS RESTARTS AGE webapp 1/1 Running 17 2d webapp-release-0-5 1/1 Running 0 13m
After a half of the day of investigating why Analyzing Dependencies
takes forever, I found out that I was installing the latest Firebase
pod (7.1.0), which relies on GoogleAppMeasurement
version 7.1.0, and there was another pod, which is an ad mediation framework, which includes Google-Mobile-Ads-SDK
. This SDK was relying on a much lower version of GoogleAppMeasurement
~ 6.0.
I was able to install the pods by commenting out the conflicting pod from the ad mediation.
Something like this:
# Ad network framework
pod 'SomeMediationNetwork/Core'
# pod 'SomeMediationNetwork/GoogleMobileAds' # - the conflicting pod
pod 'SomeMediationNetwork/Facebook'
pod 'SomeMediationNetwork/SmartAdServer'
pod 'SomeMediationNetwork/Mopub'
I had to contact the ad mediation library publisher to fix this issue, most probably by updating to the latest Google-Mobile-Ads-SDK
pod and releasing a new version.
I hope this one helps some other folks who are banging their head
Here is what made the error disappear for me:
Close eclipse, open up a terminal window and run:
$ mvn clean eclipse:clean eclipse:eclipse
Are you using Maven? If so,
To add it: Right-click on the project, Maven → Disable Maven Nature Right-click on the project, Configure → Convert to Maven Project.
And then clean
Edit 1:
If that doesn't resolve the issue try right-clicking on your project and select properties. Select Java Build Path → Library tab. Look for a JVM. If it's not there, click to add Library and add the default JVM. If VM is there, click edit and select the default JVM. Hopefully, that works.
Edit 2:
You can also try going into the folder where you have all your projects and delete the .metadata
for eclipse (be aware that you'll have to re-import all the projects afterwards! Also all the environment settings you've set would also have to be redone). After it was deleted just import the project again, and hopefully, it works.
It depends what kind of UUID you want.
The standard Java UUID
class generates Version 4 (random) UUIDs. (UPDATE - Version 3 (name) UUIDs can also be generated.) It can also handle other variants, though it cannot generate them. (In this case, "handle" means construct UUID
instances from long
, byte[]
or String
representations, and provide some appropriate accessors.)
The Java UUID Generator (JUG) implementation purports to support "all 3 'official' types of UUID as defined by RFC-4122" ... though the RFC actually defines 4 types and mentions a 5th type.
For more information on UUID types and variants, there is a good summary in Wikipedia, and the gory details are in RFC 4122 and the other specifications.
It is more appropriate to approach this problem with the mentality that a form will have a default action tied to one submit button, and then an alternative action bound to a plain button. The difference here is that whichever one goes under the submit will be the one used when a user submits the form by pressing enter, while the other one will only be fired when a user explicitly clicks on the button.
Anyhow, with that in mind, this should do it:
<form id='myform' action='jquery.php' method='GET'>
<input type='submit' id='btn1' value='Normal Submit'>
<input type='button' id='btn2' value='New Window'>
</form>
With this javascript:
var form = document.getElementById('myform');
form.onsubmit = function() {
form.target = '_self';
};
document.getElementById('btn2').onclick = function() {
form.target = '_blank';
form.submit();
}
Approaches that bind code to the submit button's click event will not work on IE.
java.util.Date temp = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSSSSS").parse("2012-07-10 14:58:00.000000");
The mm
is minutes you want MM
CODE
public class Test {
public static void main(String[] args) throws ParseException {
java.util.Date temp = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSSSSS")
.parse("2012-07-10 14:58:00.000000");
System.out.println(temp);
}
}
Prints:
Tue Jul 10 14:58:00 EDT 2012
You do it exactly the same way as you would with an element directive. You will have them in the attrs object, my sample has them two-way binding via the isolate scope but that's not required. If you're using an isolated scope you can access the attributes with scope.$eval(attrs.sample)
or simply scope.sample, but they may not be defined at linking depending on your situation.
app.directive('sample', function () {
return {
restrict: 'A',
scope: {
'sample' : '=',
'another' : '='
},
link: function (scope, element, attrs) {
console.log(attrs);
scope.$watch('sample', function (newVal) {
console.log('sample', newVal);
});
scope.$watch('another', function (newVal) {
console.log('another', newVal);
});
}
};
});
used as:
<input type="text" ng-model="name" placeholder="Enter a name here">
<input type="text" ng-model="something" placeholder="Enter something here">
<div sample="name" another="something"></div>
Like this.
.divContainer input[type="text"] {
width:150px;
}
.divContainer input[type="radio"] {
width:20px;
}
Try Emmet plug-in command Go To Matching Pair:
http://docs.emmet.io/actions/go-to-pair/
Shortcut (Mac): Shift + Control + T
Shortcut (PC): Control + Alt + J
It's called Manage access now.
Go to your private repo, click the Settings tab, and choose Manage access from the menu on the left. You are allowed up to three collaborators with the free plan.
Note: If the account is an individual account you can still add collaborators that can do a variety of tasks, but a collaborator can't (as far as I know) sign the app in Xcode and submit it to the app store. You need an organization account for that kind of collaborator.
Those two parameters (or variants of) are sent, by convention, with all events.
sender
: The object which has raised the evente
an instance of EventArgs
including, in many cases, an object which inherits from EventArgs
. Contains additional information about the event, and sometimes provides ability for code handling the event to alter the event somehow.In the case of the events you mentioned, neither parameter is particularly useful. The is only ever one page raising the events, and the EventArgs
are Empty
as there is no further information about the event.
Looking at the 2 parameters separately, here are some examples where they are useful.
sender
Say you have multiple buttons on a form. These buttons could contain a Tag
describing what clicking them should do. You could handle all the Click
events with the same handler, and depending on the sender
do something different
private void HandleButtonClick(object sender, EventArgs e)
{
Button btn = (Button)sender;
if(btn.Tag == "Hello")
MessageBox.Show("Hello")
else if(btn.Tag == "Goodbye")
Application.Exit();
// etc.
}
Disclaimer : That's a contrived example; don't do that!
e
Some events are cancelable. They send CancelEventArgs
instead of EventArgs
. This object adds a simple boolean property Cancel
on the event args. Code handling this event can cancel the event:
private void HandleCancellableEvent(object sender, CancelEventArgs e)
{
if(/* some condition*/)
{
// Cancel this event
e.Cancel = true;
}
}
cond? statementA: statementB
Equals to:
if (cond)
statementA
else
statementB
For your case, you may just delete all "if". If you totally use if-else instead of ?:. Don't mix them together.
The easiest way would be to create a new (simple) Maven project using the "new project" wizard. You can then migrate your source into the Maven folder structure + the auto generated POM file.
You can/should set your parameter to value to DBNull.Value;
if (variable == "")
{
cmd.Parameters.Add("@Param", SqlDbType.VarChar, 500).Value = DBNull.Value;
}
else
{
cmd.Parameters.Add("@Param", SqlDbType.VarChar, 500).Value = variable;
}
Or you can leave your server side set to null and not pass the param at all.
It should be
document.getElementById("hidden").style.display = "block";
not
document.getElementById["hidden"].style.display = "block";
EDIT due to author edit:
Why are you using a <div>
here? Just add an ID to the table element and add a hidden style to it. E.g. <td id="hidden" style="display:none" class="depot_table_left">
Try C# 7.0
var Dob= DateTime.TryParseExact(s: YourDateString,format: "yyyyMMdd",provider: null,style: 0,out var dt)
? dt : DateTime.Parse("1800-01-01");
Using Spring Data JPA there is a provision to select specific columns from database
---- In DAOImpl ----
@Override
@Transactional
public List<Employee> getAllEmployee() throws Exception {
LOGGER.info("Inside getAllEmployee");
List<Employee> empList = empRepo.getNameAndCityOnly();
return empList;
}
---- In Repo ----
public interface EmployeeRepository extends CrudRepository<Employee,Integer> {
@Query("select e.name, e.city from Employee e" )
List<Employee> getNameAndCityOnly();
}
It worked 100% in my case. Thanks.
This is how it looks like in Kotlin
main.xml
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<item
android:id="@+id/action_settings"
android:orderInCategory="100"
android:title="@string/action_settings"
app:showAsAction="never" />
<item
android:id="@+id/action_logout"
android:orderInCategory="101"
android:title="@string/sign_out"
app:showAsAction="never" />
Then in MainActivity
override fun onCreateOptionsMenu(menu: Menu): Boolean {
// Inflate the menu; this adds items to the action bar if it is present.
menuInflater.inflate(R.menu.main, menu)
return true
}
This is onOptionsItemSelected function
override fun onOptionsItemSelected(item: MenuItem): Boolean {
return when(item.itemId){
R.id.action_settings -> {
true
}
R.id.action_logout -> {
signOut()
true
}
else -> return super.onOptionsItemSelected(item)
}
}
For starting new activity
private fun signOut(){
MySharedPreferences.clearToken()
startSplashScreenActivity()
}
private fun startSplashScreenActivity(){
val intent = Intent(GrepToDo.applicationContext(), SplashScreenActivity::class.java)
startActivity(intent)
finish()
}
An angular solution using $anchorScroll
taken from a now archived blog post by Ben Lesh, which is also reproduced in some detail at this SO answer he contributed (including a rewrite of how to do this within a routing):
app.controller('MainCtrl', function($scope, $location, $anchorScroll) {
var i = 1;
$scope.items = [{ id: 1, name: 'Item 1' }];
$scope.addItem = function (){
i++;
//add the item.
$scope.items.push({ id: i, name: 'Item ' + i});
//now scroll to it.
$location.hash('item' + i);
$anchorScroll();
};
});
And here is the plunker, from the blog that provided this solution: http://plnkr.co/edit/xi2r8wP6ZhQpmJrBj1jM?p=preview
Important to note that the template at that plunker includes this, which sets up the id
that you're using $anchorScroll
to scroll to:
<li ng-repeat="item in items"
id="item{{item.id}}"
>{{item.name}</li>
And if you care for a pure javascript solution, here is one:
Invoke runScroll in your code with parent container id and target scroll id:
function runScroll(parentDivId,targetID) {
var longdiv;
longdiv = document.querySelector("#" + parentDivId);
var div3pos = document.getElementById(targetID).offsetTop;
scrollTo(longdiv, div3pos, 600);
}
function scrollTo(element, to, duration) {
if (duration < 0) return;
var difference = to - element.scrollTop;
var perTick = difference / duration * 10;
setTimeout(function () {
element.scrollTop = element.scrollTop + perTick;
if (element.scrollTop == to) return;
scrollTo(element, to, duration - 10);
}, 10);
}
Reference: Cross browser JavaScript (not jQuery...) scroll to top animation
You need to do it through an ArrayAdapter
which will adapt your ArrayList (or any other collection) to your items in your layout (ListView, Spinner etc.).
This is what the Android developer guide says:
A
ListAdapter
that manages aListView
backed by an array of arbitrary objects. By default this class expects that the provided resource id references a singleTextView
. If you want to use a more complex layout, use the constructors that also takes a field id. That field id should reference aTextView
in the larger layout resource.However the
TextView
is referenced, it will be filled with thetoString()
of each object in the array. You can add lists or arrays of custom objects. Override thetoString()
method of your objects to determine what text will be displayed for the item in the list.To use something other than
TextViews
for the array display, for instanceImageViews
, or to have some of data besidestoString()
results fill the views, overridegetView(int, View, ViewGroup)
to return the type of view you want.
So your code should look like:
public class YourActivity extends Activity {
private ListView lv;
public void onCreate(Bundle saveInstanceState) {
setContentView(R.layout.your_layout);
lv = (ListView) findViewById(R.id.your_list_view_id);
// Instanciating an array list (you don't need to do this,
// you already have yours).
List<String> your_array_list = new ArrayList<String>();
your_array_list.add("foo");
your_array_list.add("bar");
// This is the array adapter, it takes the context of the activity as a
// first parameter, the type of list view as a second parameter and your
// array as a third parameter.
ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(
this,
android.R.layout.simple_list_item_1,
your_array_list );
lv.setAdapter(arrayAdapter);
}
}
Another option is to use numpy.full
, an option available in NumPy 1.8+
a = np.full([height, width, 9], np.nan)
This is pretty flexible and you can fill it with any other number that you want.
Base-64 encoding is a way of taking binary data and turning it into text so that it's more easily transmitted in things like e-mail and HTML form data.
That's funny you asked this, I just did this recently for my work's site and I was thinking I should write a tutorial... Here is how to do it with PHP/Imagick, which uses ImageMagick:
$usmap = '/path/to/blank/us-map.svg';
$im = new Imagick();
$svg = file_get_contents($usmap);
/*loop to color each state as needed, something like*/
$idColorArray = array(
"AL" => "339966"
,"AK" => "0099FF"
...
,"WI" => "FF4B00"
,"WY" => "A3609B"
);
foreach($idColorArray as $state => $color){
//Where $color is a RRGGBB hex value
$svg = preg_replace(
'/id="'.$state.'" style="fill:#([0-9a-f]{6})/'
, 'id="'.$state.'" style="fill:#'.$color
, $svg
);
}
$im->readImageBlob($svg);
/*png settings*/
$im->setImageFormat("png24");
$im->resizeImage(720, 445, imagick::FILTER_LANCZOS, 1); /*Optional, if you need to resize*/
/*jpeg*/
$im->setImageFormat("jpeg");
$im->adaptiveResizeImage(720, 445); /*Optional, if you need to resize*/
$im->writeImage('/path/to/colored/us-map.png');/*(or .jpg)*/
$im->clear();
$im->destroy();
the steps regex color replacement may vary depending on the svg path xml and how you id & color values are stored. If you don't want to store a file on the server, you can output the image as base 64 like
<?php echo '<img src="data:image/jpg;base64,' . base64_encode($im) . '" />';?>
(before you use clear/destroy) but ie has issues with PNG as base64 so you'd probably have to output base64 as jpeg
you can see an example here I did for a former employer's sales territory map:
Start: https://upload.wikimedia.org/wikipedia/commons/1/1a/Blank_US_Map_(states_only).svg
Finish:
Edit
Since writing the above, I've come up with 2 improved techniques:
1) instead of a regex loop to change the fill on state , use CSS to make style rules like
<style type="text/css">
#CA,#FL,HI{
fill:blue;
}
#Al, #NY, #NM{
fill:#cc6699;
}
/*etc..*/
</style>
and then you can do a single text replace to inject your css rules into the svg before proceeding with the imagick jpeg/png creation. If the colors don't change, check to make sure you don't have any inline fill styles in your path tags overriding the css.
2) If you don't have to actually create a jpeg/png image file (and don't need to support outdated browsers), you can manipulate the svg directly with jQuery. You can't access the svg paths when embedding the svg using img or object tags, so you'll have to directly include the svg xml in your webpage html like:
<div>
<?php echo file_get_contents('/path/to/blank/us-map.svg');?>
</div>
then changing the colors is as easy as:
<script type="text/javascript" src="/path/to/jquery.js"></script>
<script type="text/javascript">
$('#CA').css('fill', 'blue');
$('#NY').css('fill', '#ff0000');
</script>
This is the simplest example I found for pagination! http://code.ciphertrick.com/2015/06/01/search-sort-and-pagination-ngrepeat-angularjs/
copy *.csv new.csv
No need for /b as csv isn't a binary file type.
You should now use DbFunctions.TruncateTime
var anyCalls = _db.CallLogs.Where(r => DbFunctions.TruncateTime(r.DateTime) == callDateTime.Date).ToList();
The above were really close. Here's my solution:
Private Sub getDsClone(ByRef inClone As DataSet, ByVal matchStr As String, ByRef outClone As DataSet)
Dim i As Integer
outClone = inClone.Clone
Dim dv As DataView = inClone.Tables(0).DefaultView
dv.RowFilter = matchStr
Dim dt As New DataTable
dt = dv.ToTable
For i = 0 To dv.Count - 1
outClone.Tables(0).ImportRow(dv.Item(i).Row)
Next
End Sub
In addition to some of the other answers provided, if you wanted to look at the differences in table structure with a table that might have the similar but differing structure, you could do this in multiple ways:
First - If using Oracle SQL Developer, you could run a describe on both tables to compare them:
descr TABLE_NAME1
descr TABLE_NAME2
Second - The first solution may not be ideal for larger tables with a lot of columns. If you only want to see the differences in the data between the two tables, then as mentioned by several others, using the SQL Minus operator should do the job.
Third - If you are using Oracle SQL Developer, and you want to compare the table structure of two tables using different schemas you can do the following:
Fourth - If the tables two tables you wish to compare have more columns, are in the same schema, have no need to compare more than two tables and are unappealing to compare visually using the DESCR command you can use the following to compare the differences in the table structure:
select
a.column_name || ' | ' || b.column_name,
a.data_type || ' | ' || b.data_type,
a.data_length || ' | ' || b.data_length,
a.data_scale || ' | ' || b.data_scale,
a.data_precision || ' | ' || b.data_precision
from
user_tab_columns a,
user_tab_columns b
where
a.table_name = 'TABLE_NAME1'
and b.table_name = 'TABLE_NAME2'
and (
a.data_type <> b.data_type or
a.data_length <> b.data_length or
a.data_scale <> b.data_scale or
a.data_precision <> b.data_precision
)
and a.column_name = b.column_name;
Here is the content of the file MessageBoxManager.cs
#pragma warning disable 0618
using System;
using System.Text;
using System.Runtime.InteropServices;
using System.Security.Permissions;
[assembly: SecurityPermission(SecurityAction.RequestMinimum, UnmanagedCode = true)]
namespace System.Windows.Forms
{
public class MessageBoxManager
{
private delegate IntPtr HookProc(int nCode, IntPtr wParam, IntPtr lParam);
private delegate bool EnumChildProc(IntPtr hWnd, IntPtr lParam);
private const int WH_CALLWNDPROCRET = 12;
private const int WM_DESTROY = 0x0002;
private const int WM_INITDIALOG = 0x0110;
private const int WM_TIMER = 0x0113;
private const int WM_USER = 0x400;
private const int DM_GETDEFID = WM_USER + 0;
private const int MBOK = 1;
private const int MBCancel = 2;
private const int MBAbort = 3;
private const int MBRetry = 4;
private const int MBIgnore = 5;
private const int MBYes = 6;
private const int MBNo = 7;
[DllImport("user32.dll")]
private static extern IntPtr SendMessage(IntPtr hWnd, int Msg, IntPtr wParam, IntPtr lParam);
[DllImport("user32.dll")]
private static extern IntPtr SetWindowsHookEx(int idHook, HookProc lpfn, IntPtr hInstance, int threadId);
[DllImport("user32.dll")]
private static extern int UnhookWindowsHookEx(IntPtr idHook);
[DllImport("user32.dll")]
private static extern IntPtr CallNextHookEx(IntPtr idHook, int nCode, IntPtr wParam, IntPtr lParam);
[DllImport("user32.dll", EntryPoint = "GetWindowTextLengthW", CharSet = CharSet.Unicode)]
private static extern int GetWindowTextLength(IntPtr hWnd);
[DllImport("user32.dll", EntryPoint = "GetWindowTextW", CharSet = CharSet.Unicode)]
private static extern int GetWindowText(IntPtr hWnd, StringBuilder text, int maxLength);
[DllImport("user32.dll")]
private static extern int EndDialog(IntPtr hDlg, IntPtr nResult);
[DllImport("user32.dll")]
private static extern bool EnumChildWindows(IntPtr hWndParent, EnumChildProc lpEnumFunc, IntPtr lParam);
[DllImport("user32.dll", EntryPoint = "GetClassNameW", CharSet = CharSet.Unicode)]
private static extern int GetClassName(IntPtr hWnd, StringBuilder lpClassName, int nMaxCount);
[DllImport("user32.dll")]
private static extern int GetDlgCtrlID(IntPtr hwndCtl);
[DllImport("user32.dll")]
private static extern IntPtr GetDlgItem(IntPtr hDlg, int nIDDlgItem);
[DllImport("user32.dll", EntryPoint = "SetWindowTextW", CharSet = CharSet.Unicode)]
private static extern bool SetWindowText(IntPtr hWnd, string lpString);
[StructLayout(LayoutKind.Sequential)]
public struct CWPRETSTRUCT
{
public IntPtr lResult;
public IntPtr lParam;
public IntPtr wParam;
public uint message;
public IntPtr hwnd;
};
private static HookProc hookProc;
private static EnumChildProc enumProc;
[ThreadStatic]
private static IntPtr hHook;
[ThreadStatic]
private static int nButton;
/// <summary>
/// OK text
/// </summary>
public static string OK = "&OK";
/// <summary>
/// Cancel text
/// </summary>
public static string Cancel = "&Cancel";
/// <summary>
/// Abort text
/// </summary>
public static string Abort = "&Abort";
/// <summary>
/// Retry text
/// </summary>
public static string Retry = "&Retry";
/// <summary>
/// Ignore text
/// </summary>
public static string Ignore = "&Ignore";
/// <summary>
/// Yes text
/// </summary>
public static string Yes = "&Yes";
/// <summary>
/// No text
/// </summary>
public static string No = "&No";
static MessageBoxManager()
{
hookProc = new HookProc(MessageBoxHookProc);
enumProc = new EnumChildProc(MessageBoxEnumProc);
hHook = IntPtr.Zero;
}
/// <summary>
/// Enables MessageBoxManager functionality
/// </summary>
/// <remarks>
/// MessageBoxManager functionality is enabled on current thread only.
/// Each thread that needs MessageBoxManager functionality has to call this method.
/// </remarks>
public static void Register()
{
if (hHook != IntPtr.Zero)
throw new NotSupportedException("One hook per thread allowed.");
hHook = SetWindowsHookEx(WH_CALLWNDPROCRET, hookProc, IntPtr.Zero, AppDomain.GetCurrentThreadId());
}
/// <summary>
/// Disables MessageBoxManager functionality
/// </summary>
/// <remarks>
/// Disables MessageBoxManager functionality on current thread only.
/// </remarks>
public static void Unregister()
{
if (hHook != IntPtr.Zero)
{
UnhookWindowsHookEx(hHook);
hHook = IntPtr.Zero;
}
}
private static IntPtr MessageBoxHookProc(int nCode, IntPtr wParam, IntPtr lParam)
{
if (nCode < 0)
return CallNextHookEx(hHook, nCode, wParam, lParam);
CWPRETSTRUCT msg = (CWPRETSTRUCT)Marshal.PtrToStructure(lParam, typeof(CWPRETSTRUCT));
IntPtr hook = hHook;
if (msg.message == WM_INITDIALOG)
{
int nLength = GetWindowTextLength(msg.hwnd);
StringBuilder className = new StringBuilder(10);
GetClassName(msg.hwnd, className, className.Capacity);
if (className.ToString() == "#32770")
{
nButton = 0;
EnumChildWindows(msg.hwnd, enumProc, IntPtr.Zero);
if (nButton == 1)
{
IntPtr hButton = GetDlgItem(msg.hwnd, MBCancel);
if (hButton != IntPtr.Zero)
SetWindowText(hButton, OK);
}
}
}
return CallNextHookEx(hook, nCode, wParam, lParam);
}
private static bool MessageBoxEnumProc(IntPtr hWnd, IntPtr lParam)
{
StringBuilder className = new StringBuilder(10);
GetClassName(hWnd, className, className.Capacity);
if (className.ToString() == "Button")
{
int ctlId = GetDlgCtrlID(hWnd);
switch (ctlId)
{
case MBOK:
SetWindowText(hWnd, OK);
break;
case MBCancel:
SetWindowText(hWnd, Cancel);
break;
case MBAbort:
SetWindowText(hWnd, Abort);
break;
case MBRetry:
SetWindowText(hWnd, Retry);
break;
case MBIgnore:
SetWindowText(hWnd, Ignore);
break;
case MBYes:
SetWindowText(hWnd, Yes);
break;
case MBNo:
SetWindowText(hWnd, No);
break;
}
nButton++;
}
return true;
}
}
}
Check out Javascript's Array API for details on the exact syntax for Array methods. Modifying your code to use the correct syntax would be:
var array = [];
calendars.forEach(function(item) {
array.push(item.id);
});
console.log(array);
You can also use the map()
method to generate an Array filled with the results of calling the specified function on each element. Something like:
var array = calendars.map(function(item) {
return item.id;
});
console.log(array);
And, since ECMAScript 2015 has been released, you may start seeing examples using let
or const
instead of var
and the =>
syntax for creating functions. The following is equivalent to the previous example (except it may not be supported in older node versions):
let array = calendars.map(item => item.id);
console.log(array);
resoverall
is a sqlalchemy ResultProxy object. You can read more about it in the sqlalchemy docs, the latter explains basic usage of working with Engines and Connections. Important here is that resoverall
is dict like.
Pandas likes dict like objects to create its data structures, see the online docs
Good luck with sqlalchemy and pandas.
In Kotlin Android EditText listener is set using,
val searchTo : EditText = findViewById(R.id.searchTo)
searchTo.addTextChangedListener(object : TextWatcher {
override fun afterTextChanged(s: Editable) {
// you can call or do what you want with your EditText here
// yourEditText...
}
override fun beforeTextChanged(s: CharSequence, start: Int, count: Int, after: Int) {}
override fun onTextChanged(s: CharSequence, start: Int, before: Int, count: Int) {}
})
In my case, Python was unable to find it because I'd put the code inside a module with hyphens, e.g. my-module
. When I changed it to my_module
it worked.
Using the step
attribute will enable it. It not only determines how much it's supposed to cycle, but the allowable numbers, as well. Using step="0.01"
should do the trick but this may depend on how the browser adheres to the standard.
<input type='number' step='0.01' value='5.00'>
_x000D_
You have declared your Class as:
@Table( name = "foobar" )
public class FooBar {
You need to write the Class Name for the search.
from FooBar
Like this?
public static void Test()
{
using (var image = Image.FromFile(@"c:\logo.png"))
using (var newImage = ScaleImage(image, 300, 400))
{
newImage.Save(@"c:\test.png", ImageFormat.Png);
}
}
public static Image ScaleImage(Image image, int maxWidth, int maxHeight)
{
var ratioX = (double)maxWidth / image.Width;
var ratioY = (double)maxHeight / image.Height;
var ratio = Math.Min(ratioX, ratioY);
var newWidth = (int)(image.Width * ratio);
var newHeight = (int)(image.Height * ratio);
var newImage = new Bitmap(newWidth, newHeight);
using (var graphics = Graphics.FromImage(newImage))
graphics.DrawImage(image, 0, 0, newWidth, newHeight);
return newImage;
}
As of Java 11 one can use Pattern#asMatchPredicate
which returns Predicate<String>
.
String string = "stores%store%product";
String regex = "stores.*store.*product.*";
Predicate<String> matchesRegex = Pattern.compile(regex).asMatchPredicate();
boolean match = matchesRegex.test(string); // true
The method enables chaining with other String predicates, which is the main advantage of this method as long as the Predicate
offers and
, or
and negate
methods.
String string = "stores$store$product";
String regex = "stores.*store.*product.*";
Predicate<String> matchesRegex = Pattern.compile(regex).asMatchPredicate();
Predicate<String> hasLength = s -> s.length() > 20;
boolean match = hasLength.and(matchesRegex).test(string); // false
$collection = collect([1, 2, 3, 4, 5, 6, 7, 8, 9]);
$chunk = $collection->forPage(2, 3);
$chunk->all();
use toUpperCase() or toLowerCase() method of String class.
Enable mod_headers in Apache2 to be able to use Header directive :
a2enmod headers
This behavior is related to Zone that is set - Internet/Intranet/etc and corresponding Security Level
You can change this by setting less secure Security Level (not recommended) or by customizing Display Mixed Content property
You can do that by following steps:
Both getSingleResult()
and getOneOrNullResult()
will throw an exception if there is more than one result.
To fix this problem you could add setMaxResults(1)
to your query builder.
$firstSubscriber = $entity->createQueryBuilder()->select('sub')
->from("\Application\Entity\Subscriber", 'sub')
->where('sub.subscribe=:isSubscribe')
->setParameter('isSubscribe', 1)
->setMaxResults(1)
->getQuery()
->getOneOrNullResult();
I sometimes find a variation of this useful.
Example in JavaScript:
class Scaler {
constructor(inMin, inMax, outMin, outMax) {
this.inMin = inMin;
this.inMax = inMax;
this.outMin = outMin;
this.outMax = outMax;
}
scale(value) {
const result = (value - this.inMin) * (this.outMax - this.outMin) / (this.inMax - this.inMin) + this.outMin;
if (result < this.outMin) {
return this.outMin;
} else if (result > this.outMax) {
return this.outMax;
}
return result;
}
}
This example along with a function based version comes from the page https://writingjavascript.com/scaling-values-between-two-ranges
No need to add any plugin, CSS can do this job !!!
The idea is to make the position of all the first cells in each column absolute, and make width fixed. Ex:
max-width: 125px;
min-width: 125px;
position: absolute;
This hides some parts of some columns under the first column, so add an empty second column (add second empty td) with width same as the first column.
I tested and this works in Chrome and Firefox.
If you are using any Databases such as Oracle/Mysql then first check this databases services are start
I would use a List if you need a dynamically sized array:
List<string> ls = new List<string>();
ls.Add("Hello");
Through the Computer management console, navigate through Event Viewer > Windows Logs > System. Every services that change state will be logged here.
You'll see info like: The XXXX service entered the running state or The XXXX service entered the stopped state, etc.
GREP: Global Regular Expression Print/Parser/Processor/Program.
You can use this to search the current directory.
You can specify -R for "recursive", which means the program searches in all subfolders, and their subfolders, and their subfolder's subfolders, etc.
grep -R "your word" .
-n
will print the line number, where it matched in the file.
-i
will search case-insensitive (capital/non-capital letters).
grep -inR "your regex pattern" .
There are 2 ways in which you can get the values:-
I also recommend the SSH SFTP Updater Support plugin. Just solved all my problems too...especially in regards to getting plugins to delete through the admin. Just install it in the usual way, and the next time you're prompted by WordPress for FTP details, there'll be extra fields for you to copy/paste your private SSH key or upload your PEM file.
Only problem I have is in getting it to remember the key (tried both methods). Don't like the idea of having to find and enter it every time I need to delete a plugin. But at least it's a solid fix for now.
If you need add this reference for cordova plugin add next line in your plugin.xml file.
<framework src="com.android.support:support-v4:+" />
Almost 5 years later, I think my answer can reduce a little bit the hard work of many people.
Update an element in the DOM with the HTML from the one from the ajax call can be achieved that way
$('#submitform').click(function() {
$.ajax({
url: "getinfo.asp",
data: {
txtsearch: $('#appendedInputButton').val()
},
type: "GET",
dataType : "html",
success: function (data){
$('#showresults').html($('#showresults',data).html());
// similar to $(data).find('#showresults')
},
});
or with replaceWith()
// codes
success: function (data){
$('#showresults').replaceWith($('#showresults',data));
},
The answer I was searching for was answered here: How to use python argparse with args other than sys.argv?
If main.py
and parse_args()
is written in this way, then the parsing can be done nicely
# main.py
import argparse
def parse_args():
parser = argparse.ArgumentParser(description="")
parser.add_argument('--input', default='my_input.txt')
return parser
def main(args):
print(args.input)
if __name__ == "__main__":
parser = parse_args()
args = parser.parse_args()
main(args)
Then you can call main()
and parse arguments with parser.parse_args(['--input', 'foobar.txt'])
to it in another python script:
# temp.py
from main import main, parse_args
parser = parse_args()
args = parser.parse_args([]) # note the square bracket
# to overwrite default, use parser.parse_args(['--input', 'foobar.txt'])
print(args) # Namespace(input='my_input.txt')
main(args)
You must add a full table inside the td
<table>_x000D_
<tr>_x000D_
<td>_x000D_
<table>_x000D_
<tr>_x000D_
<td>_x000D_
..._x000D_
</td>_x000D_
</tr>_x000D_
</table>_x000D_
</td>_x000D_
</tr>_x000D_
</table>
_x000D_
You are probably manually calling setVisible(true)
on the menu. That can cause some nasty buggy behavior in the menu.
The show(Component, int x, int x)
method handles all of the things you need to happen, (Highlighting things on mouseover and closing the popup when necessary) where using setVisible(true)
just shows the menu without adding any additional behavior.
To make a right click popup menu simply create a JPopupMenu
.
class PopUpDemo extends JPopupMenu {
JMenuItem anItem;
public PopUpDemo() {
anItem = new JMenuItem("Click Me!");
add(anItem);
}
}
Then, all you need to do is add a custom MouseListener
to the components you would like the menu to popup for.
class PopClickListener extends MouseAdapter {
public void mousePressed(MouseEvent e) {
if (e.isPopupTrigger())
doPop(e);
}
public void mouseReleased(MouseEvent e) {
if (e.isPopupTrigger())
doPop(e);
}
private void doPop(MouseEvent e) {
PopUpDemo menu = new PopUpDemo();
menu.show(e.getComponent(), e.getX(), e.getY());
}
}
// Then on your component(s)
component.addMouseListener(new PopClickListener());
Of course, the tutorials have a slightly more in-depth explanation.
Note: If you notice that the popup menu is appearing way off from where the user clicked, try using the e.getXOnScreen()
and e.getYOnScreen()
methods for the x and y coordinates.
Think of the print statement as causing a side-effect, it makes your function write some text out to the user, but it can't be used by another function.
I'll attempt to explain this better with some examples, and a couple definitions from Wikipedia.
Here is the definition of a function from Wikipedia
A function, in mathematics, associates one quantity, the argument of the function, also known as the input, with another quantity, the value of the function, also known as the output..
Think about that for a second. What does it mean when you say the function has a value?
What it means is that you can actually substitute the value of a function with a normal value! (Assuming the two values are the same type of value)
Why would you want that you ask?
What about other functions that may accept the same type of value as an input?
def square(n):
return n * n
def add_one(n):
return n + 1
print square(12)
# square(12) is the same as writing 144
print add_one(square(12))
print add_one(144)
#These both have the same output
There is a fancy mathematical term for functions that only depend on their inputs to produce their outputs: Referential Transparency. Again, a definition from Wikipedia.
Referential transparency and referential opaqueness are properties of parts of computer programs. An expression is said to be referentially transparent if it can be replaced with its value without changing the behavior of a program
It might be a bit hard to grasp what this means if you're just new to programming, but I think you will get it after some experimentation. In general though, you can do things like print in a function, and you can also have a return statement at the end.
Just remember that when you use return you are basically saying "A call to this function is the same as writing the value that gets returned"
Python will actually insert a return value for you if you decline to put in your own, it's called "None", and it's a special type that simply means nothing, or null.
Replace it with a reusable NOOP (no operation) function.
// this function does nothing
function noop() {};
function foo() {
foo = noop; // swap the functions
// do your thing
}
function bar() {
bar = noop; // swap the functions
// do your thing
}
Check your file: settings.gradle
for presence lines with included subprojects (for example:
include chapter1-bookstore
)
ALTER TABLE TABLE_NAME MODIFY COLUMN_NAME VARCHAR(40);
Late to the question - but I am using Oracle SQL Developer and @anonymous's answer was the closest but kept receiving syntax errors until I edited the query to this.
Hope this helps someone
What's wrong with:
Motor=['1','2','2']
For i in Motor:
If i != '2':
Print(i)
Print(motor)
Using anaconda
Use simply:
ListBox2.Items.Clear()
MSDN: ListBox.ObjectCollection.Clear
Removes all items from the collection.
Note that the problem with your approach is that RemoveAt
changes the index of all remaining items.
When you remove an item from the list, the indexes change for subsequent items in the list. All information about the removed item is deleted. You can use this method to remove a specific item from the list by specifying the index of the item to remove from the list. To specify the item to remove instead of the index to the item, use the Remove method. To remove all items from the list, use the Clear method.
If you want to use RemoveAt
anyway, you can go backwards, for example with:
a for
-loop:
For i As Int32 = ListBox2.Items.Count To 0 Step -1
ListBox2.Items.RemoveAt(i)
Next
or a while
While ListBox2.Items.Count > 0
ListBox2.Items.RemoveAt(ListBox2.Items.Count - 1)
End While
old C# code
for (int i = ListBox2.Items.Count - 1; i >= 0; i--)
ListBox2.Items.RemoveAt(i);
while(ListBox2.Items.Count > 0)
ListBox2.Items.RemoveAt(ListBox2.Items.Count - 1);
Be sure to stringify
before sending. I leaned on the libraries too much and thought they would encode properly based on the contentType I was posting, but they do not seem to.
Works:
$.ajax({
url: _saveAllDevicesUrl
, type: 'POST'
, contentType: 'application/json'
, data: JSON.stringify(postData) //stringify is important
, success: _madeSave.bind(this)
});
I prefer this method to using a plugin like $.toJSON, although that does accomplish the same thing.
You also need to include the Log4J JAR file in the classpath.
Note that slf4j-log4j12-1.6.4.jar
is only an adapter to make it possible to use Log4J via the SLF4J API. It does not contain the actual implementation of Log4J.
Check that the file is called GNUMakefile, makefile or Makefile.
If it is called anything else (and you don't want to rename it) then try:
make -f othermakefilename clean
While looking at the same problem, I found an example
<style type="text/css">
#topright {
position: absolute;
right: 0;
top: 0;
display: block;
height: 125px;
width: 125px;
background: url(TRbanner.gif) no-repeat;
text-indent: -999em;
text-decoration: none;
}
</style>
<a id="topright" href="#" title="TopRight">Top Right Link Text</a>
The trick here is to create a small, (I used GIMP) a PNG (or GIF) that has a transparent background, (and then just delete the opposite bottom corner.)
Got a better approach to implement the animating FAB menu without using any library or to write huge xml code for animations. hope this will help in future for someone who needs a simple way to implement this.
Just using animate().translationY()
function, you can animate any view up or down just I did in my below code, check complete code in github. In case you are looking for the same code in kotlin, you can checkout the kotlin code repo Animating FAB Menu.
first define all your FAB at same place so they overlap each other, remember on top the FAB should be that you want to click and to show other. eg:
<android.support.design.widget.FloatingActionButton
android:id="@+id/fab3"
android:layout_width="@dimen/standard_45"
android:layout_height="@dimen/standard_45"
android:layout_gravity="bottom|end"
android:layout_margin="@dimen/standard_21"
app:srcCompat="@android:drawable/ic_btn_speak_now" />
<android.support.design.widget.FloatingActionButton
android:id="@+id/fab2"
android:layout_width="@dimen/standard_45"
android:layout_height="@dimen/standard_45"
android:layout_gravity="bottom|end"
android:layout_margin="@dimen/standard_21"
app:srcCompat="@android:drawable/ic_menu_camera" />
<android.support.design.widget.FloatingActionButton
android:id="@+id/fab1"
android:layout_width="@dimen/standard_45"
android:layout_height="@dimen/standard_45"
android:layout_gravity="bottom|end"
android:layout_margin="@dimen/standard_21"
app:srcCompat="@android:drawable/ic_dialog_map" />
<android.support.design.widget.FloatingActionButton
android:id="@+id/fab"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="bottom|end"
android:layout_margin="@dimen/fab_margin"
app:srcCompat="@android:drawable/ic_dialog_email" />
Now in your java class just define all your FAB and perform the click like shown below:
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab1 = (FloatingActionButton) findViewById(R.id.fab1);
fab2 = (FloatingActionButton) findViewById(R.id.fab2);
fab3 = (FloatingActionButton) findViewById(R.id.fab3);
fab.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if(!isFABOpen){
showFABMenu();
}else{
closeFABMenu();
}
}
});
Use the animation().translationY()
to animate your FAB,I prefer you to use the attribute of this method in DP since only using an int will effect the display compatibility with higher resolution or lower resolution. as shown below:
private void showFABMenu(){
isFABOpen=true;
fab1.animate().translationY(-getResources().getDimension(R.dimen.standard_55));
fab2.animate().translationY(-getResources().getDimension(R.dimen.standard_105));
fab3.animate().translationY(-getResources().getDimension(R.dimen.standard_155));
}
private void closeFABMenu(){
isFABOpen=false;
fab1.animate().translationY(0);
fab2.animate().translationY(0);
fab3.animate().translationY(0);
}
Now define the above mentioned dimension inside res->values->dimens.xml as shown below:
<dimen name="standard_55">55dp</dimen>
<dimen name="standard_105">105dp</dimen>
<dimen name="standard_155">155dp</dimen>
That's all hope this solution will help the people in future, who are searching for simple solution.
EDITED
If you want to add label over the FAB then simply take a horizontal LinearLayout and put the FAB with textview as label, and animate the layouts if find any issue doing this, you can check my sample code in github, I have handelled all backward compatibility issues in that sample code. check my sample code for FABMenu in Github
to close the FAB on Backpress, override onBackPress() as showen below:
@Override
public void onBackPressed() {
if(!isFABOpen){
this.super.onBackPressed();
}else{
closeFABMenu();
}
}
The Screenshot have the title as well with the FAB,because I take it from my sample app present ingithub
I my case the reason for the
ERROR 2013 (HY000): Lost connection to MySQL server during query
error was that parts of my table were corrupted. I was also not able to mysqldump
my table because some rows broke it.
The error was not related to any memory issues etc. like mentioned above.
The nice thing was that MySQL returned me the row number which was the first what failed. It was something like
mysqldump: Error 2013: Lost connection to MySQL server during query when dumping table mytable at row: 12723
The solution was to copy the data into a new table. In my case I lost 10 rows of data because i had to skip these corrupted rows. First I created a "tmp" table with the schema of the old one. SHOW CREATE TABLE
is your friend here. E.g.
SHOW CREATE TABLE mydatabase.mytable;
With the i created the new table. Let's call it mytabletmp. And then copy the rows you are able to copy via e.g.
insert into mysqltabletmp select * from mytable where id < 12723;
insert into mysqltabletmp select * from mytable where id > 12733;
After that drop old table, rename tmp-table to the old table name.
There are also some nice Information from Peter regarding this problem.
Just use simple code
<%
if(condition)
{%>
html code
<% }
else
{
%>
html code
<% } %>
instead of using " + " operator
print( "Alireza" + 1980)
Use comma " , " operator
print( "Alireza" , 1980)
You can use innerHTML
to just concat the extra field string;
document.head.innerHTML = document.head.innerHTML + '<link rel="stylesheet>...'
However, you can't guarantee that the extra things you add to the head will be recognised by the browser after the first load, and it's possible you will get a FOUC (flash of unstyled content) as the extra stylesheets are loaded.
I haven't looked at the API in years, but you could also use document.write
, which is what was designed for this sort of action. However, this would require you to block the page from rendering until your initial AJAX request has completed.
A better method is using strrpos + substr (faster than explode for that) :
$userfile_name = $_FILES['image']['name'];
$userfile_extn = substr($userfile_name, strrpos($userfile_name, '.')+1);
But, to check the type of a file, using mime_content_type is a better way : http://www.php.net/manual/en/function.mime-content-type.php
The shortest version I found is to use the --cat
option of parallel
like below. This version avoids using xargs, only relying on features of parallel
:
cat files.txt | \
parallel -n 500 --lb --pipe --cat rsync --files-from={} user@remote:/dir /dir -avPi
#### Arg explainer
# -n 500 :: split input into chunks of 500 entries
#
# --cat :: create a tmp file referenced by {} containing the 500
# entry content for each process
#
# user@remote:/dir :: the root relative to which entries in files.txt are considered
#
# /dir :: local root relative to which files are copied
Sample content from files.txt
:
/dir/file-1
/dir/subdir/file-2
....
Note that this doesn't use -j 50
for job count, that didn't work on my end here. Instead I've used -n 500
for record count per job, calculated as a reasonable number given the total number of records.
I had this problem today using any of concat, append or merge, and I got around it by adding a helper column sequentially numbered and then doing an outer join
helper=1
for i in df1.index:
df1.loc[i,'helper']=helper
helper=helper+1
for i in df2.index:
df2.loc[i,'helper']=helper
helper=helper+1
df1.merge(df2,on='helper',how='outer')
public static void main(String[] args) {
try {
DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
Document doc = docBuilder.newDocument();
Element rootElement = doc.createElement("CONFIGURATION");
doc.appendChild(rootElement);
Element browser = doc.createElement("BROWSER");
browser.appendChild(doc.createTextNode("chrome"));
rootElement.appendChild(browser);
Element base = doc.createElement("BASE");
base.appendChild(doc.createTextNode("http:fut"));
rootElement.appendChild(base);
Element employee = doc.createElement("EMPLOYEE");
rootElement.appendChild(employee);
Element empName = doc.createElement("EMP_NAME");
empName.appendChild(doc.createTextNode("Anhorn, Irene"));
employee.appendChild(empName);
Element actDate = doc.createElement("ACT_DATE");
actDate.appendChild(doc.createTextNode("20131201"));
employee.appendChild(actDate);
TransformerFactory transformerFactory = TransformerFactory.newInstance();
Transformer transformer = transformerFactory.newTransformer();
DOMSource source = new DOMSource(doc);
StreamResult result = new StreamResult(new File("/Users/myXml/ScoreDetail.xml"));
transformer.transform(source, result);
System.out.println("File saved!");
} catch (ParserConfigurationException pce) {
pce.printStackTrace();
} catch (TransformerException tfe) {
tfe.printStackTrace();}}
The values in you XML is Hard coded.
Just nest another if clause in the else statement. But that doesn't make it look any prettier.
>>> x=5
>>> x if x>0 else ("zero" if x==0 else "invalid value")
5
>>> x = 0
>>> x if x>0 else ("zero" if x==0 else "invalid value")
'zero'
>>> x = -1
>>> x if x>0 else ("zero" if x==0 else "invalid value")
'invalid value'
Why not use a list comprehension?
In Python 2
ran_floats = [random.uniform(low,high) for _ in xrange(size)]
In Python 3, range
works like xrange
(ref)
ran_floats = [random.uniform(low,high) for _ in range(size)]
Follow the steps,
CFile/QFile/ifstream m_file; m_file.Open(path,Other parameter/mood to open file);
For reading file you have to make buffer or string to save data and you can pass that variable in read() method.
Use the keyword and
, not &
because &
is a bit operator.
Be careful with this... just so you know, in Java and C++, the &
operator is ALSO a bit operator. The correct way to do a boolean comparison in those languages is &&
. Similarly |
is a bit operator, and ||
is a boolean operator. In Python and
and or
are used for boolean comparisons.
I would suggest Travis for Open source project. It's just simple to configure and use.
Simple steps to setup:
.travis.yml
file in root of your project. Add Travis as service in your repository settings page.Now every time you commit into your repository Travis will build your project. You can follow simple steps to get started with Travis CI.
Add an EditText on top of your listview in its .xml layout file. And in your activity/fragment..
lv = (ListView) findViewById(R.id.list_view);
inputSearch = (EditText) findViewById(R.id.inputSearch);
// Adding items to listview
adapter = new ArrayAdapter<String>(this, R.layout.list_item, R.id.product_name, products);
lv.setAdapter(adapter);
inputSearch.addTextChangedListener(new TextWatcher() {
@Override
public void onTextChanged(CharSequence cs, int arg1, int arg2, int arg3) {
// When user changed the Text
MainActivity.this.adapter.getFilter().filter(cs);
}
@Override
public void beforeTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) { }
@Override
public void afterTextChanged(Editable arg0) {}
});
The basic here is to add an OnTextChangeListener to your edit text and inside its callback method apply filter to your listview's adapter.
EDIT
To get filter to your custom BaseAdapter you"ll need to implement Filterable interface.
class CustomAdapter extends BaseAdapter implements Filterable {
public View getView(){
...
}
public Integer getCount()
{
...
}
@Override
public Filter getFilter() {
Filter filter = new Filter() {
@SuppressWarnings("unchecked")
@Override
protected void publishResults(CharSequence constraint, FilterResults results) {
arrayListNames = (List<String>) results.values;
notifyDataSetChanged();
}
@Override
protected FilterResults performFiltering(CharSequence constraint) {
FilterResults results = new FilterResults();
ArrayList<String> FilteredArrayNames = new ArrayList<String>();
// perform your search here using the searchConstraint String.
constraint = constraint.toString().toLowerCase();
for (int i = 0; i < mDatabaseOfNames.size(); i++) {
String dataNames = mDatabaseOfNames.get(i);
if (dataNames.toLowerCase().startsWith(constraint.toString())) {
FilteredArrayNames.add(dataNames);
}
}
results.count = FilteredArrayNames.size();
results.values = FilteredArrayNames;
Log.e("VALUES", results.values.toString());
return results;
}
};
return filter;
}
}
Inside performFiltering() you need to do actual comparison of the search query to values in your database. It will pass its result to publishResults() method.
Just run
docker restart $(docker ps -q)
Update
For Docker 1.13.1
use docker restart $(docker ps -a -q)
as in answer lower.
I had a related problem, but Raghuram's answer helped. (I don't have enough reputation yet to vote his answer up). I'm using Maven bundled with NetBeans, and was getting the same "...was cached in the local repository, resolution will not be reattempted until the update interval of nexus has elapsed or updates are forced -> [Help 1]" error.
To fix this I added <updatePolicy>always</updatePolicy>
to my settings file (C:\Program Files\NetBeans 7.0\java\maven\conf\settings.xml)
<profile>
<id>nexus</id>
<!--Enable snapshots for the built in central repo to direct -->
<!--all requests to nexus via the mirror -->
<repositories>
<repository>
<id>central</id>
<url>http://central</url>
<releases><enabled>true</enabled><updatePolicy>always</updatePolicy></releases>
<snapshots><enabled>true</enabled><updatePolicy>always</updatePolicy></snapshots>
</repository>
</repositories>
<pluginRepositories>
<pluginRepository>
<id>central</id>
<url>http://central</url>
<releases><enabled>true</enabled><updatePolicy>always</updatePolicy></releases>
<snapshots><enabled>true</enabled><updatePolicy>always</updatePolicy></snapshots>
</pluginRepository>
</pluginRepositories>
</profile>
Steve Souders has already given a definitive answer but...
I wonder whether there's an issue with both Sam's original test and Josh's repeat of it.
Both tests appear to have been performed on low latency connections where setting up the TCP connection will have a trivial cost.
How this affects the result of the test I'm not sure and I'd want to look at the waterfalls for the tests over a 'normal' latency connection but...
The first file downloaded should get the connection used for the html page, and the second file downloaded will get the new connection. (Flushing the early alters that dynamic, but it's not being done here)
In newer browsers the second TCP connection is opened speculatively so the connection overhead is reduced / goes away, in older browsers this isn't true and the second connection will have the overhead of being opened.
Quite how/if this affects the outcome of the tests I'm not sure.
I solved this error
A connection attempt failed with "ECONNREFUSED - Connection refused by server"
by changing my port to 22 that was successful
You could simply get the character length of the current directory, and remove them from your absolute list
setlocal EnableDelayedExpansion
for /L %%n in (1 1 500) do if "!__cd__:~%%n,1!" neq "" set /a "len=%%n+1"
setlocal DisableDelayedExpansion
for /r . %%g in (*.log) do (
set "absPath=%%g"
setlocal EnableDelayedExpansion
set "relPath=!absPath:~%len%!"
echo(!relPath!
endlocal
)
It's working to uninstall the old files, but you don't have to restart Eclipse. After the uninstall process, install the new software and then restart Eclipse.
It was quite simple and works for me.
Here's what I had to do to setup basic auth on Ubuntu 14.04 (didn't find a guide anywhere else)
/etc/squid3/squid.conf
instead of the super bloated default config file
auth_param basic program /usr/lib/squid3/basic_ncsa_auth /etc/squid3/passwords
auth_param basic realm proxy
acl authenticated proxy_auth REQUIRED
http_access allow authenticated
# Choose the port you want. Below we set it to default 3128.
http_port 3128
Please note the basic_ncsa_auth program instead of the old ncsa_auth
For squid 2.x you need to edit /etc/squid/squid.conf
file and place:
auth_param basic program /usr/lib/squid/digest_pw_auth /etc/squid/passwords
auth_param basic realm proxy
acl authenticated proxy_auth REQUIRED
http_access allow authenticated
sudo htpasswd -c /etc/squid3/passwords username_you_like
and enter a password twice for the chosen username then
sudo service squid3 restart
sudo htpasswd -c /etc/squid/passwords username_you_like
and enter a password twice for the chosen username then
sudo service squid restart
For the many people that asked me: the 2 tools produce different file formats:
htdigest
stores the password in plain text.htpasswd
stores the password hashed (various hashing algos are available)Despite this difference in format basic_ncsa_auth
will still be able to parse a password file generated with htdigest
. Hence you can alternatively use:
sudo htdigest -c /etc/squid3/passwords realm_you_like username_you_like
Beware that this approach is empirical, undocumented and may not be supported by future versions of Squid.
On Ubuntu 14.04 htdigest
and htpasswd
are both available in the [apache2-utils][1]
package.
Similar as above applies, but file paths are different.
Install squid
brew install squid
Start squid service
brew services start squid
Squid config file is stored at /usr/local/etc/squid.conf
.
Comment or remove following line:
http_access allow localnet
Then similar to linux config (but with updated paths) add this:
auth_param basic program /usr/local/Cellar/squid/4.8/libexec/basic_ncsa_auth /usr/local/etc/squid_passwords
auth_param basic realm proxy
acl authenticated proxy_auth REQUIRED
http_access allow authenticated
Note that path to basic_ncsa_auth
may be different since it depends on installed version when using brew
, you can verify this with ls /usr/local/Cellar/squid/
. Also note that you should add the above just bellow the following section:
#
# INSERT YOUR OWN RULE(S) HERE TO ALLOW ACCESS FROM YOUR CLIENTS
#
Now generate yourself a user:password basic auth credential (note: htpasswd
and htdigest
are also both available on MacOS)
htpasswd -c /usr/local/etc/squid_passwords username_you_like
Restart the squid service
brew services restart squid
I doubt that anyone will actually see it but I have a simple solution for those who want to mix several colors in the same line:
export enum Colors {
Black = '\033[30m',
Red = '\x1b[31m',
Green = '\x1b[32m',
Yellow = '\x1b[33m',
Blue = '\033[34m',
Magenta = '\033[35m',
Cyan = '\033[36m',
White = '\033[37m'
}
function color(text: string, color: color: Colors) {
return `${color}${text}\x1b[0m`;
}
console.log(`This is ${color('green text', Colors.Green)} but this is black. This is red ${color('red', Colors.Red)} etc`);
1) The circles are Entities/POJOs/Beans
2) deg is an abbreviation for degree as in graphs (number of edges)
PK=Primary key, FK=Foreign key
Note the contradiction between the degree and the name of the side. Many corresponds to degree=1 while One corresponds to degree >1.
Last revision merged from trunk to branch can be found by running this command inside the working copy directory:
svn log -v --stop-on-copy
i think this is shortest code for finding primes with eratosthenes method
def prime(r):
n = range(2,r)
while len(n)>0:
yield n[0]
n = [x for x in n if x not in range(n[0],r,n[0])]
print(list(prime(r)))
@roens is correct. This affects all Anaconda users, with below error
curl: (77) error setting certificate verify locations:
CAfile: /etc/pki/tls/certs/ca-bundle.crt
CApath: none
The workaround is to use the default system curl and avoid messing with the prepended Anaconda PATH
variable. You can either
Rename the Anaconda curl binary :)
mv /path/to/anaconda/bin/curl /path/to/anaconda/bin/curl_anaconda
OR remove Anaconda curl
conda remove curl
$ which curl
/usr/bin/curl
[0] Anaconda Ubuntu curl Github issue https://github.com/conda/conda-recipes/issues/352
I think you want this:
foreach ($myarray as $key => $value) {
echo "$key = $value\n";
}
I recently (today :D) had to integrate this behavior. In order to not impact the original design fields, including combo, I opted to apply the transformation at the focus of the field:
input[type="text"]:focus, input[type="password"]:focus,
textarea:focus, select:focus {
font-size: 16px;
}
This is the simplest way to do it. Allows for group authorities, as well as user authorities.
-- Postgres syntax
create table users (
user_id serial primary key,
enabled boolean not null default true,
password text not null,
username citext not null unique
);
create index on users (username);
create table groups (
group_id serial primary key,
name citext not null unique
);
create table authorities (
authority_id serial primary key,
authority citext not null unique
);
create table user_authorities (
user_id int references users,
authority_id int references authorities,
primary key (user_id, authority_id)
);
create table group_users (
group_id int references groups,
user_id int referenecs users,
primary key (group_id, user_id)
);
create table group_authorities (
group_id int references groups,
authority_id int references authorities,
primary key (group_id, authority_id)
);
Then in META-INF/applicationContext-security.xml
<beans:bean class="org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder" id="passwordEncoder" />
<authentication-manager>
<authentication-provider>
<jdbc-user-service
data-source-ref="dataSource"
users-by-username-query="select username, password, enabled from users where username=?"
authorities-by-username-query="select users.username, authorities.authority from users join user_authorities using(user_id) join authorities using(authority_id) where users.username=?"
group-authorities-by-username-query="select groups.id, groups.name, authorities.authority from users join group_users using(user_id) join groups using(group_id) join group_authorities using(group_id) join authorities using(authority_id) where users.username=?"
/>
<password-encoder ref="passwordEncoder" />
</authentication-provider>
</authentication-manager>
Using String format will help but you must be care full with the locale. In germany float will be separates with in comma instead an point.
Using String.format("geo:%f,%f",5.1,2.1);
on locale english the result will be "geo:5.1,2.1"
but with locale german you will get "geo:5,1,2,1"
You should use the English locale to prevent this behavior.
String uri = String.format(Locale.ENGLISH, "geo:%f,%f", latitude, longitude);
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(uri));
context.startActivity(intent);
To set an label to the geo point you can extend your geo uri by using:
!!! but be carefull with this the geo-uri is still under develoment http://tools.ietf.org/html/draft-mayrhofer-geo-uri-00
String uri = String.format(Locale.ENGLISH, "geo:%f,%f?z=%d&q=%f,%f (%s)",
latitude, longitude, zoom, latitude, longitude, label);
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(uri));
context.startActivity(intent);
This tool saved me a lot, since I have no Admin permission on my machine and already had nodejs installed. For some reason the configuration on my network does not give me access to other machines just pointing the IP on the browser.
# Using a local.dev vhost
$ browser-sync start --proxy
# Using a local.dev vhost with PORT
$ browser-sync start --proxy local.dev:8001
# Using a localhost address
$ browser-sync start --proxy localhost:8001
# Using a localhost address in a sub-dir
$ browser-sync start --proxy localhost:8080/site1
If you say that it works with accessing directly manageproducts.do?option=1
in the browser then it should work with:
$.get('manageproducts.do', { option: '1' }, function(data) {
...
});
as it would send the same GET request.
I've created tutorial on my page https://madebydenis.com/ajax-load-posts-on-wordpress/ about implementing this on Twenty Sixteen theme, so feel free to check it out :)
I've tested this on Twenty Fifteen and it's working, so it should be working for you.
In index.php (assuming that you want to show the posts on the main page, but this should work even if you put it in a page template) I put:
<div id="ajax-posts" class="row">
<?php
$postsPerPage = 3;
$args = array(
'post_type' => 'post',
'posts_per_page' => $postsPerPage,
'cat' => 8
);
$loop = new WP_Query($args);
while ($loop->have_posts()) : $loop->the_post();
?>
<div class="small-12 large-4 columns">
<h1><?php the_title(); ?></h1>
<p><?php the_content(); ?></p>
</div>
<?php
endwhile;
wp_reset_postdata();
?>
</div>
<div id="more_posts">Load More</div>
This will output 3 posts from category 8 (I had posts in that category, so I used it, you can use whatever you want to). You can even query the category you're in with
$cat_id = get_query_var('cat');
This will give you the category id to use in your query. You could put this in your loader (load more div), and pull with jQuery like
<div id="more_posts" data-category="<?php echo $cat_id; ?>">>Load More</div>
And pull the category with
var cat = $('#more_posts').data('category');
But for now, you can leave this out.
Next in functions.php I added
wp_localize_script( 'twentyfifteen-script', 'ajax_posts', array(
'ajaxurl' => admin_url( 'admin-ajax.php' ),
'noposts' => __('No older posts found', 'twentyfifteen'),
));
Right after the existing wp_localize_script
. This will load WordPress own admin-ajax.php so that we can use it when we call it in our ajax call.
At the end of the functions.php file I added the function that will load your posts:
function more_post_ajax(){
$ppp = (isset($_POST["ppp"])) ? $_POST["ppp"] : 3;
$page = (isset($_POST['pageNumber'])) ? $_POST['pageNumber'] : 0;
header("Content-Type: text/html");
$args = array(
'suppress_filters' => true,
'post_type' => 'post',
'posts_per_page' => $ppp,
'cat' => 8,
'paged' => $page,
);
$loop = new WP_Query($args);
$out = '';
if ($loop -> have_posts()) : while ($loop -> have_posts()) : $loop -> the_post();
$out .= '<div class="small-12 large-4 columns">
<h1>'.get_the_title().'</h1>
<p>'.get_the_content().'</p>
</div>';
endwhile;
endif;
wp_reset_postdata();
die($out);
}
add_action('wp_ajax_nopriv_more_post_ajax', 'more_post_ajax');
add_action('wp_ajax_more_post_ajax', 'more_post_ajax');
Here I've added paged key in the array, so that the loop can keep track on what page you are when you load your posts.
If you've added your category in the loader, you'd add:
$cat = (isset($_POST['cat'])) ? $_POST['cat'] : '';
And instead of 8, you'd put $cat
. This will be in the $_POST
array, and you'll be able to use it in ajax.
Last part is the ajax itself. In functions.js I put inside the $(document).ready();
enviroment
var ppp = 3; // Post per page
var cat = 8;
var pageNumber = 1;
function load_posts(){
pageNumber++;
var str = '&cat=' + cat + '&pageNumber=' + pageNumber + '&ppp=' + ppp + '&action=more_post_ajax';
$.ajax({
type: "POST",
dataType: "html",
url: ajax_posts.ajaxurl,
data: str,
success: function(data){
var $data = $(data);
if($data.length){
$("#ajax-posts").append($data);
$("#more_posts").attr("disabled",false);
} else{
$("#more_posts").attr("disabled",true);
}
},
error : function(jqXHR, textStatus, errorThrown) {
$loader.html(jqXHR + " :: " + textStatus + " :: " + errorThrown);
}
});
return false;
}
$("#more_posts").on("click",function(){ // When btn is pressed.
$("#more_posts").attr("disabled",true); // Disable the button, temp.
load_posts();
});
Saved it, tested it, and it works :)
Images as proof (don't mind the shoddy styling, it was done quickly). Also post content is gibberish xD
UPDATE
For 'infinite load' instead on click event on the button (just make it invisible, with visibility: hidden;
) you can try with
$(window).on('scroll', function () {
if ($(window).scrollTop() + $(window).height() >= $(document).height() - 100) {
load_posts();
}
});
This should run the load_posts()
function when you're 100px from the bottom of the page. In the case of the tutorial on my site you can add a check to see if the posts are loading (to prevent firing of the ajax twice), and you can fire it when the scroll reaches the top of the footer
$(window).on('scroll', function(){
if($('body').scrollTop()+$(window).height() > $('footer').offset().top){
if(!($loader.hasClass('post_loading_loader') || $loader.hasClass('post_no_more_posts'))){
load_posts();
}
}
});
Now the only drawback in these cases is that you could never scroll to the value of $(document).height() - 100
or $('footer').offset().top
for some reason. If that should happen, just increase the number where the scroll goes to.
You can easily check it by putting console.log
s in your code and see in the inspector what they throw out
$(window).on('scroll', function () {
console.log($(window).scrollTop() + $(window).height());
console.log($(document).height() - 100);
if ($(window).scrollTop() + $(window).height() >= $(document).height() - 100) {
load_posts();
}
});
And just adjust accordingly ;)
Hope this helps :) If you have any questions just ask.
For a method that works with both C and C++, you might want to consider using the standard library function strtol().
#include <cstdlib>
#include <iostream>
using namespace std;
int main() {
string s = "abcd";
char * p;
long n = strtol( s.c_str(), & p, 16 );
if ( * p != 0 ) { //my bad edit was here
cout << "not a number" << endl;
}
else {
cout << n << endl;
}
}
I have tried with almost 5+ different android approaches and found this is the best solution provided by google especially for android:
try {
HttpURLConnection urlConnection = (HttpURLConnection)
(new URL("http://clients3.google.com/generate_204")
.openConnection());
urlConnection.setRequestProperty("User-Agent", "Android");
urlConnection.setRequestProperty("Connection", "close");
urlConnection.setConnectTimeout(1500);
urlConnection.connect();
if (urlConnection.getResponseCode() == 204 &&
urlConnection.getContentLength() == 0) {
Log.d("Network Checker", "Successfully connected to internet");
return true;
}
} catch (IOException e) {
Log.e("Network Checker", "Error checking internet connection", e);
}
It's faster
, efficient
and accurate
than any other available solution.
If you want to create a .war file you can deploy to a Tomcat instance using the Manager app, create a folder, put all your files in that folder (including an index.html file) move your terminal window into that folder, and execute the following command:
zip -r <AppName>.war *
I've tested it with Tomcat 8 on the Mac, but it should work anywhere
You are doing two mistakes here.
1. calling getMaxValue(),getMinValue()
methods before array initialization completes.
2.Not storing return value returned by the getMaxValue(),getMinValue()
methods.
So try this code
for (int i = 0 ; i < array.length; i++ )
{
int next = input.nextInt();
// sentineil that will stop loop when 999 is entered
if (next == 999)
break;
array[i] = next;
}
// get biggest number
int maxValue = getMaxValue(array);
System.out.println(maxValue );
// get smallest number
int minValue = getMinValue(array);
System.out.println(minValue);
Just subtract the string address from what strchr returns:
char *string = "qwerty";
char *e;
int index;
e = strchr(string, 'e');
index = (int)(e - string);
Note that the result is zero based, so in above example it will be 2.
this is a select command
FROM
user
WHERE
application_key = 'dsfdsfdjsfdsf'
AND email NOT LIKE '%applozic.com'
AND email NOT LIKE '%gmail.com'
AND email NOT LIKE '%kommunicate.io';
this update command
UPDATE user
SET email = null
WHERE application_key='dsfdsfdjsfdsf' and email not like '%applozic.com'
and email not like '%gmail.com' and email not like '%kommunicate.io';
Perhaps this is over-simplistic...
Create a Windows Form project...
Then: Project Properties -> Application -> Output Type -> Console Application
Then can have Console and Forms running together, works for me
In C++0x you have
for(string str: strarr) { ... }
But till then use ordinary for loop.
I was facing the same problem. For my solution, I added br
enclosed between 2 brackets < > enclosed in double quotation marks, and preceded and followed by the + sign:
+"<br>"+
Try this in your browser and see, it certainly works in my Internet Explorer.
In response to Jonathan's answer above, this only seems to work for certain delimiters. For example:
>>> a='Beautiful, is; better*than\nugly'
>>> import re
>>> re.split('; |, |\*|\n',a)
['Beautiful', 'is', 'better', 'than', 'ugly']
>>> b='1999-05-03 10:37:00'
>>> re.split('- :', b)
['1999-05-03 10:37:00']
By putting the delimiters in square brackets it seems to work more effectively.
>>> re.split('[- :]', b)
['1999', '05', '03', '10', '37', '00']
https://perldoc.perl.org/perlre.html#Quoting-metacharacters and https://perldoc.perl.org/functions/quotemeta.html
In the official documentation, such characters are called metacharacters. Example of quoting:
my $regex = quotemeta($string)
s/$regex/something/
It was particular for me. I am sending a header named 'SESSIONHASH'. No problem for Chrome and Opera, but Firefox also wants this header in the list "Access-Control-Allow-Headers". Otherwise, Firefox will throw the CORS error.
Related issue:
I was having trouble converting struct to JSON, sending it as response from Golang, then, later catch the same in JavaScript via Ajax.
Wasted a lot of time, so posting solution here.
In Go:
// web server
type Foo struct {
Number int `json:"number"`
Title string `json:"title"`
}
foo_marshalled, err := json.Marshal(Foo{Number: 1, Title: "test"})
fmt.Fprint(w, string(foo_marshalled)) // write response to ResponseWriter (w)
In JavaScript:
// web call & receive in "data", thru Ajax/ other
var Foo = JSON.parse(data);
console.log("number: " + Foo.number);
console.log("title: " + Foo.title);
See doco for setText() in TextView http://developer.android.com/reference/android/widget/TextView.html
To style your strings, attach android.text.style.* objects to a SpannableString, or see the Available Resource Types documentation for an example of setting formatted text in the XML resource file.
Have you tried, after calling DataBind on your DropDownList, to do something like ddl.SelectedIndex = 0 ?
I'm reluctant to add yet another answer, but I've had to beg, borrow and steal from the others to get what I want, which is a complete list of all the FK relationships on tables in a given schema, INCLUDING FKs to tables in other schemas. The two crucial recordsets are information_schema.KEY_COLUMN_USAGE and information_schema.referential_constraints. If an attribute you want is missing, just uncomment the KCU., RC. to see what's available
SELECT DISTINCT KCU.TABLE_NAME, KCU.COLUMN_NAME, REFERENCED_TABLE_SCHEMA, KCU.REFERENCED_TABLE_NAME, KCU.REFERENCED_COLUMN_NAME, UPDATE_RULE, DELETE_RULE #, KCU.*, RC.*
FROM information_schema.KEY_COLUMN_USAGE KCU
INNER JOIN information_schema.referential_constraints RC ON KCU.CONSTRAINT_NAME = RC.CONSTRAINT_NAME
WHERE TABLE_SCHEMA = (your schema name)
AND KCU.REFERENCED_TABLE_NAME IS NOT NULL
ORDER BY KCU.TABLE_NAME, KCU.COLUMN_NAME;
You are writing to memory you do not own:
int board[2][50]; //make an array with 3 columns (wrong)
//(actually makes an array with only two 'columns')
...
for (i=0; i<num3+1; i++)
board[2][i] = 'O';
^
Change this line:
int board[2][50]; //array with 2 columns (legal indices [0-1][0-49])
^
To:
int board[3][50]; //array with 3 columns (legal indices [0-2][0-49])
^
When creating an array, the value used to initialize: [3]
indicates array size.
However, when accessing existing array elements, index values are zero based.
For an array created: int board[3][50];
Legal indices are board[0][0]...board[2][49]
EDIT To address bad output comment and initialization comment
add an additional "\n" for formatting output:
Change:
...
for (k=0; k<50;k++) {
printf("%d",board[j][k]);
}
}
...
To:
...
for (k=0; k<50;k++) {
printf("%d",board[j][k]);
}
printf("\n");//at the end of every row, print a new line
}
...
Initialize board variable:
int board[3][50] = {0};//initialize all elements to zero
Use Css Selector for this, or learn more about Css Selector just go here
https://www.w3schools.com/cssref/css_selectors.asp
#main_text > .title {
/* Style goes here */
}
#main_text .title {
/* Style goes here */
}
Try this:
git commit --amend
Then copy and paste the Change-Id: I55862204ef71f69bc88c79fe2259f7cb8365699a
at the end of the file.
Save it and push it again!
This solution depends on Bootstrap 3, as pointed out by @günther-jena
Try <a class="btn text-right">Call to Action</a>
. This way you don't need extra markup or rules to clear out floated elements.
For my Android Studio workout. I found that this happen when I change Compile SDK Version from API23 (Android 6) to be API17 (Android 4.2) manually in Project Structure setting, and trying to change some code in layout files.
I miss-understood that I have to change it manually, even on New Project I have selected the "Minimum SdK" to be 4.2 already.
Solve by just change it back to API23, and it still can run on Android 4.2. ^^
I start versioning at the lowest (non hotfix) segement. I do not limit this segment to 10. Unless you are tracking builds then you just need to decide when you want to apply an increment. If you have a QA phase then that might be where you apply an increment to the lowest segment and then the next segement up when it passes QA and is released. Leave the topmost segment for Major behavior/UI changes.
If you are like me you will make it a hybrid of the methods so as to match the pace of your software's progression.
I think the most accepted pattern a.b.c. or a.b.c.d especially if you have QA/Compliance in the mix. I have had so much flack around date being a regular part of versions that I gave it up for mainstream.
I do not track builds so I like to use the a.b.c pattern unless a hotfix is involved. When I have to apply a hotfix then I apply parameter d as a date with time. I adopted the time parameter as d because there is always the potential of several in a day when things really blow up in production. I only apply the d segment (YYYYMMDDHHNN) when I'm diverging for a production fix.
I personally wouldn't be opposed to a software scheme of va.b revc where c is YYYYMMDDHHMM or YYYYMMDD.
All that said. If you can just snag a tool to configure and run with it will keep you from the headache having to marshall the opinion facet of versioning and you can just say "use the tool"... because everyone in the development process is typically so compliant.
The modulo operator %
in C and C++ is defined for two integers, however, there is an fmod()
function available for usage with doubles.
Ctrl+C sends a SIGINT
signal.
kill -INT <pid>
sends a SIGINT
signal too:
# Terminates the program (like Ctrl+C)
kill -INT 888
# Force kill
kill -9 888
Assuming 888
is your process ID.
Note that kill 888
sends a SIGTERM
signal, which is slightly different, but will also ask for the program to stop. So if you know what you are doing (no handler bound to SIGINT
in the program), a simple kill
is enough.
To get the PID of the last command launched in your script, use $!
:
# Launch script in background
./my_script.sh &
# Get its PID
PID=$!
# Wait for 2 seconds
sleep 2
# Kill it
kill $PID
delete acts like a non real world situation, it just removes the item, but the array length stays the same:
example from node terminal:
> var arr = ["a","b","c","d"];
> delete arr[2]
true
> arr
[ 'a', 'b', , 'd', 'e' ]
Here is a function to remove an item of an array by index, using slice(), it takes the arr as the first arg, and the index of the member you want to delete as the second argument. As you can see, it actually deletes the member of the array, and will reduce the array length by 1
function(arr,arrIndex){
return arr.slice(0,arrIndex).concat(arr.slice(arrIndex + 1));
}
What the function above does is take all the members up to the index, and all the members after the index , and concatenates them together, and returns the result.
Here is an example using the function above as a node module, seeing the terminal will be useful:
> var arr = ["a","b","c","d"]
> arr
[ 'a', 'b', 'c', 'd' ]
> arr.length
4
> var arrayRemoveIndex = require("./lib/array_remove_index");
> var newArray = arrayRemoveIndex(arr,arr.indexOf('c'))
> newArray
[ 'a', 'b', 'd' ] // c ya later
> newArray.length
3
please note that this will not work one array with dupes in it, because indexOf("c") will just get the first occurance, and only splice out and remove the first "c" it finds.
use the builtin: (no need for tkinter)
s = input('->>')
print(s) # what you just typed); now use if's
Try this:
-webkit-column-break-inside: avoid;
page-break-inside: avoid;
break-inside: avoid;
-webkit-column-break-inside: avoid-column;
page-break-inside: avoid-column;
break-inside: avoid-column;
...worked for me, might work for you.
var date = new Date(year, month, day);
or
var date = new Date('01/01/1970');
date string in format '01-01-1970' will not work in FireFox, So better use "/" instead of "-" in date format string.
Here is a good table for printf
specifiers. So it should be %hu
for unsigned short int
.
And link to Wikipedia "C data types" too.
Use Integer
instead.
HashMap<Integer, MyObject> myMap = new HashMap<Integer, MyObject>();
Java will automatically autobox your int
primitive values to Integer
objects.
Read more about autoboxing from Oracle Java documentations.
In order to use jQuery inside Angular only declare the $ as following: declare var $: any;
Here's the query example to check the existence of multiple fields:
{
"query": {
"bool": {
"filter": [
{
"exists": {
"field": "field_1"
}
},
{
"exists": {
"field": "field_2"
}
},
{
"exists": {
"field": "field_n"
}
}
]
}
}
}
Now this was a nice little puzzle - great question!
Here's an alternative to Nicola Bonelli's solution that does not rely on the non-standard typeof
operator.
Unfortunately, it does not work on GCC (MinGW) 3.4.5 or Digital Mars 8.42n, but it does work on all versions of MSVC (including VC6) and on Comeau C++.
The longer comment block has the details on how it works (or is supposed to work). As it says, I'm not sure which behavior is standards compliant - I'd welcome commentary on that.
update - 7 Nov 2008:
It looks like while this code is syntactically correct, the behavior that MSVC and Comeau C++ show does not follow the standard (thanks to Leon Timmermans and litb for pointing me in the right direction). The C++03 standard says the following:
14.6.2 Dependent names [temp.dep]
Paragraph 3
In the definition of a class template or a member of a class template, if a base class of the class template depends on a template-parameter, the base class scope is not examined during unqualified name lookup either at the point of definition of the class template or member or during an instantiation of the class template or member.
So, it looks like that when MSVC or Comeau consider the toString()
member function of T
performing name lookup at the call site in doToString()
when the template is instantiated, that is incorrect (even though it's actually the behavior I was looking for in this case).
The behavior of GCC and Digital Mars looks to be correct - in both cases the non-member toString()
function is bound to the call.
Rats - I thought I might have found a clever solution, instead I uncovered a couple compiler bugs...
#include <iostream>
#include <string>
struct Hello
{
std::string toString() {
return "Hello";
}
};
struct Generic {};
// the following namespace keeps the toString() method out of
// most everything - except the other stuff in this
// compilation unit
namespace {
std::string toString()
{
return "toString not defined";
}
template <typename T>
class optionalToStringImpl : public T
{
public:
std::string doToString() {
// in theory, the name lookup for this call to
// toString() should find the toString() in
// the base class T if one exists, but if one
// doesn't exist in the base class, it'll
// find the free toString() function in
// the private namespace.
//
// This theory works for MSVC (all versions
// from VC6 to VC9) and Comeau C++, but
// does not work with MinGW 3.4.5 or
// Digital Mars 8.42n
//
// I'm honestly not sure what the standard says
// is the correct behavior here - it's sort
// of like ADL (Argument Dependent Lookup -
// also known as Koenig Lookup) but without
// arguments (except the implied "this" pointer)
return toString();
}
};
}
template <typename T>
std::string optionalToString(T & obj)
{
// ugly, hacky cast...
optionalToStringImpl<T>* temp = reinterpret_cast<optionalToStringImpl<T>*>( &obj);
return temp->doToString();
}
int
main(int argc, char *argv[])
{
Hello helloObj;
Generic genericObj;
std::cout << optionalToString( helloObj) << std::endl;
std::cout << optionalToString( genericObj) << std::endl;
return 0;
}
SELECT DATABASEPROPERTYEX('DBName', 'Collation') SQLCollation;
Where DBName is your database name.
A lot of people have given some very technical answers for this and similar questions, but I think it's simpler than that. Sometimes if you're not paying attention a selector that you don't intend to use can be attached to something in the interface. You might be getting this error because the selector's there but you haven't written any code for it.
The easiest way to double-check that this is not the case is to control-click the item so you can see all of the selectors that are associated with it. If there's anything in there that you don't want to be, get rid of it! Hope this helps...
Why not create a viewmodel with a simple string parameter and then pass that to the view? It has the benefit of being extensible (i.e. you can then add any other things you may want to set in your controller) and it's fairly simple.
public class MyViewModel
{
public string YourString { get; set; }
}
In the view
@model MyViewModel
@Html.Label(model => model.YourString)
In the controller
public ActionResult Index()
{
myViewModel = new MyViewModel();
myViewModel.YourString = "However you are setting this."
return View(myViewModel)
}
$dbc
is returning false. Your query has an error in it:
SELECT users.*, profile.* --You do not join with profile anywhere.
FROM users
INNER JOIN contact_info
ON contact_info.user_id = users.user_id
WHERE users.user_id=3");
The fix for this in general has been described by Raveren.
Java String
s are immutable.
In your first example, you are changing the reference to the String
, thus assigning it the value of two other Strings
combined: str + " Morning"
.
On the contrary, a StringBuilder
or StringBuffer
can be modified through its methods.
I had to run my commands in the one and same terminal, not seperately.
nohup sudo Xvfb :10 -ac
export DISPLAY=:10
java -jar vendor/se/selenium-server-standalone/bin/selenium-server-standalone.jar -Dwebdriver.chrome.bin="/usr/bin/google-chrome" -Dwebdriver.chrome.driver="vendor/bin/chromedriver"
Run jupyter kernelspec list
to get the paths of all your kernels.
Then simply uninstall your unwanted-kernel
jupyter kernelspec uninstall unwanted-kernel
Old answer
Delete the folder corresponding to the kernel you want to remove.
The docs has a list of the common paths for kernels to be stored in: http://jupyter-client.readthedocs.io/en/latest/kernels.html#kernelspecs
<!-- Latest compiled and minified CSS -->_x000D_
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">_x000D_
_x000D_
<!-- Optional theme -->_x000D_
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap-theme.min.css">_x000D_
_x000D_
<!-- Latest compiled and minified JavaScript -->_x000D_
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>_x000D_
_x000D_
_x000D_
<style type="text/css">_x000D_
.sign-in-facebook_x000D_
{_x000D_
background-image: url('http://i.stack.imgur.com/e2S63.png');_x000D_
background-position: -9px -7px;_x000D_
background-repeat: no-repeat;_x000D_
background-size: 39px 43px;_x000D_
padding-left: 41px;_x000D_
color: #000;_x000D_
}_x000D_
.sign-in-facebook:hover_x000D_
{_x000D_
background-image: url('http://i.stack.imgur.com/e2S63.png');_x000D_
background-position: -9px -7px;_x000D_
background-repeat: no-repeat;_x000D_
background-size: 39px 43px;_x000D_
padding-left: 41px;_x000D_
color: #000;_x000D_
}_x000D_
</style>_x000D_
<p>My current button got white background<br/>_x000D_
<input type="button" value="Sign In with Facebook" class="sign-in-facebook btn btn-secondary" style="margin-top:2px; margin-bottom:2px;" >_x000D_
</p>_x000D_
<p>I need the current btn-default style like below<br/>_x000D_
<input type="button" class="btn btn-default" value="Sign In with Facebook" />_x000D_
</p>_x000D_
<strong>NOTE:</strong> facebook icon at left side of the button.
_x000D_
Solved this by adding following
RewriteCond %{ENV:REDIRECT_STATUS} 200 [OR]
RewriteCond %{REQUEST_FILENAME} -f [OR]
RewriteCond %{REQUEST_FILENAME} -d
RewriteRule ^ - [L]
Firstly you can run every time with root privileges
sudo npm start
Or you can delete node_modules folder and use npm install
to install again
or you can get permanent solution
echo fs.inotify.max_user_watches=524288 | sudo tee -a /etc/sysctl.conf && sudo sysctl -p
Use the collapse
argument to paste
:
paste(a,collapse=" ")
[1] "aa bb cc"
The correct statement should be :
SELECT
student.firstname,
student.lastname,
exam.name,
exam.date,
grade.grade
FROM grade
INNER JOIN student
ON student.studentId = grade.fk_studentId
INNER JOIN exam
ON exam.examId = grade.fk_examId
ORDER BY exam.date
A table is refered to other on the basis of the foreign key relationship defined. You should refer the ids properly if you wish the data to show as queried. So you should refer the id's to the proper foreign keys in the table rather than just on the id which doesn't define a proper relation
There are two options that I can think of, but without more details, I can't be sure which is the better:
#elementId {
display: block;
}
This will force the element to a 'new line' if it's not on the same line as a floated element.
#elementId {
clear: both;
}
This will force the element to clear the floats, and move to a 'new line.'
In the case of the element being on the same line as another that has position
of fixed
or absolute
nothing will, so far as I know, force a 'new line,' as those elements are removed from the document's normal flow.
Can someone help me with the exact syntax?
It's a three-step process, and it involves modifying the openssl.cnf
file. You might be able to do it with only command line options, but I don't do it that way.
Find your openssl.cnf
file. It is likely located in /usr/lib/ssl/openssl.cnf
:
$ find /usr/lib -name openssl.cnf
/usr/lib/openssl.cnf
/usr/lib/openssh/openssl.cnf
/usr/lib/ssl/openssl.cnf
On my Debian system, /usr/lib/ssl/openssl.cnf
is used by the built-in openssl
program. On recent Debian systems it is located at /etc/ssl/openssl.cnf
You can determine which openssl.cnf
is being used by adding a spurious XXX
to the file and see if openssl
chokes.
First, modify the req
parameters. Add an alternate_names
section to openssl.cnf
with the names you want to use. There are no existing alternate_names
sections, so it does not matter where you add it.
[ alternate_names ]
DNS.1 = example.com
DNS.2 = www.example.com
DNS.3 = mail.example.com
DNS.4 = ftp.example.com
Next, add the following to the existing [ v3_ca ]
section. Search for the exact string [ v3_ca ]
:
subjectAltName = @alternate_names
You might change keyUsage
to the following under [ v3_ca ]
:
keyUsage = digitalSignature, keyEncipherment
digitalSignature
and keyEncipherment
are standard fare for a server certificate. Don't worry about nonRepudiation
. It's a useless bit thought up by computer science guys/gals who wanted to be lawyers. It means nothing in the legal world.
In the end, the IETF (RFC 5280), browsers and CAs run fast and loose, so it probably does not matter what key usage you provide.
Second, modify the signing parameters. Find this line under the CA_default
section:
# Extension copying option: use with caution.
# copy_extensions = copy
And change it to:
# Extension copying option: use with caution.
copy_extensions = copy
This ensures the SANs are copied into the certificate. The other ways to copy the DNS names are broken.
Third, generate your self-signed certificate:
$ openssl genrsa -out private.key 3072
$ openssl req -new -x509 -key private.key -sha256 -out certificate.pem -days 730
You are about to be asked to enter information that will be incorporated
into your certificate request.
What you are about to enter is what is called a Distinguished Name or a DN.
...
Finally, examine the certificate:
$ openssl x509 -in certificate.pem -text -noout
Certificate:
Data:
Version: 3 (0x2)
Serial Number: 9647297427330319047 (0x85e215e5869042c7)
Signature Algorithm: sha256WithRSAEncryption
Issuer: C=US, ST=MD, L=Baltimore, O=Test CA, Limited, CN=Test CA/[email protected]
Validity
Not Before: Feb 1 05:23:05 2014 GMT
Not After : Feb 1 05:23:05 2016 GMT
Subject: C=US, ST=MD, L=Baltimore, O=Test CA, Limited, CN=Test CA/[email protected]
Subject Public Key Info:
Public Key Algorithm: rsaEncryption
Public-Key: (3072 bit)
Modulus:
00:e2:e9:0e:9a:b8:52:d4:91:cf:ed:33:53:8e:35:
...
d6:7d:ed:67:44:c3:65:38:5d:6c:94:e5:98:ab:8c:
72:1c:45:92:2c:88:a9:be:0b:f9
Exponent: 65537 (0x10001)
X509v3 extensions:
X509v3 Subject Key Identifier:
34:66:39:7C:EC:8B:70:80:9E:6F:95:89:DB:B5:B9:B8:D8:F8:AF:A4
X509v3 Authority Key Identifier:
keyid:34:66:39:7C:EC:8B:70:80:9E:6F:95:89:DB:B5:B9:B8:D8:F8:AF:A4
X509v3 Basic Constraints: critical
CA:FALSE
X509v3 Key Usage:
Digital Signature, Non Repudiation, Key Encipherment, Certificate Sign
X509v3 Subject Alternative Name:
DNS:example.com, DNS:www.example.com, DNS:mail.example.com, DNS:ftp.example.com
Signature Algorithm: sha256WithRSAEncryption
3b:28:fc:e3:b5:43:5a:d2:a0:b8:01:9b:fa:26:47:8e:5c:b7:
...
71:21:b9:1f:fa:30:19:8b:be:d2:19:5a:84:6c:81:82:95:ef:
8b:0a:bd:65:03:d1
This can be done for a normal subview
inside a larger UIView
, but it doesn't work automatically for headerViews
. The height of a headerView
is determined by what's returned by tableView:heightForHeaderInSection:
so you have to calculate the height
based on the height
of the UILabel
plus space for the UIButton
and any padding
you need. You need to do something like this:
-(CGFloat)tableView:(UITableView *)tableView
heightForHeaderInSection:(NSInteger)section {
NSString *s = self.headeString[indexPath.section];
CGSize size = [s sizeWithFont:[UIFont systemFontOfSize:17]
constrainedToSize:CGSizeMake(281, CGFLOAT_MAX)
lineBreakMode:NSLineBreakByWordWrapping];
return size.height + 60;
}
Here headerString
is whatever string you want to populate the UILabel
, and the 281 number is the width
of the UILabel
(as setup in Interface Builder
)
In my case, Jay D is right. I have to add this before the call.
$.ajaxSetup({
async: false
});
In my previous code, I have this:
var jsonData= (function() {
var result;
$.ajax({
type:'GET',
url:'data.txt',
dataType:'json',
async:false,
success:function(data){
result = data;
}
});
return result;
})();
alert(JSON.stringify(jsonData));
It works find. Then I change to
var jsonData= (function() {
var result;
$.getJSON('data.txt', {}, function(data){
result = data;
});
return result;
})();
alert(JSON.stringify(jsonData));
The alert is undefined.
If I add those three lines, the alert shows the data again.
$.ajaxSetup({
async: false
});
var jsonData= (function() {
var result;
$.getJSON('data.txt', {}, function(data){
result = data;
});
return result;
})();
alert(JSON.stringify(jsonData));
I have tried to use the above robot there is a need to add a delay :( also you cannot debug or do something else because you lose the focus :(
//open upload window upload.click();
//put path to your image in a clipboard
StringSelection ss = new StringSelection(file.getAbsoluteFile());
Toolkit.getDefaultToolkit().getSystemClipboard().setContents(ss, null);
//imitate mouse events like ENTER, CTRL+C, CTRL+V
Robot robot = new Robot();
robot.delay(250);
robot.keyPress(KeyEvent.VK_ENTER);
robot.keyRelease(KeyEvent.VK_ENTER);
robot.keyPress(KeyEvent.VK_CONTROL);
robot.keyPress(KeyEvent.VK_V);
robot.keyRelease(KeyEvent.VK_V);
robot.keyRelease(KeyEvent.VK_CONTROL);
robot.keyPress(KeyEvent.VK_ENTER);
robot.delay(50);
robot.keyRelease(KeyEvent.VK_ENTER);
jQuery.fn
is defined shorthand for jQuery.prototype
. From the source code:
jQuery.fn = jQuery.prototype = {
// ...
}
That means jQuery.fn.jquery
is an alias for jQuery.prototype.jquery
, which returns the current jQuery version. Again from the source code:
// The current version of jQuery being used
jquery: "@VERSION",
what about changing the position: relative on your #content #text div to position: absolute
#content #text {
position:absolute;
width:950px;
height:215px;
color:red;
}
then you can use the css properties left and top to position within the #content div
try this:
import datetime
from datetime import datetime as dt
today_date = datetime.date.today()
date_time = dt.strptime(date_time_string, '%Y-%m-%d %H:%M')
strp() doesn't exist. I think you mean strptime.
libCURL is a pretty good option for you. Depending on what you need to do, the tutorial should tell you what you want, specifically for the easy handle. But, basically, you could do this just to see the source of a page:
CURL* c;
c = curl_easy_init();
curl_easy_setopt( c, CURL_URL, "www.google.com" );
curl_easy_perform( c );
curl_easy_cleanup( c );
I believe this will cause the result to be printed to stdout. If you want to handle it instead -- which, I assume, you do -- you need to set the CURL_WRITEFUNCTION. All of that is covered in the curl tutorial linked above.
From Dianne Hackborn:
Things That Cannot Change:
The most obvious and visible of these is the “manifest package name,” the unique name you give to your application in its AndroidManifest.xml. The name uses a Java-language-style naming convention, with Internet domain ownership helping to avoid name collisions. For example, since Google owns the domain “google.com”, the manifest package names of all of our applications should start with “com.google.” It’s important for developers to follow this convention in order to avoid conflicts with other developers.
Once you publish your application under its manifest package name, this is the unique identity of the application forever more. Switching to a different name results in an entirely new application, one that can’t be installed as an update to the existing application.
More on things you cannot change here
Regarding your question on the URL from Google Play, the package defined there is linked to the app's fully qualified package you have in your AndroidManifest.xml file. More on Google Play's link formats here.
Per the MSDN documentation for sys.database_permissions, this query lists all permissions explicitly granted or denied to principals in the database you're connected to:
SELECT DISTINCT pr.principal_id, pr.name, pr.type_desc,
pr.authentication_type_desc, pe.state_desc, pe.permission_name
FROM sys.database_principals AS pr
JOIN sys.database_permissions AS pe
ON pe.grantee_principal_id = pr.principal_id;
Per Managing Databases and Logins in Azure SQL Database, the loginmanager and dbmanager roles are the two server-level security roles available in Azure SQL Database. The loginmanager role has permission to create logins, and the dbmanager role has permission to create databases. You can view which users belong to these roles by using the query you have above against the master database. You can also determine the role memberships of users on each of your user databases by using the same query (minus the filter predicate) while connected to them.
You can't initialize arrays like this:
int cipher[Array_size][Array_size]=0;
The syntax for 2D arrays is:
int cipher[Array_size][Array_size]={{0}};
Note the curly braces on the right hand side of the initialization statement.
for 1D arrays:
int tomultiply[Array_size]={0};
There are a lot many good answers out there, i just wanted to add a scenario where the usage of these expectations might be helpful. Using element.all(xxx)
, if i need to check if all elements are displayed at a single run, i can perform -
expect(element.all(xxx).isDisplayed()).toBeTruthy(); //Expectation passes
expect(element.all(xxx).isDisplayed()).toBe(true); //Expectation fails
expect(element.all(xxx).isDisplayed()).toBeTrue(); //Expectation fails
Reason being .all()
returns an array of values and so all kinds of expectations(getText
, isPresent
, etc...) can be performed with toBeTruthy()
when .all()
comes into picture. Hope this helps.
The code below gives the HEX and RGB value of the range whether formatted using conditional formatting or otherwise. If the range is not formatted using Conditional Formatting and you intend to use iColor function in the Excel as UDF. It won't work. Read the below excerpt from MSDN.
Note that the DisplayFormat property does not work in user defined functions. For example, in a worksheet function that returns the interior color of a cell, if you use a line similar to:
Range.DisplayFormat.Interior.ColorIndex
then the worksheet function executes to return a #VALUE! error. If you are not finding color of the conditionally formatted range, then I encourage you to rather use
Range.Interior.ColorIndex
as then the function can also be used as UDF in Excel. Such as iColor(B1,"HEX")
Public Function iColor(rng As Range, Optional formatType As String) As Variant
'formatType: Hex for #RRGGBB, RGB for (R, G, B) and IDX for VBA Color Index
Dim colorVal As Variant
colorVal = rng.DisplayFormat.Interior.Color
Select Case UCase(formatType)
Case "HEX"
iColor = "#" & Format(Hex(colorVal Mod 256),"00") & _
Format(Hex((colorVal \ 256) Mod 256),"00") & _
Format(Hex((colorVal \ 65536)),"00")
Case "RGB"
iColor = Format((colorVal Mod 256),"00") & ", " & _
Format(((colorVal \ 256) Mod 256),"00") & ", " & _
Format((colorVal \ 65536),"00")
Case "IDX"
iColor = rng.Interior.ColorIndex
Case Else
iColor = colorVal
End Select
End Function
'Example use of the iColor function
Sub Get_Color_Format()
Dim rng As Range
For Each rng In Selection.Cells
rng.Offset(0, 1).Value = iColor(rng, "HEX")
rng.Offset(0, 2).Value = iColor(rng, "RGB")
Next
End Sub
Modify your constructor to the following so that it calls the base class constructor properly:
public class MyExceptionClass : Exception
{
public MyExceptionClass(string message, string extrainfo) : base(message)
{
//other stuff here
}
}
Note that a constructor is not something that you can call anytime within a method. That's the reason you're getting errors in your call in the constructor body.
Couldn't your query just be written as:
SELECT u1.name as UserName from Message m1, User u1
WHERE u1.uid = m1.UserFromID GROUP BY u1.name HAVING count(m1.UserFromId)>3
That should also help with the known speed issues with subqueries in MySQL
This may be helpful whenever you need a very very random token
<?php
echo mb_strtoupper(strval(bin2hex(openssl_random_pseudo_bytes(16))));
?>
I am using Bootstrap CSS, JS and Fonts in my application. I created a folder called asset
in root directory of the app and place all these folder inside it. Then in server file added following line:
app.use("/asset",express.static("asset"));
This line enables me to load the files that are in the asset
directory from the /asset
path prefix like: http://localhost:3000/asset/css/bootstrap.min.css
.
Now in the views I can simply include CSS and JS like below:
<link href="/asset/css/bootstrap.min.css" rel="stylesheet">
As of PHP 7, you can use the Unicode codepoint escape syntax to do this.
echo "\u{00ed}";
outputs í
.
The solution is given in the error itself, Goto My computer(Right click)-->properties-->Advanced system settings-->Environment variables-->Create new variable.
Give the following details to it:
Variable name : JAVA_HOME.
Variable value : (your path to java jdk installation folder).
To find the path for java installation, go to program files in your window installation drive (normally C drive). Find folder named JAVA, in that navigate to JDK folder.
Copy the link address from the top, and paste it in the Variable value .
Now Press Ok and once environment variable gets created restart the android studio.
Hope it helps.
I am not saying that you have to abandon PHP, but you need different technologies here.
Let's start off simple (without Akamai :-)) and think about the implications here. Video, chat, etc. - it's all client-side in the beginning. The user has a webcam, you want to grab the signal somehow and send it to the server. There is no PHP so far.
I know that Flash supports this though (check this tutorial on webcams and flash) so you could use Flash to transport the content to the server. I think if you'll stay with Flash, then Flex (flex and webcam tutorial) is probably a good idea to look into.
So those are just the basics, maybe it gives you an idea of where you need to research because obviously this won't give you a full video chat inside your app yet. For starters, you will need some sort of way to record the streams and re-publish them so others see other people from the chat, etc..
I'm also not sure how much traffic and bandwidth this is gonna consume though and generally, you will need way more than a Stackoverflow question to solve this issue. Best would be to do a full spec of your app and then hire some people to help you build it.
HTH!
Function imageMorph
will create a new img element therefore the id is removed.
Changed to
$("#wrapper > img")
You should use live() function for click event if you want you rocket lanch again.
Updated demo: http://jsfiddle.net/ynhat/QQRsW/4/
If you happen to be running in Node only, you could use the fs module to read in the multi-line string from a file:
var diagram;
var fs = require('fs');
fs.readFile( __dirname + '/diagram.txt', function (err, data) {
if (err) {
throw err;
}
diagram = data.toString();
});
String actual = list.stream().reduce((t, u) -> t + "," + u).get();
1- open powershell and navigate to your application folder 2- enter your virtualenv folder ex : cd .\venv\Scripts\ 3- active virtualenv by type .\activate
Using just awk you could do (I also shortened some of your piping):
strings -a libAddressDoctor5.so | awk '/EngineVersion/ { if(NR==2) { gsub("\"",""); print $2 } }'
I can't verify it for you because I don't know your exact input, but the following works:
echo "Blah EngineVersion=\"123\"" | awk '/EngineVersion/ { gsub("\"",""); print $2 }'
See also this question on removing single quotes.
For the purpose of encoding javascript has given three inbuilt functions -
escape()
- does not encode @*/+
This method is deprecated after the ECMA 3 so it should be avoided.
encodeURI()
- does not encode ~!@#$&*()=:/,;?+'
It assumes that the URI is a complete URI, so does not encode reserved characters that have special meaning in the URI.
This method is used when the intent is to convert the complete URL instead of some special segment of URL.
Example - encodeURI('http://stackoverflow.com');
will give - http://stackoverflow.com
encodeURIComponent()
- does not encode - _ . ! ~ * ' ( )
This function encodes a Uniform Resource Identifier (URI) component by replacing each instance of certain characters by one, two, three, or four escape sequences representing the UTF-8 encoding of the character. This method should be used to convert a component of URL. For instance some user input needs to be appended
Example - encodeURIComponent('http://stackoverflow.com');
will give - http%3A%2F%2Fstackoverflow.com
All this encoding is performed in UTF 8 i.e the characters will be converted in UTF-8 format.
encodeURIComponent differ from encodeURI in that it encode reserved characters and Number sign # of encodeURI