You can do this using with jQuery UI dialog, you can download JQuery ui from here Download JQueryUI
Include these scripts first inside <head>
tag
<link href="css/smoothness/jquery-ui-1.9.0.custom.css" rel="stylesheet">
<script language="javascript" type="text/javascript" src="jquery-1.8.2.js"></script>
<script src="js/jquery-ui-1.9.0.custom.js"></script>
JQuery code
<script language="javascript" type="text/javascript">
$(document).ready(function() {
$('#trigger').click(function(){
$("#dialog").dialog();
});
});
</script>
HTML code within <body>
tag. Use an iframe to load the pdf file inside
<a href="#" id="trigger">this link</a>
<div id="dialog" style="display:none">
<div>
<iframe src="yourpdffile.pdf"></iframe>
</div>
</div>
Try this once and make sure you are not getting any error in project Structure saying that "ComGoogleAndroidGmsPlay not added"
Open File > Project Structure
and check for below all. If error is shown click on Red bulb marked and click on "Add to dependency".
This is a bug in Android Studio and fixed for the next release(0.4.3)
Dick.Guertin's answer [1] suggested that one could escape the spaces in a filename is a valuable alternative to other solutions suggested here (such as using a null character as a separator rather than whitespace). But it could be simpler - you don't really need a unique character. You can just have sed add the escaped spaces directly:
ls | grep ' ' | sed 's| |\\ |g' | xargs ...
Furthermore, the grep is only necessary if you only want files with spaces in the names. More generically (e.g., when processing a batch of files some of which have spaces, some not), just skip the grep:
ls | sed 's| |\\ |g' | xargs ...
Then, of course, the filename may have other whitespace than blanks (e.g., a tab):
ls | sed -r 's|[[:blank:]]|\\\1|g' | xargs ...
That assumes you have a sed that supports -r (extended regex) such as GNU sed or recent versions of bsd sed (e.g., FreeBSD which originally spelled the option "-E" before FreeBSD 8 and supports both -r & -E for compatibility through FreeBSD 11 at least). Otherwise you can use a basic regex character class bracket expression and manually enter the space and tab characters in the []
delimiters.
[1] This is perhaps more appropriate as a comment or an edit to that answer, but at the moment I do not have enough reputation to comment and can only suggest edits. Since the latter forms above (without the grep) alters the behavior of Dick.Guertin's original answer, a direct edit is perhaps not appropriate anyway.
If you even did not get scroll after doing what is written above .....
Set the android:layout_height="250dp"
or you can say xdp
where x
can be any numerical value.
If you want to use Unix shell commands on Windows, you can use Windows Powershell, which includes both Windows and Unix commands as aliases. You can find more info on it in the documentation.
PowerShell supports aliases to refer to commands by alternate names. Aliasing allows users with experience in other shells to use common command names that they already know for similar operations in PowerShell.
The PowerShell equivalents may not produce identical results. However, the results are close enough that users can do work without knowing the PowerShell command name.
As Tariq Khan suggested, I did the same thing and it worked out..
FIX UBUNTU 14.10 UNICORN APT-GET UPDATE
Backup the repo first
$ sudo cp /etc/apt/sources.list /etc/apt/sources.list.backup
$ sudo vi /etc/apt/sources.list
rename us.archive or archive in http://us.archive.ubuntu.com/ubuntu/ as http://old-release.ubuntu.com/ubuntu/
rename http://security.ubuntu.com/ubuntu/dists/saucy-security/universe/binary-i386/Packages as http://old-releases.ubuntu.com/ubuntu/dists/saucy-security/universe/binary-i386/Packages
$ sudo apt-get update
<input type="text" placeholder="specify">
This adds "specify" as tool-tip text inside the input box.
It's called String#start_with?
, not String#startswith
: In Ruby, the names of boolean-ish methods end with ?
and the words in method names are separated with an _
. Not sure where the s
went, personally, I'd prefer String#starts_with?
over the actual String#start_with?
In your User
model, add the following line in the User
class:
public $timestamps = true;
Now, whenever you save or update a user, Laravel will automatically update the created_at
and updated_at
fields.
Update:
If you want to set the created at manually you should use the date format Y-m-d H:i:s
. The problem is that the format you have used is not the same as Laravel uses for the created_at
field.
Update: Nov 2018 Laravel 5.6
"message": "Access level to App\\Note::$timestamps must be public",
Make sure you have the proper access level as well. Laravel 5.6 is public
.
I know ten years on this should be settled but the first two answers did not work for me so I kept digging. On a Redhat (remote server) - Windows 10 (local machine), if you cannot select the whole thing with a mouse, you are stuck because the usual copies do not work between the remote and the local machine clipboards.
So, to copy on the remote Linux and to paste on the local Windows, specify the primary buffer with the * and do a nice double yank
Use gg" * yy.
Here is the documentation of <select>
. You are using 2 attributes:
multiple
This Boolean attribute indicates that multiple options can be selected in the list. If it is not specified, then only one option can be selected at a time. When multiple is specified, most browsers will show a scrolling list box instead of a single line dropdown.
size
If the control is presented as a scrolling list box (e.g. when multiple is specified), this attribute represents the number of rows in the list that should be visible at one time. Browsers are not required to present a select element as a scrolled list box. The default value is 0.
As described in the docs. <select size="1" multiple>
will render a List box only 1 line visible and a scrollbar. So you are loosing the dropdown/arrow with the multiple
attribute.
Based on my own experiences and internet search, I find these places work:
/etc/paths.d
~/.bash_profile
Note that you should open a new terminal window to see the changes.
You may also refer to this this question
If you're using CakePHP 1.3, you can put this in your views to output the SQL:
<?php echo $this->element('sql_dump'); ?>
So you could create a view called 'sql', containing only the line above, and then call this in your controller whenever you want to see it:
$this->render('sql');
(Also remember to set your debug level to at least 2 in app/config/core.php
)
This code has helped me to dock some executable in windows form. like NotePad, Excel, word, Acrobat reader n many more...
But it wont work for some applications. As sometimes when you start process of some application.... wait for idle time... and the try to get its mainWindowHandle.... till the time the main window handle becomes null.....
so I have done one trick to solve this
If you get main window handle as null... then search all the runnning processes on sytem and find you process ... then get the main hadle of the process and the set panel as its parent.
ProcessStartInfo info = new ProcessStartInfo();
info.FileName = "xxxxxxxxxxxx.exe";
info.Arguments = "yyyyyyyyyy";
info.UseShellExecute = true;
info.CreateNoWindow = true;
info.WindowStyle = ProcessWindowStyle.Maximized;
info.RedirectStandardInput = false;
info.RedirectStandardOutput = false;
info.RedirectStandardError = false;
System.Diagnostics.Process p = System.Diagnostics.Process.Start(info);
p.WaitForInputIdle();
Thread.Sleep(3000);
Process[] p1 ;
if(p.MainWindowHandle == null)
{
List<String> arrString = new List<String>();
foreach (Process p1 in Process.GetProcesses())
{
// Console.WriteLine(p1.MainWindowHandle);
arrString.Add(Convert.ToString(p1.ProcessName));
}
p1 = Process.GetProcessesByName("xxxxxxxxxxxx");
//p.WaitForInputIdle();
Thread.Sleep(5000);
SetParent(p1[0].MainWindowHandle, this.panel2.Handle);
}
else
{
SetParent(p.MainWindowHandle, this.panel2.Handle);
}
$(OBJDIR):
mkdir $@
Which also works for multiple directories, e.g..
OBJDIRS := $(sort $(dir $(OBJECTS)))
$(OBJDIRS):
mkdir $@
Adding $(OBJDIR)
as the first target works well.
ICMP means Internet Control Message Protocol and is always coupled with the IP protocol (There's 2 ICMP variants one for IPv4 and one for IPv6.)
echo request and echo response are the two operation codes of ICMP used to implement ping
.
Besides the original ping program, ping might simply mean the action of checking if a remote node is responding, this might be done on several layers in a protocol stack - e.g. ARP ping for testing hosts on a local network. The term ping might be used on higher protocol layers and APIs as well, e.g. the act of checking if a database is up, done at the database layer protocol.
ICMP sits on top of IP. What you have below depends on the network you're on, and are not in themselves relevant to the operation of ping.
/** Count max number of nonempty cells in sheet rows */
private int getColumnsCount(XSSFSheet xssfSheet) {
int result = 0;
Iterator<Row> rowIterator = xssfSheet.iterator();
while (rowIterator.hasNext()) {
Row row = rowIterator.next();
List<Cell> cells = new ArrayList<>();
Iterator<Cell> cellIterator = row.cellIterator();
while (cellIterator.hasNext()) {
cells.add(cellIterator.next());
}
for (int i = cells.size(); i >= 0; i--) {
Cell cell = cells.get(i-1);
if (cell.toString().trim().isEmpty()) {
cells.remove(i-1);
} else {
result = cells.size() > result ? cells.size() : result;
break;
}
}
}
return result;
}
its super easy.
You'll need each machine to have it's own copy of ElasticSearch (simply copy the one you have now) -- the reason is that each machine / node whatever is going to keep it's own files that are sharded accross the cluster.
The only thing you really need to do is edit the config file to include the name of the cluster.
If all machines have the same cluster name elasticsearch will do the rest automatically (as long as the machines are all on the same network)
Read here to get you started: https://www.elastic.co/guide/en/elasticsearch/guide/current/deploy.html
When you create indexes (where the data goes) you define at that time how many replicas you want (they'll be distributed around the cluster)
Use Apache CollectionUtils
:
CollectionUtils.find(myList, new Predicate() {
public boolean evaluate(Object o) {
return name.equals(((MyClass) o).getName());
}
}
When you have own struct
, you could have own convert-to-string function.
package main
import (
"fmt"
)
type Color struct {
Red int `json:"red"`
Green int `json:"green"`
Blue int `json:"blue"`
}
func (c Color) String() string {
return fmt.Sprintf("[%d, %d, %d]", c.Red, c.Green, c.Blue)
}
func main() {
c := Color{Red: 123, Green: 11, Blue: 34}
fmt.Println(c) //[123, 11, 34]
}
Only call time pass-by-reference is removed. So change:
call_user_func($func, &$this, &$client ...
To this:
call_user_func($func, $this, $client ...
&$this
should never be needed after PHP4 anyway period.
If you absolutely need $client to be passed by reference, update the function ($func) signature instead (function func(&$client) {
)
http uses port 80, and understandably, your internet browser will automatically use that port when you type in an address - unless you specify another port. Now, when running a web server on your computer, you need to access that server somehow - and since port 80 is already busy, you need to use a different port to successfully connect to it. Although any open port is fair game, usually such a server is configured to use port 8080, hence when accessing your server you type in:
http:// (protocol) localhost (your computer) :8080 (port 8080) / (path pointing to the root of the public folder of your server)
$('#elm').removeAttr('class');
no longer class attr wil be present in "elm".
enum Constants
{
Abc = 1,
Def = 2,
Ghi = 3
}
...
int i = (int)Enum.Parse(typeof(Constants), "Def");
We don't need to access the canvas context.
Implementing hednek in pure JS you would get canvas.setAttribute('style', 'background-color:#00F8')
. But my preferred method requires converting the kabab-case to camelCase.
canvas.style.backgroundColor = '#00F8'
I think your issue is that Range("H18")
doesn't contain a formula. Also, you could make your code more efficient by eliminating x
. Instead, change your code to
Range("H18").GoalSeek Goal:=Range("H32").Value, ChangingCell:=Range("G18")
Another simple way using JOIN
and INSTR
Sub Sample()
Dim Mainfram(4) As String, strg As String
Dim cel As Range
Dim Delim As String
Delim = "#"
Mainfram(0) = "apple"
Mainfram(1) = "pear"
Mainfram(2) = "orange"
Mainfram(3) = "fruit"
strg = Join(Mainfram, Delim)
strg = Delim & strg
For Each cel In Selection
If InStr(1, strg, Delim & cel.Value & Delim, vbTextCompare) Then _
Rows(cel.Row).Style = "Accent1"
Next cel
End Sub
One option using your data (for future reference, use set.seed()
to make examples using sample
reproducible):
DF <- data.frame(V1=c(2,8,1),V2=c(7,3,5),V3=c(9,6,4))
colnames(DF)[apply(DF,1,which.max)]
[1] "V3" "V1" "V2"
A faster solution than using apply
might be max.col
:
colnames(DF)[max.col(DF,ties.method="first")]
#[1] "V3" "V1" "V2"
...where ties.method
can be any of "random"
"first"
or "last"
This of course causes issues if you happen to have two columns which are equal to the maximum. I'm not sure what you want to do in that instance as you will have more than one result for some rows. E.g.:
DF <- data.frame(V1=c(2,8,1),V2=c(7,3,5),V3=c(7,6,4))
apply(DF,1,function(x) which(x==max(x)))
[[1]]
V2 V3
2 3
[[2]]
V1
1
[[3]]
V2
2
In Bash this is easy. Just tie them together with &&
:
command1 && command2 && command3
You can also use the nested if construct:
if command1
then
if command2
then
do_something
else
exit
fi
else
exit
fi
Simple Answer: NO
Well, at least a naming convention as such encouraged by Oracle or community, no, however, basically you have to be aware of following the rules and limits for identifiers, such as indicated in MySQL documentation: https://dev.mysql.com/doc/refman/8.0/en/identifiers.html
About the naming convention you follow, I think it is ok, just the number 5 is a little bit unnecesary, I think most visual tools for managing databases offer a option for sorting column names (I use DBeaver, and it have it), so if the purpouse is having a nice visual presentation of your table you can use this option I mention.
By personal experience, I would recommed this:
lower_case_table_names
is not correctly configured and your server start throwing errors just by simply unrecognizing your camelCase or PascalCase standard (case sensitivity problem).And what about the "Plural vs Singular" naming? Well, this is most a situation of personal preferences. In my case I try to use plural names for tables because I think a table as a collection of elements or a package containig elements, so a plural name make sense for me; and singular names for columns because I see columns as attributes that describe singularly to those table elements.
Try this code:
activity_main.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="fill_parent" android:layout_height="100dip" tools:context=".MainActivity" > <HorizontalScrollView android:id="@+id/hsv" android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_alignParentTop="true" android:fillViewport="true" android:measureAllChildren="false" android:scrollbars="none" > <LinearLayout android:id="@+id/innerLay" android:layout_width="wrap_content" android:layout_height="wrap_content" android:gravity="center_vertical" android:orientation="horizontal" > <LinearLayout android:id="@+id/asthma_action_plan" android:layout_width="wrap_content" android:layout_height="wrap_content" android:gravity="center" android:orientation="vertical" > <RelativeLayout android:layout_width="fill_parent" android:layout_height="match_parent" > <ImageView android:layout_width="wrap_content" android:layout_height="wrap_content" android:src="@drawable/action_plan" /> <TextView android:layout_width="0.2dp" android:layout_height="fill_parent" android:layout_alignParentRight="true" android:background="@drawable/ln" /> </RelativeLayout> </LinearLayout> <LinearLayout android:id="@+id/controlled_medication" android:layout_width="wrap_content" android:layout_height="wrap_content" android:gravity="center" android:orientation="vertical" > <RelativeLayout android:layout_width="fill_parent" android:layout_height="match_parent" > <ImageView android:layout_width="wrap_content" android:layout_height="wrap_content" android:src="@drawable/controlled" /> <TextView android:layout_width="0.2dp" android:layout_height="fill_parent" android:layout_alignParentRight="true" android:background="@drawable/ln" /> </RelativeLayout> </LinearLayout> <LinearLayout android:id="@+id/as_needed_medication" android:layout_width="wrap_content" android:layout_height="wrap_content" android:gravity="center" android:orientation="vertical" > <RelativeLayout android:layout_width="fill_parent" android:layout_height="match_parent" android:orientation="horizontal" > <ImageView android:layout_width="wrap_content" android:layout_height="wrap_content" android:src="@drawable/as_needed" /> <TextView android:layout_width="0.2dp" android:layout_height="fill_parent" android:layout_alignParentRight="true" android:background="@drawable/ln" /> </RelativeLayout> </LinearLayout> <LinearLayout android:id="@+id/rescue_medication" android:layout_width="wrap_content" android:layout_height="wrap_content" android:gravity="center" android:orientation="vertical" > <RelativeLayout android:layout_width="fill_parent" android:layout_height="match_parent" > <ImageView android:layout_width="wrap_content" android:layout_height="wrap_content" android:src="@drawable/rescue" /> <TextView android:layout_width="0.2dp" android:layout_height="fill_parent" android:layout_alignParentRight="true" android:background="@drawable/ln" /> </RelativeLayout> </LinearLayout> <LinearLayout android:id="@+id/your_symptoms" android:layout_width="wrap_content" android:layout_height="wrap_content" android:gravity="center" android:orientation="vertical" > <RelativeLayout android:layout_width="fill_parent" android:layout_height="match_parent" > <ImageView android:layout_width="wrap_content" android:layout_height="wrap_content" android:src="@drawable/symptoms" /> <TextView android:layout_width="0.2dp" android:layout_height="fill_parent" android:layout_alignParentRight="true" android:background="@drawable/ln" /> </RelativeLayout> </LinearLayout> <LinearLayout android:id="@+id/your_triggers" android:layout_width="wrap_content" android:layout_height="wrap_content" android:gravity="center" android:orientation="vertical" > <RelativeLayout android:layout_width="fill_parent" android:layout_height="match_parent" > <ImageView android:layout_width="wrap_content" android:layout_height="wrap_content" android:src="@drawable/triggers" /> <TextView android:layout_width="0.2dp" android:layout_height="fill_parent" android:layout_alignParentRight="true" android:background="@drawable/ln" /> </RelativeLayout> </LinearLayout> <LinearLayout android:id="@+id/wheeze_rate" android:layout_width="wrap_content" android:layout_height="wrap_content" android:gravity="center" android:orientation="vertical" > <RelativeLayout android:layout_width="fill_parent" android:layout_height="match_parent" > <ImageView android:layout_width="wrap_content" android:layout_height="wrap_content" android:src="@drawable/wheeze_rate" /> <TextView android:layout_width="0.2dp" android:layout_height="fill_parent" android:layout_alignParentRight="true" android:background="@drawable/ln" /> </RelativeLayout> </LinearLayout> <LinearLayout android:id="@+id/peak_flow" android:layout_width="wrap_content" android:layout_height="wrap_content" android:gravity="center" android:orientation="vertical" > <RelativeLayout android:layout_width="fill_parent" android:layout_height="match_parent" > <ImageView android:layout_width="wrap_content" android:layout_height="wrap_content" android:src="@drawable/peak_flow" /> <TextView android:layout_width="0.2dp" android:layout_height="fill_parent" android:layout_alignParentRight="true" android:background="@drawable/ln" /> </RelativeLayout> </LinearLayout> </LinearLayout> </HorizontalScrollView> <TextView android:layout_width="fill_parent" android:layout_height="0.2dp" android:layout_alignParentRight="true" android:layout_below="@+id/hsv" android:background="@drawable/ln" /> <LinearLayout android:id="@+id/prev" android:layout_width="wrap_content" android:layout_height="fill_parent" android:layout_alignParentLeft="true" android:layout_centerVertical="true" android:paddingLeft="5dip" android:paddingRight="5dip" android:descendantFocusability="blocksDescendants" > <ImageView android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center_vertical" android:src="@drawable/prev_arrow" /> </LinearLayout> <LinearLayout android:id="@+id/next" android:layout_width="wrap_content" android:layout_height="fill_parent" android:layout_alignParentRight="true" android:layout_centerVertical="true" android:paddingLeft="5dip" android:paddingRight="5dip" android:descendantFocusability="blocksDescendants" > <ImageView android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center_vertical" android:src="@drawable/next_arrow" /> </LinearLayout> </RelativeLayout>
grid_item.xml
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" > <ImageView android:id="@+id/imageView1" android:layout_width="fill_parent" android:layout_height="100dp" android:src="@drawable/ic_launcher" /> </LinearLayout>
MainActivity.java
import java.util.ArrayList;
import android.app.Activity;
import android.graphics.Rect;
import android.os.Bundle;
import android.os.Handler;
import android.view.Display;
import android.view.GestureDetector;
import android.view.GestureDetector.SimpleOnGestureListener;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.widget.HorizontalScrollView;
import android.widget.LinearLayout;
import android.widget.LinearLayout.LayoutParams;
public class MainActivity extends Activity {
LinearLayout asthmaActionPlan, controlledMedication, asNeededMedication,
rescueMedication, yourSymtoms, yourTriggers, wheezeRate, peakFlow;
LayoutParams params;
LinearLayout next, prev;
int viewWidth;
GestureDetector gestureDetector = null;
HorizontalScrollView horizontalScrollView;
ArrayList<LinearLayout> layouts;
int parentLeft, parentRight;
int mWidth;
int currPosition, prevPosition;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
prev = (LinearLayout) findViewById(R.id.prev);
next = (LinearLayout) findViewById(R.id.next);
horizontalScrollView = (HorizontalScrollView) findViewById(R.id.hsv);
gestureDetector = new GestureDetector(new MyGestureDetector());
asthmaActionPlan = (LinearLayout) findViewById(R.id.asthma_action_plan);
controlledMedication = (LinearLayout) findViewById(R.id.controlled_medication);
asNeededMedication = (LinearLayout) findViewById(R.id.as_needed_medication);
rescueMedication = (LinearLayout) findViewById(R.id.rescue_medication);
yourSymtoms = (LinearLayout) findViewById(R.id.your_symptoms);
yourTriggers = (LinearLayout) findViewById(R.id.your_triggers);
wheezeRate = (LinearLayout) findViewById(R.id.wheeze_rate);
peakFlow = (LinearLayout) findViewById(R.id.peak_flow);
Display display = getWindowManager().getDefaultDisplay();
mWidth = display.getWidth(); // deprecated
viewWidth = mWidth / 3;
layouts = new ArrayList<LinearLayout>();
params = new LayoutParams(viewWidth, LayoutParams.WRAP_CONTENT);
asthmaActionPlan.setLayoutParams(params);
controlledMedication.setLayoutParams(params);
asNeededMedication.setLayoutParams(params);
rescueMedication.setLayoutParams(params);
yourSymtoms.setLayoutParams(params);
yourTriggers.setLayoutParams(params);
wheezeRate.setLayoutParams(params);
peakFlow.setLayoutParams(params);
layouts.add(asthmaActionPlan);
layouts.add(controlledMedication);
layouts.add(asNeededMedication);
layouts.add(rescueMedication);
layouts.add(yourSymtoms);
layouts.add(yourTriggers);
layouts.add(wheezeRate);
layouts.add(peakFlow);
next.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
new Handler().postDelayed(new Runnable() {
public void run() {
horizontalScrollView.smoothScrollTo(
(int) horizontalScrollView.getScrollX()
+ viewWidth,
(int) horizontalScrollView.getScrollY());
}
}, 100L);
}
});
prev.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
new Handler().postDelayed(new Runnable() {
public void run() {
horizontalScrollView.smoothScrollTo(
(int) horizontalScrollView.getScrollX()
- viewWidth,
(int) horizontalScrollView.getScrollY());
}
}, 100L);
}
});
horizontalScrollView.setOnTouchListener(new OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
if (gestureDetector.onTouchEvent(event)) {
return true;
}
return false;
}
});
}
class MyGestureDetector extends SimpleOnGestureListener {
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX,
float velocityY) {
if (e1.getX() < e2.getX()) {
currPosition = getVisibleViews("left");
} else {
currPosition = getVisibleViews("right");
}
horizontalScrollView.smoothScrollTo(layouts.get(currPosition)
.getLeft(), 0);
return true;
}
}
public int getVisibleViews(String direction) {
Rect hitRect = new Rect();
int position = 0;
int rightCounter = 0;
for (int i = 0; i < layouts.size(); i++) {
if (layouts.get(i).getLocalVisibleRect(hitRect)) {
if (direction.equals("left")) {
position = i;
break;
} else if (direction.equals("right")) {
rightCounter++;
position = i;
if (rightCounter == 2)
break;
}
}
}
return position;
}
}
Let me know if any issue enjoy...
Old school of doing things by hand has always been good for me.
Clean the select and leave the first option:
$('#your_select_id').find('option').remove()
.end().append('<option value="0">Selec...</option>')
.val('whatever');
If your data comes from a Json or whatever (just Concat the data):
var JSONObject = JSON.parse(data);
newOptionsSelect = '';
for (var key in JSONObject) {
if (JSONObject.hasOwnProperty(key)) {
var newOptionsSelect = newOptionsSelect + '<option value="'+JSONObject[key]["value"]+'">'+JSONObject[key]["text"]+'</option>';
}
}
$('#your_select_id').append( newOptionsSelect );
My Json Objetc:
[{"value":1,"text":"Text 1"},{"value":2,"text":"Text 2"},{"value":3,"text":"Text 3"}]
This solution is ideal for working with Ajax, and answers in Json from a database.
I had this error because I included the requirejs file along with other librairies included directly in a script tag. Those librairies (like lodash) used a define function that was conflicting with require's define. The requirejs file was loading asynchronously so I suspect that the require's define was defined after the other libraries define, hence the conflict.
To get rid of the error, include all your other js files by using requirejs.
According to Visa's "Card Acceptance and Chargeback Management Guidelines for Visa Merchants"; "Good Thru" (or "Valid Thru") Date is the expiration date of the card:
A card is valid through the last day of the month shown, (e .g ., if the Good Thru date is 03/12,the card is valid through March 31, 2012 and expires on April 1, 2012 .)
It is located below the embossed account number. If the current transaction date is after the "Good Thru" date, the card has expired.
import random
sourcelist=[]
resultlist=[]
for x in range(100):
sourcelist.append(x)
for y in sourcelist:
resultlist.insert(random.randint(0,len(resultlist)),y)
print (resultlist)
Its an auto-implemented property for C#.
You can try lib Ouzo goodies, and do this in fluent way:
echo Clock::now()->plusHours($hours)->format("Y-m-d H:m:s");
API's allow multiple operations.
You can also try ternary operator. Something like this
{{data.id === 5 ? "it's true" : "it's false"}}
Change your html code little bit and try this hope so it will be work for you.
As @epascarello mentioned for W3C standard browsers, you should use:
body.addEventListener("load", init, false);
However, if you want it to work on IE<9 as well you can use:
var prefix = window.addEventListener ? "" : "on";
var eventName = window.addEventListener ? "addEventListener" : "attachEvent";
document.body[eventName](prefix + "load", init, false);
Or if you want it in a single line:
document.body[window.addEventListener ? 'addEventListener' : 'attachEvent'](
window.addEventListener ? "load" : "onload", init, false);
Note: here I get a straight reference to the body element via the document, saving the need for the first line.
Also, if you're using jQuery, and you want to use the DOM ready
event rather than when the body load
s, the answer can be even shorter...
$(init);
Using the accepted answer my script kept returning exceptionally early (right after 'exec > >(tee ...)') leaving the rest of my script running in the background. As I couldn't get that solution to work my way I found another solution/work around to the problem:
# Logging setup
logfile=mylogfile
mkfifo ${logfile}.pipe
tee < ${logfile}.pipe $logfile &
exec &> ${logfile}.pipe
rm ${logfile}.pipe
# Rest of my script
This makes output from script go from the process, through the pipe into the sub background process of 'tee' that logs everything to disc and to original stdout of the script.
Note that 'exec &>' redirects both stdout and stderr, we could redirect them separately if we like, or change to 'exec >' if we just want stdout.
Even thou the pipe is removed from the file system in the beginning of the script it will continue to function until the processes finishes. We just can't reference it using the file name after the rm-line.
In case anyone likes it, here is a .NET 4+ only solution formed as an extension method without the needless Dispose call on the MemoryStream. This is a hopelessly trivial optimization, but it is worth noting that failing to Dispose a MemoryStream is not a real failure.
public static class StreamHelpers
{
public static byte[] ReadFully(this Stream input)
{
var ms = new MemoryStream();
input.CopyTo(ms);
return ms.ToArray();
}
}
Many browsers' implementations (and Node) have constants, used with const
.
const SOME_VALUE = "Your string";
This const
means that you can't reassign it to any other value.
Check the compatibility notes to see if your targeted browsers are supported.
Alternatively, you could also modify the first example, using defineProperty()
or its friends and make the writable
property false
. This will mean the variable's contents can not be changed, like a constant.
I would also add a canonical link to help your SEO people:
<link rel="canonical" href="http://www.example.com/product.php?item=swedish-fish"/>
A ListView is a specialized ListBox (that is, it inherits from ListBox). It allows you to specify different views rather than a straight list. You can either roll your own view, or use GridView (think explorer-like "details view"). It's basically the multi-column listbox, the cousin of windows form's listview.
If you don't need the additional capabilities of ListView, you can certainly use ListBox if you're simply showing a list of items (Even if the template is complex).
The basic idea of this solution is to mimic the way you enumerate all the combinations without repetitions by hand in high school. Let com be List[int] of length k and nums be List[int] the given n items, where n >= k. The idea is as follows:
for x[0] in nums[0,...,n-1]
for x[1] in nums[idx_of_x[0] + 1,..,n-1]
for x[2] in nums [idx_of_x[1] + 1,...,n-1]
..........
for x[k-1] in nums [idx_of_x[k-2]+1, ..,n-1]
Obviously, k and n are variable arguments, which makes it impossible to write explicit multiple nested for-loops. This is where the recursion comes to rescue the issue.
Statement len(com) + len(nums[i:]) >= k
checks whether the remaining unvisited forward list of items can provide k iitems. By forward, I mean you should not walk the nums backward for avoiding the repeated combination, which consists of same set of items but in different order. Put it in another way, in these different orders, we can choose the order these items appear in the list by scaning the list forward. More importantly, this test clause internally prunes the recursion tree such that it only contains n choose k
recursive calls. Hence, the running time is O(n choose k
).
from typing import List
class Solution:
def combine(self, n: int, k: int) -> List[List[int]]:
assert 1 <= n <= 20
assert 1 <= k <= n
com_sets = []
self._combine_recurse(k, list(range(1, n+1)), [], com_sets)
return com_sets
def _combine_recurse(self, k: int, nums: List[int], com: List[int], com_set: List[List[int]]):
"""
O(C_n^k)
"""
if len(com) < k:
for i in range(len(nums)):
# Once again, don't com.append() since com should not be global!
if len(com) + len(nums[i:]) >= k:
self._combine_recurse(k, nums[i+1:], com + [nums[i]], com_set)
else:
if len(com) == k:
com_set.append(com)
print(com)
sol = Solution()
sol.combine(5, 3)
[1, 2, 3]
[1, 2, 4]
[1, 2, 5]
[1, 3, 4]
[1, 3, 5]
[1, 4, 5]
[2, 3, 4]
[2, 3, 5]
[2, 4, 5]
[3, 4, 5]
Simply use
dialog.setCanceledOnTouchOutside(true);
You can simply use this bootstrap helper to dialogs (only 5 kB)
it has support for ajax request, iframes, common dialogs, confirm and prompt!
you can use it as:
eModal.iframe('http://someUrl.com', 'This is a tile for iframe', callbackIfNeeded);
eModal.alert('The message', 'This title');
eModal.ajax('/mypage.html', 'This is a ajax', callbackIfNeeded);
eModal.confirm('the question', 'The title', theMandatoryCallback);
eModal.prompt('Form question', 'This is a ajax', theMandatoryCallback);
this provide a loading progress while loading the iframe!
No html required.
You can use a object literal as parameter to extra options.
Check the site form more details.
best,
In Swift 5, Use this Extension
:
extension Array where Element: Equatable{
mutating func remove (element: Element) {
if let i = self.firstIndex(of: element) {
self.remove(at: i)
}
}
}
example:
var array = ["alpha", "beta", "gamma"]
array.remove(element: "beta")
In Swift 3, Use this Extension
:
extension Array where Element: Equatable{
mutating func remove (element: Element) {
if let i = self.index(of: element) {
self.remove(at: i)
}
}
}
example:
var array = ["alpha", "beta", "gamma"]
array.remove(element: "beta")
If you have a project ready and just want to change some code and then build. Check out MSBuild which is located in the Microsoft.Net under windows directory.
C:\Windows\Microsoft.NET\Framework\v4.0.30319\msbuild "C:\Projects\MyProject.csproj" /p:Configuration=Debug;DeployOnBuild=True;PackageAsSingleFile=False;outdir=C:\Projects\MyProjects\Publish\
(Please do not edit, leave as a single line)
... The line above broken up for readability
C:\Windows\Microsoft.NET\Framework\v4.0.30319\msbuild "C:\Projects\MyProject.csproj"
/p:Configuration=Debug;DeployOnBuild=True;PackageAsSingleFile=False;
outdir=C:\Projects\MyProjects\Publish\
As of 2018 and beyond, you have a more modern option which is to incorporate async/await in your ReactJS application. A promise-based HTTP client library such as axios can be used. The sample code is given below:
import axios from 'axios';
...
class Login extends Component {
constructor(props, context) {
super(props, context);
this.onLogin = this.onLogin.bind(this);
...
}
async onLogin() {
const { email, password } = this.state;
try {
const response = await axios.post('/login', { email, password });
console.log(response);
} catch (err) {
...
}
}
...
}
Ok. I found a program buried deep in other files from the beginning of the year that does what I want. I can't really comment on the suggestions offered because I'm not an experienced spim or low level programmer.Here it is:
.text
.globl __start
__start:
la $a0,str1 #Load and print string asking for string
li $v0,4
syscall
li $v0,8 #take in input
la $a0, buffer #load byte space into address
li $a1, 20 # allot the byte space for string
move $t0,$a0 #save string to t0
syscall
la $a0,str2 #load and print "you wrote" string
li $v0,4
syscall
la $a0, buffer #reload byte space to primary address
move $a0,$t0 # primary address = t0 address (load pointer)
li $v0,4 # print string
syscall
li $v0,10 #end program
syscall
.data
buffer: .space 20
str1: .asciiz "Enter string(max 20 chars): "
str2: .asciiz "You wrote:\n"
###############################
#Output:
#Enter string(max 20 chars): qwerty 123
#You wrote:
#qwerty 123
#Enter string(max 20 chars): new world oreddeYou wrote:
# new world oredde //lol special character
###############################
The first preserves the original stacktrace:
try { ... }
catch
{
// Do something.
throw;
}
The second allows you to change the type of the exception and/or the message and other data:
try { ... } catch (Exception e)
{
throw new BarException("Something broke!");
}
There's also a third way where you pass an inner exception:
try { ... }
catch (FooException e) {
throw new BarException("foo", e);
}
I'd recommend using:
YOU CAN ALSO DOWNLOAD THE CODE IN THE BELOW LINK AND SEE HOW IT WORKS
https://gallery.technet.microsoft.com/Extract-Database-dfa53d5a
THIS IS HOW YOU WILL SEE THE OUTPUT OF THIS QUERY
set nocount off
IF OBJECT_ID(N'tempdb..##temp1') IS NOT NULL
DROP TABLE ##temp1
create table ##temp1(query varchar(1000))
insert into ##temp1
select 'use '+db_name() +';'
insert into ##temp1
select 'go'
/*creating database roles*/
insert into ##temp1
select 'if DATABASE_PRINCIPAL_ID('''+name+''') is null
exec sp_addrole '''+name+'''' from sysusers
where issqlrole = 1 and (sid is not null and sid <> 0x0)
/*creating application roles*/
insert into ##temp1
select 'if DATABASE_PRINCIPAL_ID('+char(39)+name+char(39)+')
is null CREATE APPLICATION ROLE ['+name+'] WITH DEFAULT_SCHEMA = ['+
default_schema_name+'], Password='+char(39)+'Pass$w0rd123'+char(39)+' ;'
from sys.database_principals
where type_desc='APPLICATION_ROLE'
insert into ##temp1
select
case
when state_desc='GRANT_WITH_GRANT_OPTION'
then
substring (state_desc,0,6)+' '+permission_name+' to '+'['+USER_NAME(grantee_principal_id)+']'+' WITH GRANT OPTION ;'
else
state_desc+' '+permission_name+' to '+'['+USER_NAME(grantee_principal_id)+']'+' ;'
END
from sys.database_permissions
where class=0 and USER_NAME(grantee_principal_id) not in ('dbo','guest','sys','information_schema')
insert into ##temp1
select
case
when state_desc='GRANT_WITH_GRANT_OPTION'
then
substring (state_desc,0,6)+' '+permission_name+' on '+OBJECT_SCHEMA_NAME(major_id)+'.['+OBJECT_NAME(major_id)
+'] to '+'['+USER_NAME(grantee_principal_id)+']'+' with grant option ;'
else
state_desc+' '+permission_name+' on '+OBJECT_SCHEMA_NAME(major_id)+'.['+OBJECT_NAME(major_id)
+'] to '+'['+USER_NAME(grantee_principal_id)+']'+' ;'
end
from sys.database_permissions where class=1 and USER_NAME(grantee_principal_id) not in ('public');
insert into ##temp1
select
case
when state_desc='GRANT_WITH_GRANT_OPTION'
then
substring (state_desc,0,6)+' '+permission_name+' ON schema::['+sa.name+
'] to ['+user_name(dp.grantee_principal_id)+'] with grant option ;'
else
state_desc+' '+permission_name+' ON schema::['+sa.name+
'] to ['+user_name(dp.grantee_principal_id)+'] ;'
COLLATE LATIN1_General_CI_AS
end
from sys.database_permissions dp inner join sys.schemas sa on
sa.schema_id = dp.major_id where dp.class=3
insert into ##temp1
select
case
when state_desc='GRANT_WITH_GRANT_OPTION'
then
substring (state_desc,0,6)+' '+permission_name+' ON APPLICATION ROLE::['+sa.name+
'] to ['+user_name(dp.grantee_principal_id)+'] with grant option ;'
else
state_desc+' '+permission_name+' ON APPLICATION ROLE::['+sa.name+
'] to ['+user_name(dp.grantee_principal_id)+'] ;'
COLLATE LATIN1_General_CI_AS
end
from sys.database_permissions dp inner join sys.database_principals sa on
sa.principal_id = dp.major_id where dp.class=4 and sa.type='A'
insert into ##temp1
select
case
when state_desc='GRANT_WITH_GRANT_OPTION'
then
substring (state_desc,0,6)+' '+permission_name+' ON ROLE::['+sa.name+
'] to ['+user_name(dp.grantee_principal_id)+'] with grant option ;'
else
state_desc+' '+permission_name+' ON ROLE::['+sa.name+
'] to ['+user_name(dp.grantee_principal_id)+'] ;'
COLLATE LATIN1_General_CI_AS
end
from sys.database_permissions dp inner join
sys.database_principals sa on sa.principal_id = dp.major_id
where dp.class=4 and sa.type='R'
insert into ##temp1
select
case
when state_desc='GRANT_WITH_GRANT_OPTION'
then
substring (state_desc,0,6)+' '+permission_name+' ON ASSEMBLY::['+sa.name+
'] to ['+user_name(dp.grantee_principal_id)+'] with grant option ;'
else
state_desc+' '+permission_name+' ON ASSEMBLY::['+sa.name+
'] to ['+user_name(dp.grantee_principal_id)+'] ;'
COLLATE LATIN1_General_CI_AS
end
from sys.database_permissions dp inner join sys.assemblies sa on
sa.assembly_id = dp.major_id
where dp.class=5
insert into ##temp1
select
case
when state_desc='GRANT_WITH_GRANT_OPTION'
then
substring (state_desc,0,6)+' '+permission_name+' ON type::['
+SCHEMA_NAME(schema_id)+'].['+sa.name+
'] to ['+user_name(dp.grantee_principal_id)+'] with grant option ;'
else
state_desc+' '+permission_name+' ON type::['
+SCHEMA_NAME(schema_id)+'].['+sa.name+
'] to ['+user_name(dp.grantee_principal_id)+'] ;'
COLLATE LATIN1_General_CI_AS
end
from sys.database_permissions dp inner join sys.types sa on
sa.user_type_id = dp.major_id
where dp.class=6
insert into ##temp1
select
case
when state_desc='GRANT_WITH_GRANT_OPTION'
then
substring (state_desc,0,6)+' '+permission_name+' ON XML SCHEMA COLLECTION::['+
SCHEMA_NAME(SCHEMA_ID)+'].['+sa.name+'] to ['+user_name(dp.grantee_principal_id)+'] with grant option ;'
else
state_desc+' '+permission_name+' ON XML SCHEMA COLLECTION::['+
SCHEMA_NAME(SCHEMA_ID)+'].['+sa.name+'] to ['+user_name(dp.grantee_principal_id)+'];'
COLLATE LATIN1_General_CI_AS
end
from sys.database_permissions dp inner join sys.xml_schema_collections sa on
sa.xml_collection_id = dp.major_id
where dp.class=10
insert into ##temp1
select
case
when state_desc='GRANT_WITH_GRANT_OPTION'
then
substring (state_desc,0,6)+' '+permission_name+' ON message type::['+sa.name+
'] to ['+user_name(dp.grantee_principal_id)+'] with grant option ;'
else
state_desc+' '+permission_name+' ON message type::['+sa.name+
'] to ['+user_name(dp.grantee_principal_id)+'] ;'
COLLATE LATIN1_General_CI_AS
end
from sys.database_permissions dp inner join sys.service_message_types sa on
sa.message_type_id = dp.major_id
where dp.class=15
insert into ##temp1
select
case
when state_desc='GRANT_WITH_GRANT_OPTION'
then
substring (state_desc,0,6)+' '+permission_name+' ON contract::['+sa.name+
'] to ['+user_name(dp.grantee_principal_id)+'] with grant option ;'
else
state_desc+' '+permission_name+' ON contract::['+sa.name+
'] to ['+user_name(dp.grantee_principal_id)+'] ;'
COLLATE LATIN1_General_CI_AS
end
from sys.database_permissions dp inner join sys.service_contracts sa on
sa.service_contract_id = dp.major_id
where dp.class=16
insert into ##temp1
select
case
when state_desc='GRANT_WITH_GRANT_OPTION'
then
substring (state_desc,0,6)+' '+permission_name+' ON SERVICE::['+sa.name+
'] to ['+user_name(dp.grantee_principal_id)+'] with grant option ;'
else
state_desc+' '+permission_name+' ON SERVICE::['+sa.name+
'] to ['+user_name(dp.grantee_principal_id)+'] ;'
COLLATE LATIN1_General_CI_AS
end
from sys.database_permissions dp inner join sys.services sa on
sa.service_id = dp.major_id
where dp.class=17
insert into ##temp1
select
case
when state_desc='GRANT_WITH_GRANT_OPTION'
then
substring (state_desc,0,6)+' '+permission_name+' ON REMOTE SERVICE BINDING::['+sa.name+
'] to ['+user_name(dp.grantee_principal_id)+'] with grant option ;'
else
state_desc+' '+permission_name+' ON REMOTE SERVICE BINDING::['+sa.name+
'] to ['+user_name(dp.grantee_principal_id)+'] ;'
COLLATE LATIN1_General_CI_AS
end
from sys.database_permissions dp inner join sys.remote_service_bindings sa on
sa.remote_service_binding_id = dp.major_id
where dp.class=18
insert into ##temp1
select
case
when state_desc='GRANT_WITH_GRANT_OPTION'
then
substring (state_desc,0,6)+' '+permission_name+' ON route::['+sa.name+
'] to ['+user_name(dp.grantee_principal_id)+'] with grant option ;'
else
state_desc+' '+permission_name+' ON route::['+sa.name+
'] to ['+user_name(dp.grantee_principal_id)+'] ;'
COLLATE LATIN1_General_CI_AS
end
from sys.database_permissions dp inner join sys.routes sa on
sa.route_id = dp.major_id
where dp.class=19
insert into ##temp1
select
case
when state_desc='GRANT_WITH_GRANT_OPTION'
then
substring (state_desc,0,6)+' '+permission_name+' ON FULLTEXT CATALOG::['+sa.name+
'] to ['+user_name(dp.grantee_principal_id)+'] with grant option ;'
else
state_desc+' '+permission_name+' ON FULLTEXT CATALOG::['+sa.name+
'] to ['+user_name(dp.grantee_principal_id)+'] ;'
COLLATE LATIN1_General_CI_AS
end
from sys.database_permissions dp inner join sys.fulltext_catalogs sa on
sa.fulltext_catalog_id = dp.major_id
where dp.class=23
insert into ##temp1
select
case
when state_desc='GRANT_WITH_GRANT_OPTION'
then
substring (state_desc,0,6)+' '+permission_name+' ON SYMMETRIC KEY::['+sa.name+
'] to ['+user_name(dp.grantee_principal_id)+'] with grant option ;'
else
state_desc+' '+permission_name+' ON SYMMETRIC KEY::['+sa.name+
'] to ['+user_name(dp.grantee_principal_id)+'] ;'
COLLATE LATIN1_General_CI_AS
end
from sys.database_permissions dp inner join sys.symmetric_keys sa on
sa.symmetric_key_id = dp.major_id
where dp.class=24
insert into ##temp1
select
case
when state_desc='GRANT_WITH_GRANT_OPTION'
then
substring (state_desc,0,6)+' '+permission_name+' ON certificate::['+sa.name+
'] to ['+user_name(dp.grantee_principal_id)+'] with grant option ;'
else
state_desc+' '+permission_name+' ON certificate::['+sa.name+
'] to ['+user_name(dp.grantee_principal_id)+'] ;'
COLLATE LATIN1_General_CI_AS
end
from sys.database_permissions dp inner join sys.certificates sa on
sa.certificate_id = dp.major_id
where dp.class=25
insert into ##temp1
select
case
when state_desc='GRANT_WITH_GRANT_OPTION'
then
substring (state_desc,0,6)+' '+permission_name+' ON ASYMMETRIC KEY::['+sa.name+
'] to ['+user_name(dp.grantee_principal_id)+'] with grant option ;'
else
state_desc+' '+permission_name+' ON ASYMMETRIC KEY::['+sa.name+
'] to ['+user_name(dp.grantee_principal_id)+'] ;'
COLLATE LATIN1_General_CI_AS
end
from sys.database_permissions dp inner join sys.asymmetric_keys sa on
sa.asymmetric_key_id = dp.major_id
where dp.class=26
insert into ##temp1
select 'exec sp_addrolemember ''' +p.NAME+''','+'['+m.NAME+']'+' ;'
FROM sys.database_role_members rm
JOIN sys.database_principals p
ON rm.role_principal_id = p.principal_id
JOIN sys.database_principals m
ON rm.member_principal_id = m.principal_id
where m.name not like 'dbo';
select * from ##temp1
strtotime()
gives you a number back that represents a time in seconds. To increment it, add the corresponding number of seconds you want to add. 10 hours = 60*60*10 = 36000, so...
$date = date('h:i:s A', strtotime($today)+36000); // $today is today date
Edit: I had assumed you had a string time in $today - if you're just using the current time, even simpler:
$date = date('h:i:s A', time()+36000); // time() returns a time in seconds already
No performance implications that I'm aware of or have ever run into, as far as I know its just "syntactic sugar" and compiles down to the same thing as using delegate syntax, etc.
It is an implementation of Pythagorean theorem. Link: http://en.wikipedia.org/wiki/Pythagorean_theorem
Make Executable your jar and after that double click on it on Mac OS then it works successfully.
sudo chmod +x filename.jar
Try this, I hope this works.
I have had similar problems on and off. The error message often provides very little detail, regardless of actual cause. But I found a way to get more useful info. It turns out that the internal android class 'LayoutInflater.java' (in android.view package) has an 'inflate' method that re-throws an exception, but does not pick up the details, so you lose info on the cause.
I used AndroidStudio, and set a breakpoint at LayoutInflator line 539 (in the version I'm working in), which is the first line of the catch block for a generic exception in that 'inflate' method:
} catch (Exception e) {
InflateException ex = new InflateException(
parser.getPositionDescription()
+ ": " + e.getMessage());
ex.initCause(e);
throw ex;
If you look at 'e' in the debugger, you will see a 'cause' field. It can be very helpful in giving you a hint about what really occurred. This is how, for example, I found that the parent of an included fragment must have an id, even if not used in your code. Or that a TextView had an issue with a dimension.
Unfortunately this isn't entirely possible as the ClassLoader won't tell you what classes are available. You can, however, get fairly close doing something like this:
for (String classpathEntry : System.getProperty("java.class.path").split(System.getProperty("path.separator"))) {
if (classpathEntry.endsWith(".jar")) {
File jar = new File(classpathEntry);
JarInputStream is = new JarInputStream(new FileInputStream(jar));
JarEntry entry;
while( (entry = is.getNextJarEntry()) != null) {
if(entry.getName().endsWith(".class")) {
// Class.forName(entry.getName()) and check
// for implementation of the interface
}
}
}
}
Edit: johnstok is correct (in the comments) that this only works for standalone Java applications, and won't work under an application server.
Always try to use parametrized sql query to keep safe from malicious occurrence, so you could rearrange you code as below:
Also make sure that your table has column name matches to Name
, PhoneNo
,Address
.
using (SqlConnection connection = new SqlConnection(connectionString))
{
SqlCommand cmd = new SqlCommand("INSERT INTO Data (Name, PhoneNo, Address) VALUES (@Name, @PhoneNo, @Address)");
cmd.CommandType = CommandType.Text;
cmd.Connection = connection;
cmd.Parameters.AddWithValue("@Name", txtName.Text);
cmd.Parameters.AddWithValue("@PhoneNo", txtPhone.Text);
cmd.Parameters.AddWithValue("@Address", txtAddress.Text);
connection.Open();
cmd.ExecuteNonQuery();
}
I tested Github Flavored Markdown for a while and can summarize with four rules:
-
For example, if your section is named this:
## 1.1 Hello World
Create a link to it this way:
[Link](#11-hello-world)
Regardless of what error Oracle SQL Developer may indicate in the syntax highlighting, actually running your alter
statement exactly the way you originally had it works perfectly:
ALTER TABLE TEST_PROJECT2 MODIFY proj_name VARCHAR2(300);
You only need to add parenthesis if you need to alter more than one column at once, such as:
ALTER TABLE TEST_PROJECT2 MODIFY (proj_name VARCHAR2(400), proj_desc VARCHAR2(400));
For example, attempting to run a build on a device running iOS 9.3 in Xcode 7.2 results in this error; Could not find Developer Disk Image
.
Why an error message that actually describes what the hell is going on can't be provided is beyond me (Apple, I'm looking at you ).
Update to the latest version of Xcode through the App Store or via direct download to guarantee interoperability with connected iOS hardware.
Most efficient mapping of a one-to-one association You can avoid all these problems and get rid of the foreign key column by using the same primary key value for both associated entities. You can do that by annotating the owning side of the association with @MapsId.
@Entity
public class Book {
@Id
@GeneratedValue
private Long id;
@OneToOne(mappedBy = "book", fetch = FetchType.LAZY, optional = false)
private Manuscript manuscript;
...
}
@Entity
public class Manuscript {
@Id
private Long id;
@OneToOne
@MapsId
@JoinColumn(name = "id")
private Book book;
...
}
Book b = em.find(Book.class, 100L);
Manuscript m = em.find(Manuscript.class, b.getId());
In force layouts simply setting the 'height' and 'width' attributes will not work to re-center/move the plot into the svg container. However, there's a very simple answer that works for Force Layouts found here. In summary:
Use same (any) eventing you like.
window.on('resize', resize);
Then assuming you have svg & force variables:
var svg = /* D3 Code */;
var force = /* D3 Code */;
function resize(e){
// get width/height with container selector (body also works)
// or use other method of calculating desired values
var width = $('#myselector').width();
var height = $('#myselector').height();
// set attrs and 'resume' force
svg.attr('width', width);
svg.attr('height', height);
force.size([width, height]).resume();
}
In this way, you don't re-render the graph entirely, we set the attributes and d3 re-calculates things as necessary. This at least works when you use a point of gravity. I'm not sure if that's a prerequisite for this solution. Can anyone confirm or deny ?
Cheers, g
GPS Visualizer has an interface by which you can cut and paste a CSV file and convert it to kml:
http://www.gpsvisualizer.com/map_input?form=googleearth
Then use Google Earth. If you don't have Google Earth and want to display it online I found another nifty service that will plot kml files online:
The normal method to send a file upload is POST, thus also post_max_size
should be 16 Mb or more.
Incidentally, also memory_limit
plays a role. It should be bigger than 16Mb, but since the default value is 128Mb, you won't see this problem. Example php.ini
configuration:
post_max_size = 16M
upload_max_filesize = 16M
memory_limit = 128M
Change these value in php.ini
if you've access to it, otherwise you can try to change them in an .htaccess
file.
php_value upload_max_filesize 16M
php_value post_max_size 16M
This will work only if the AllowOverride
settings permit it. Otherwise, you've to ask to your hosting company.
according to NPM Doc
So it seems that by running npm install package_name
, the package dependency should be automatically added to package.json right?
You can find the DMGs or XIPs for Xcode and other development tools on https://developer.apple.com/download/more/ (requires Apple ID to login).
You must login to have a valid session before downloading anything below.
*(Newest on top. For each minor version (6.3, 5.1, etc.) only the latest revision is kept in the list.)
*With Xcode 12.2, Apple introduces the term “Release Candidate” (RC) which replaces “GM seed” and indicates this version is near final.
Xcode 12
12.4 (requires a Mac with Apple silicon running macOS Big Sur 11 or later, or an Intel-based Mac running macOS Catalina 10.15.4 or later) (Latest as of 27-Jan-2021)
12.3 (requires a Mac with Apple silicon running macOS Big Sur 11 or later, or an Intel-based Mac running macOS Catalina 10.15.4 or later)
12.0.1 (Requires macOS 10.15.4 or later) (Latest as of 24-Sept-2020)
Xcode 11
11.7 (Latest as of Sept 02 2020)
11.4.1 (Requires macOS 10.15.2 or later)
11 (Requires macOS 10.14.4 or later)
Xcode 10 (unsupported for iTunes Connect)
Xcode 9
Xcode 8
Xcode 7
Xcode 6
Even Older Versions (unsupported for iTunes Connect)
Use ave
, ddply
, dplyr
or data.table
:
df$num <- ave(df$val, df$cat, FUN = seq_along)
or:
library(plyr)
ddply(df, .(cat), mutate, id = seq_along(val))
or:
library(dplyr)
df %>% group_by(cat) %>% mutate(id = row_number())
or (the most memory efficient, as it assigns by reference within DT
):
library(data.table)
DT <- data.table(df)
DT[, id := seq_len(.N), by = cat]
DT[, id := rowid(cat)]
About access
<ol class="viewer-nav">
<li *ngFor="let section of sections"
[attr.data-sectionvalue]="section.value"
(click)="get_data($event)">
{{ section.text }}
</li>
</ol>
And
get_data(event) {
console.log(event.target.dataset.sectionvalue)
}
Since PostgreSQL 9.1 there is the convenient FOREACH
:
DO
$do$
DECLARE
m varchar[];
arr varchar[] := array[['key1','val1'],['key2','val2']];
BEGIN
FOREACH m SLICE 1 IN ARRAY arr
LOOP
RAISE NOTICE 'another_func(%,%)',m[1], m[2];
END LOOP;
END
$do$
Solution for older versions:
DO
$do$
DECLARE
arr varchar[] := '{{key1,val1},{key2,val2}}';
BEGIN
FOR i IN array_lower(arr, 1) .. array_upper(arr, 1)
LOOP
RAISE NOTICE 'another_func(%,%)',arr[i][1], arr[i][2];
END LOOP;
END
$do$
Also, there is no difference between varchar[]
and varchar[][]
for the PostgreSQL type system. I explain in more detail here.
The DO
statement requires at least PostgreSQL 9.0, and LANGUAGE plpgsql
is the default (so you can omit the declaration).
my answer is transposed of 3x3 matrix
#include<iostream.h>
#include<math.h>
main()
{
int a[3][3];
int b[3];
cout<<"You must give us an array 3x3 and then we will give you Transposed it "<<endl;
for(int i=0;i<3;i++)
{
for(int j=0;j<3;j++)
{
cout<<"Enter a["<<i<<"]["<<j<<"]: ";
cin>>a[i][j];
}
}
cout<<"Matrix you entered is :"<<endl;
for (int e = 0 ; e < 3 ; e++ )
{
for ( int f = 0 ; f < 3 ; f++ )
cout << a[e][f] << "\t";
cout << endl;
}
cout<<"\nTransposed of matrix you entered is :"<<endl;
for (int c = 0 ; c < 3 ; c++ )
{
for ( int d = 0 ; d < 3 ; d++ )
cout << a[d][c] << "\t";
cout << endl;
}
return 0;
}
In the navigator under SCHEMAS, right click your schema/database and select "Table Data Import Wizard"
Works for mac too.
For tensorflow-2.0
it's very simple.
import tensorflow as tf
model.save("model_name")
model = tf.keras.models.load_model('model_name')
Don't worry... Its much easy to solve your problem. Just SET you SDK-LOCATION and JDK-LOCATION.
Clik Android Sdk Location
Select & Browse your Android SDK Location (Like: C:\Android\sdk)
Uncheck USE EMBEDDED JDK LOCATION
Currently (November 2009), I am testing with jdk6 update 17 the following configuration set of options (with Galileo -- eclipse 3.5.x, see below for 3.4 or above for Helios 3.6.x):
(of course, adapt the relative paths present in this eclipse.ini to the correct paths for your setup)
Note: for eclipse3.5, replace startup
and launcher.library
lines by:
-startup
plugins/org.eclipse.equinox.launcher_1.0.200.v20090520.jar
--launcher.library
plugins/org.eclipse.equinox.launcher.win32.win32.x86_1.0.200.v20090519
-data
../../workspace
-showlocation
-showsplash
org.eclipse.platform
--launcher.XXMaxPermSize
384m
-startup
plugins/org.eclipse.equinox.launcher_1.0.201.R35x_v20090715.jar
--launcher.library
plugins/org.eclipse.equinox.launcher.win32.win32.x86_1.0.200.v20090519
-vm
../../../../program files/Java/jdk1.6.0_17/jre/bin/client/jvm.dll
-vmargs
-Dosgi.requiredJavaVersion=1.5
-Xms128m
-Xmx384m
-Xss4m
-XX:PermSize=128m
-XX:MaxPermSize=384m
-XX:CompileThreshold=5
-XX:MaxGCPauseMillis=10
-XX:MaxHeapFreeRatio=70
-XX:+UseConcMarkSweepGC
-XX:+CMSIncrementalMode
-XX:+CMSIncrementalPacing
-Dcom.sun.management.jmxremote
-Dorg.eclipse.equinox.p2.reconciler.dropins.directory=C:/jv/eclipse/mydropins
See also my original answer above for more information.
org.eclipse.equinox.p2.reconciler.dropins.directory
option.There was a bug with ignored breakpoints actually related to the JDK.
Do use JDK6u16 or more recent for launching eclipse (You can then define as many JDKs you want to compile within eclipse: it is not because you launch an eclipse with JDK6 that you will have to compile with that same JDK).
Note the usage of:
--launcher.XXMaxPermSize
384m
-vmargs
-XX:MaxPermSize=128m
As documented in the Eclipse Wiki,
Eclipse 3.3 supports a new argument to the launcher:
--launcher.XXMaxPermSize
.
If the VM being used is a Sun VM and there is not already a-XX:MaxPermSize=
VM argument, then the launcher will automatically add-XX:MaxPermSize=256m
to the list of VM arguments being used.
The 3.3 launcher is only capable of identifying Sun VMs on Windows.
As detailed in this entry:
Not all vms accept the
-XX:MaxPermSize
argument which is why it is passed in this manner. There may (or may not) exist problems with identifying sun vms.
Note: Eclipse 3.3.1 has a bug where the launcher cannot detect a Sun VM, and therefore does not use the correct PermGen size. It seems this may have been a known bug on Mac OS X for 3.3.0 as well.
If you are using either of these platform combination, add the-XX
flag to theeclipse.ini
as described above.Notes:
- the "
384m
" line translates to the "=384m
" part of the VM argument, if the VM is case sensitive on the "m
", then the so is this argument.- the "
--launcher.
" prefix, this specifies that the argument is consumed by the launcher itself and was added to launcher specific arguments to avoid name collisions with application arguments. (Other examples are--launcher.library
,--launcher.suppressErrors
)The
-vmargs -XX:MaxPermSize=384m
part is the argument passed directly to the VM, bypassing the launcher entirely and no check on the VM vendor is used.
Solution native Javascript :
document.getElementById("theSelectId").insertBefore(new Option('', ''), document.getElementById("theSelectId").firstChild);
example : http://codepen.io/anon/pen/GprybL
$ cat x.mak all: echo $(OPTION) $ make -f x.mak 'OPTION=-DPASSTOC=42' echo -DPASSTOC=42 -DPASSTOC=42
In your SQL Developer Bin Folder find
\sqldeveloper\bin\sqldeveloper.conf
It should be
SetJavaHome \path\to\jdk
You said it was ../../jdk
originally so you could ultimatey do 1 of two things:
SetJavaHome C:\Program Files\Java\jdk1.7.0_60
This is assuming that you have JDK 1.7.60 installed in that directory; you don't want to point it to the bin
folder you want the whole JDK folder.
OR
The second thing you can do is find the jdk
folder in the sqldeveloper folder for me its sqldeveloper\jdk
and copy and paste the contents from C:\Program Files\Java\jdk1.7.0_60
. You then have to revert your change to read
SetJavaHome ../../jdk
in your sqldeveloper.conf
If all else fails you can always redownload the sqldeveloper that already contains the jdk7 all zipped up and ready for you to run at will: Download SQL Developer The file I talk about is called Windows 64-bit - zip file includes the JDK 7
The stroke doubles up on the middel sections, I used this layer list drawable:
<layer-list xmlns:android="http://schemas.android.com/apk/res/android" >
<item android:top="0dp" android:left="0dp" android:bottom="0dp" android:right="0dp">
<shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="rectangle">
<solid android:color="@color/grey" />
</shape>
</item>
<item android:top="1dp" android:left="1dp" android:bottom="1dp" android:right="1dp">
<shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="rectangle">
<solid android:color="@color/lightgrey" />
</shape>
</item>
</layer-list>
Serialize both objects, then calculate Hash Code, then compare.
VT-x can normally be disabled/enabled in your BIOS.
When your PC is just starting up you should press DEL (or something) to get to the BIOS settings. There you'll find an option to enable VT-technology (or something).
You've got all the necessary pieces somewhere in this thread:
if cv2.waitKey(): cv2.destroyAllWindows()
works fine for me in IDLE.
Aergistal's answer works, but I found that converting to mp4 can make some m3u8 videos broken. If you are stuck with this problem, try to convert them to mkv, and convert them to mp4 later.
Try this one -
CREATE PROC [dbo].[getVoucherNo]
AS BEGIN
DECLARE
@Prefix VARCHAR(10) = 'J'
, @startFrom INT = 1
, @maxCode VARCHAR(100)
, @sCode INT
IF EXISTS(
SELECT 1
FROM dbo.Journal_Entry
) BEGIN
SELECT @maxCode = CAST(MAX(CAST(SUBSTRING(Voucher_No,LEN(@startFrom)+1,ABS(LEN(Voucher_No)- LEN(@Prefix))) AS INT)) AS varchar(100))
FROM dbo.Journal_Entry;
SELECT @Prefix +
CAST(LEN(LEFT(@maxCode, 10) + 1) AS VARCHAR(10)) + -- !!! possible problem here
CAST(@maxCode AS VARCHAR(100))
END
ELSE BEGIN
SELECT (@Prefix + CAST(@startFrom AS VARCHAR))
END
END
Some general notes.
$obj | Select-Object
? $obj | Select-Object -Property *
The latter will show all non-intrinsic, non-compiler-generated properties. The former does not appear to (always) show all Property types (in my tests, it does appear to show the CodeProperty
MemberType
consistently though -- no guarantees here).
Get-Member
does not get static members by default. You also cannot (directly) get them along with the non-static members. That is, using the switch causes only static members to be returned:
PS Y:\Power> $obj | Get-Member -Static
TypeName: System.IsFire.TurnUpProtocol
Name MemberType Definition
---- ---------- ----------
Equals Method static bool Equals(System.Object objA, System.Object objB)
...
Use the -Force
.
The
Get-Member
command uses the Force parameter to add the intrinsic members and compiler-generated members of the objects to the display.Get-Member
gets these members, but it hides them by default.
PS Y:\Power> $obj | Get-Member -Static
TypeName: System.IsFire.TurnUpProtocol
Name MemberType Definition
---- ---------- ----------
...
pstypenames CodeProperty System.Collections.ObjectModel.Collection...
psadapted MemberSet psadapted {AccessRightType, AccessRuleType,...
...
ConvertTo-Json
for depth and readable "serialization"I do not necessary recommend saving objects using JSON (use Export-Clixml
instead).
However, you can get a more or less readable output from ConvertTo-Json
, which also allows you to specify depth.
Note that not specifying Depth
implies -Depth 2
PS Y:\Power> ConvertTo-Json $obj -Depth 1
{
"AllowSystemOverload": true,
"AllowLifeToGetInTheWay": false,
"CantAnyMore": true,
"LastResortOnly": true,
...
And if you aren't planning to read it you can -Compress
it (i.e. strip whitespace)
PS Y:\Power> ConvertTo-Json $obj -Depth 420 -Compress
-InputObject
if you can (and are willing)99.9% of the time when using PowerShell: either the performance won't matter, or you don't care about the performance. However, it should be noted that avoiding the pipe when you don't need it can save some overhead and add some speed (piping, in general, is not super-efficient).
That is, if you all you have is a single $obj
handy for printing (and aren't too lazy like me sometimes to type out -InputObject
):
# select is aliased (hardcoded) to Select-Object
PS Y:\Power> select -Property * -InputObject $obj
# gm is aliased (hardcoded) to Get-Member
PS Y:\Power> gm -Force -InputObject $obj
Caveat for Get-Member -InputObject
:
If $obj is a collection (e.g. System.Object[]
), You end up getting information about the collection object itself:
PS Y:\Power> gm -InputObject $obj,$obj2
TypeName: System.Object[]
Name MemberType Definition
---- ---------- ----------
Count AliasProperty Count = Length
...
If you want to Get-Member
for each TypeName
in the collection (N.B. for each TypeName
, not for each object--a collection of N objects with all the same TypeName
will only print 1 table for that TypeName
, not N tables for each object)......just stick with piping it in directly.
None of the answers helped me, so I'm posting the solution that worked for me, all I had to do is to import the SQLPS module, I realized this when by accident I ran the Restore-SqlDatabase command and started working, meaning that the assembly was referenced in that module somehow.
Just run:
Import-module SQLPS
Note: Thanks Jason for noting that SQLPS is deprecated
instead run:
Import-Module SqlServer
or
Install-Module SqlServer
You better use the Java HashMap object for that purpose http://download.oracle.com/javase/1,5.0/docs/api/java/util/HashMap.html
Not with CSS, but you can emulate and extend / customize the desired behavior with JavaScript.
In Java 8, we can now use the Files utility to walk a file tree. Very simple.
Files.walk(root.toPath())
.filter(path -> !Files.isDirectory(path))
.forEach(path -> System.out.println(path));
If you don't need to preserve any of the outputs you already successfully compiled
nmake /A
rebuilds all
Each iteration of the forEach()
will call the function that you have supplied. To stop further processing within any given iteration (and continue with the next item) you just have to return
from the function at the appropriate point:
elementsCollection.forEach(function(element){
if (!element.shouldBeProcessed)
return; // stop processing this iteration
// This part will be avoided if not neccessary
doSomeLengthyOperation();
});
You could do:
var matchingDog = AllDogs.FirstOrDefault(dog => dog.Id == "2"));
This will return the matching dog, else it will return null
.
You can then set the property like follows:
if (matchingDog != null)
matchingDog.Name = "New Dog Name";
Well I'm 99% percent positive that you cannot just go and change the background color of a UIButton. Instead you have to go and change the background images yourself which I think is a pain. I'm amazed that I had to do this.
If I'm wrong or if theres a better way without having to set background images please let me know
[random setBackgroundImage:[UIImage imageNamed:@"toggleoff.png"] forState:UIControlStateNormal];
[random setTitleColor:[UIColor darkTextColor] forState:UIControlStateNormal];
[random setBackgroundImage:[UIImage imageNamed:@"toggleon.png"] forState:UIControlStateNormal];
[random setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
You could use euclidean distance from the point highest and nearest the viewer, except that is not quite right. It results in spherical sort order. You can straighten that out by looking from further away. Further away the curvature becomes flattened out. So just add say 1000 to each of the x,y and z components to give x',y' and z'. The sort on x'*x'+y'*y'+z'*z'.
In my case, i tried all solutions but nothing worked.
My SO is windows 7 x64, with all the Redistributable Packages (x86,x64 / 2010,2013,2015)
The problem was that i tried to install the x64 workbench, but for some reason did not work (even my SO is x64).
so, the solution was download the x86 installer from : https://downloads.mysql.com/archives/workbench/
You can easily make a Php script to parse your old htaccess, I am using this one for PRestashop rules :
$content = $_POST['content'];
$lines = explode(PHP_EOL, $content);
$results = '';
foreach($lines as $line)
{
$items = explode(' ', $line);
$q = str_replace("^", "^/", $items[1]);
if (substr($q, strlen($q) - 1) !== '$') $q .= '$';
$buffer = 'rewrite "'.$q.'" "'.$items[2].'" last;';
$results .= $buffer.PHP_EOL;
}
die($results);
Compared to window.location="url";
it is much easyer to do just location="url";
I always use that
Simples
function time($block) {
$sw = [Diagnostics.Stopwatch]::StartNew()
&$block
$sw.Stop()
$sw.Elapsed
}
then can use as
time { .\some_command }
You may want to tweak the output
Try use this:
input {
clear: both;
float: right;
margin-bottom: 10px;
width: 100px;
}
For a simple copy-tasks I can recommend copy-rename-maven-plugin. It's straight forward and simple to use:
<project>
...
<build>
<plugins>
<plugin>
<groupId>com.coderplus.maven.plugins</groupId>
<artifactId>copy-rename-maven-plugin</artifactId>
<version>1.0</version>
<executions>
<execution>
<id>copy-file</id>
<phase>generate-sources</phase>
<goals>
<goal>copy</goal>
</goals>
<configuration>
<sourceFile>src/someDirectory/test.environment.properties</sourceFile>
<destinationFile>target/someDir/environment.properties</destinationFile>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
</project>
If you would like to copy more than one file, replace the <sourceFile>...</destinationFile>
part with
<fileSets>
<fileSet>
<sourceFile>src/someDirectory/test.environment.properties</sourceFile>
<destinationFile>target/someDir/environment.properties</destinationFile>
</fileSet>
<fileSet>
<sourceFile>src/someDirectory/test.logback.xml</sourceFile>
<destinationFile>target/someDir/logback.xml</destinationFile>
</fileSet>
</fileSets>
Furthermore you can specify multiple executions in multiple phases if needed, the second goal is "rename", which simply does what it says while the rest of the configuration stays the same. For more usage examples refer to the Usage-Page.
Note: This plugin can only copy files, not directories. (Thanks to @james.garriss for finding this limitation.)
org.postgresql.util.PSQLException: FATAL: sorry, too many clients already.
Summary:
You opened up more than the allowed limit of connections to the database. You ran something like this: Connection conn = myconn.Open();
inside of a loop, and forgot to run conn.close();
. Just because your class is destroyed and garbage collected does not release the connection to the database. The quickest fix to this is to make sure you have the following code with whatever class that creates a connection:
protected void finalize() throws Throwable
{
try { your_connection.close(); }
catch (SQLException e) {
e.printStackTrace();
}
super.finalize();
}
Place that code in any class where you create a Connection. Then when your class is garbage collected, your connection will be released.
Run this SQL to see postgresql max connections allowed:
show max_connections;
The default is 100. PostgreSQL on good hardware can support a few hundred connections at a time. If you want to have thousands, you should consider using connection pooling software to reduce the connection overhead.
Take a look at exactly who/what/when/where is holding open your connections:
SELECT * FROM pg_stat_activity;
The number of connections currently used is:
SELECT COUNT(*) from pg_stat_activity;
Debugging strategy
You could give different usernames/passwords to the programs that might not be releasing the connections to find out which one it is, and then look in pg_stat_activity to find out which one is not cleaning up after itself.
Do a full exception stack trace when the connections could not be created and follow the code back up to where you create a new Connection
, make sure every code line where you create a connection ends with a connection.close();
How to set the max_connections higher:
max_connections in the postgresql.conf sets the maximum number of concurrent connections to the database server.
SHOW config_file;
/var/lib/pgsql/data/postgresql.conf
max_connections=100
.What's the maximum max_connections?
Use this query:
select min_val, max_val from pg_settings where name='max_connections';
I get the value 8388607
, in theory that's the most you are allowed to have, but then a runaway process can eat up thousands of connections, and surprise, your database is unresponsive until reboot. If you had a sensible max_connections like 100. The offending program would be denied a new connection.
Please take a look at your addtype directives.
It looks to me like Apache is telling the browser that it's sending a document type of application/php for scripts with extensions like .php5. In fact Apache is supposed to tell the browser that the script is outputting text/html.
Please try this:
AddType text/html .php
Regarding the suggestion above that you should tell the browser that you are outputting a PHP script: It seemed like an unusual idea to me. I googled it and found that there is quite a bit of discussion about it on the web. Apparently there are cases where you might want to say that you are sending a PHP script (even though Apache is supposed to execute the script and emit text/html,) and there are also cases where the browser simply doesn't recognize that specific Mime Type.
Clearing your browser cache is always a good idea.
In case it's helpful here's a copy of my /etc/httpd/conf.d/php.conf file from a server running CentOS 5.9:
#
# PHP is an HTML-embedded scripting language which attempts to make it
# easy for developers to write dynamically generated webpages.
#
<IfModule prefork.c>
LoadModule php5_module modules/libphp5.so
</IfModule>
<IfModule worker.c>
LoadModule php5_module modules/libphp5-zts.so
</IfModule>
#
# Cause the PHP interpreter to handle files with a .php extension.
#
AddHandler php5-script .php
AddType text/html .php
#
# Add index.php to the list of files that will be served as directory
# indexes.
#
DirectoryIndex index.php
#
# Uncomment the following line to allow PHP to pretty-print .phps
# files as PHP source code:
#
#AddType application/x-httpd-php-source .phps
Unless you have GNU awk 4.1.0 or later...
You won't have such an option as sed's -i
option so instead do:
$ awk '{print $0}' file > tmp && mv tmp file
Note: the -i
is not magic, it is also creating a temporary file sed
just handles it for you.
As of GNU awk 4.1.0...
GNU awk
added this functionality in version 4.1.0 (released 10/05/2013). It is not as straight forwards as just giving the -i
option as described in the released notes:
The new -i option (from xgawk) is used for loading awk library files. This differs from -f in that the first non-option argument is treated as a script.
You need to use the bundled inplace.awk
include file to invoke the extension properly like so:
$ cat file
123 abc
456 def
789 hij
$ gawk -i inplace '{print $1}' file
$ cat file
123
456
789
The variable INPLACE_SUFFIX
can be used to specify the extension for a backup file:
$ gawk -i inplace -v INPLACE_SUFFIX=.bak '{print $1}' file
$ cat file
123
456
789
$ cat file.bak
123 abc
456 def
789 hij
I am happy this feature has been added but to me, the implementation isn't very awkish as the power comes from the conciseness of the language and -i inplace
is 8 characters too long i.m.o.
Here is a link to the manual for the official word.
I believe it would be like this
takedata.match(/(\[.+\])/g);
the g
at the end means global, so it doesn't stop at the first match.
This really belongs with @Ramnath's answer but I can't comment as I don't have enough reputation yet. You can also use the arrange
function from the dplyr
package in the same way as the plyr
package.
library(dplyr)
arrange(DF, ID, desc(num))
[myButton setTitle: @"myTitle" forState: UIControlStateNormal];
Use UIControlStateNormal
to set your title.
There are couple of states that UIbuttons provide, you can have a look:
[myButton setTitle: @"myTitle" forState: UIControlStateApplication];
[myButton setTitle: @"myTitle" forState: UIControlStateHighlighted];
[myButton setTitle: @"myTitle" forState: UIControlStateReserved];
[myButton setTitle: @"myTitle" forState: UIControlStateSelected];
[myButton setTitle: @"myTitle" forState: UIControlStateDisabled];
check this out :)
var traingIds = "[1,2]"; // ${triningIdArray} this value getting from server
alert(traingIds); // alerts [1,2]
var type = typeof(traingIds);
alert(type); // // alerts String
//remove square brackets
traingIds = traingIds.replace('[','');
traingIds = traingIds.replace(']','');
alert(traingIds); // alerts 1,2
var trainindIdArray = traingIds.split(',');
?for(i = 0; i< trainindIdArray.length; i++){
alert(trainindIdArray[i]); //outputs individual numbers in array
}?
There are two "generations" of python-docx. The initial generation ended with the 0.2.x versions and the "new" generation started at v0.3.0. The new generation is a ground-up, object-oriented rewrite of the legacy version. It has a distinct repository located here.
The opendocx() function is part of the legacy API. The documentation is for the new version. The legacy version has no documentation to speak of.
Neither reading nor writing hyperlinks are supported in the current version. That capability is on the roadmap, and the project is under active development. It turns out to be quite a broad API because Word has so much functionality. So we'll get to it, but probably not in the next month unless someone decides to focus on that aspect and contribute it. UPDATE Hyperlink support was added subsequent to this answer.
Not beautiful, but a solution nonetheless:
StringWriter writer = new StringWriter();
PrintWriter printWriter = new PrintWriter( writer );
exception.printStackTrace( printWriter );
printWriter.flush();
String stackTrace = writer.toString();
Shorter answer: ignore it.
This module is the part of Postgres that processes the SQL language. The error will often pop up as part of copying a remote database, such as with a 'heroku pg:pull'. It does not overwrite your SQL processor and warns you about that.
Why do you need a console application if you want to hide console itself? =)
I recommend setting Project Output type to Windows Application instead of Console application. It will not show you console window, but execute all actions, like Console application do.
Try this... I have tried and work fine for me
This issue is related to low memory...
Close your browsers, visual Studio and other services..
after that run following command
ionic build android
it will run successfully..
//Solutions is
create "gradle.properties" file in android folder and add following line into file
org.gradle.jvmargs=-Xmx512m -XX:MaxPermSize=512m
<your project>\platforms\android\gradle.properties
You can open browser and others..
ionic build android
Now it will work fine.
line[5:]
will give the substring you want. Search the introduction and look for 'slice notation'
Spring is moving away from XML files and uses annotations heavily. The following example is a simple standalone Spring application which uses annotation instead of XML files.
package com.zetcode.bean;
import org.springframework.stereotype.Component;
@Component
public class Message {
private String message = "Hello there!";
public void setMessage(String message){
this.message = message;
}
public String getMessage(){
return message;
}
}
This is a simple bean. It is decorated with the @Component
annotation for auto-detection by Spring container.
package com.zetcode.main;
import com.zetcode.bean.Message;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.ComponentScan;
@ComponentScan(basePackages = "com.zetcode")
public class Application {
public static void main(String[] args) {
ApplicationContext context
= new AnnotationConfigApplicationContext(Application.class);
Application p = context.getBean(Application.class);
p.start();
}
@Autowired
private Message message;
private void start() {
System.out.println("Message: " + message.getMessage());
}
}
This is the main Application
class. The @ComponentScan
annotation searches for components. The @Autowired
annotation injects the bean into the message
variable. The AnnotationConfigApplicationContext
is used to create the Spring application context.
My Standalone Spring tutorial shows how to create a standalone Spring application with both XML and annotations.
You could try this
$('#myFieldID').focus(function(){
$(this).val('');
});
I had this error using the Mongo 2.2 driver for PHP:
$collection = $db->selectCollection('post');
$collection->ensureIndex(array('someField', 'someOtherField', 'yetAnotherField'));
^^DOESN'T WORK
$collection = $db->selectCollection('post');
$collection->ensureIndex(array('someField', 'someOtherField'));
$collection->ensureIndex(array('yetAnotherField'));
^^ WORKS! (?!)
on the basis of your only jQuery
tag :)
HTML
<select id="my-select">
<option value="1">This is text 1</option>
<option value="2">This is text 2</option>
<option value="3">This is text 3</option>
</select>
For text --
$(document).ready(function() {
$("#my-select").change(function() {
alert($('#my-select option:selected').html());
});
});
For value --
$(document).ready(function() {
$("#my-select").change(function() {
alert($(this).val());
});
});
An easy way to implement multiple field comparisons is with Guava's ComparisonChain - then you can say
public int compareTo(Foo that) {
return ComparisonChain.start()
.compare(lastName, that.lastName)
.compare(firstName, that.firstName)
.compare(zipCode, that.zipCode)
.result();
}
instead of
public int compareTo(Person other) {
int cmp = lastName.compareTo(other.lastName);
if (cmp != 0) {
return cmp;
}
cmp = firstName.compareTo(other.firstName);
if (cmp != 0) {
return cmp;
}
return Integer.compare(zipCode, other.zipCode);
}
}
This might be helpful for whoever else faces this problem. I finally figured out a solution. Turns out, even if we use the inline for "content-disposition" and specify a file name, the browsers still do not use the file name. Instead browsers try and interpret the file name based on the Path/URL.
You can read further on this URL: Securly download file inside browser with correct filename
This gave me an idea, I just created my URL route that would convert the URL and end it with the name of the file I wanted to give the file. So for e.g. my original controller call just consisted of passing the Order Id of the Order being printed. I was expecting the file name to be of the format Order{0}.pdf where {0} is the Order Id. Similarly for quotes, I wanted Quote{0}.pdf.
In my controller, I just went ahead and added an additional parameter to accept the file name. I passed the filename as a parameter in the URL.Action method.
I then created a new route that would map that URL to the format: http://localhost/ShoppingCart/PrintQuote/1054/Quote1054.pdf
routes.MapRoute("", "{controller}/{action}/{orderId}/{fileName}",
new { controller = "ShoppingCart", action = "PrintQuote" }
, new string[] { "x.x.x.Controllers" }
);
This pretty much solved my issue. Hoping this helps someone!
Cheerz, Anup
Change your TableView Style:
self.tableview = [[UITableView alloc] initwithFrame:frame style:UITableViewStyleGrouped];
As per apple documentation for UITableView:
UITableViewStylePlain- A plain table view. Any section headers or footers are displayed as inline separators and float when the table view is scrolled.
UITableViewStyleGrouped- A table view whose sections present distinct groups of rows. The section headers and footers do not float.
Hope this small change will help you ..
Because of the definition of the semantics of nth-child
, I don't see how this is possible without including the length of the list of elements involved. The point of the semantics is to allow segregation of a bunch of child elements into repeating groups (edit - thanks BoltClock) or into a first part of some fixed length, followed by "the rest". You sort-of want the opposite of that, which is what nth-last-child
gives you.
You can apply the list as separate arguments:
print(*L)
and let print()
take care of converting each element to a string. You can, as always, control the separator by setting the sep
keyword argument:
>>> L = [1, 2, 3, 4, 5]
>>> print(*L)
1 2 3 4 5
>>> print(*L, sep=', ')
1, 2, 3, 4, 5
>>> print(*L, sep=' -> ')
1 -> 2 -> 3 -> 4 -> 5
Unless you need the joined string for something else, this is the easiest method. Otherwise, use str.join()
:
joined_string = ' '.join([str(v) for v in L])
print(joined_string)
# do other things with joined_string
Note that this requires manual conversion to strings for any non-string values in L
!
You forgot to specify the variable name. It should be CERas.CERAS newCeras = new CERas.CERAS();
[Updated Dec 2020]: Tested and Included 5.0
version of Bootstrap.
I know this question is old. And the question did not mentioned which version of Bootstrap he was using. So i'll assume the answer to this question is resolved.
If any of you (like me) stumbled upon this question and looking for answer using current bootstrap 5.0 (2020) and 4.5 (2019) framework, then here's the solution.
Use d-flex justify-content-center
on your column div. This will center everything inside that column.
<div class="row">
<div class="col-4 d-flex justify-content-center">
// Image
</div>
</div>
If you want to align the text inside the col just use text-center
<div class="row">
<div class="col-4 text-center">
// text only
</div>
</div>
If you have text and image inside the column, you need to use d-flex
justify-content-center
and text-center
.
<div class="row">
<div class="col-4 d-flex justify-content-center text-center">
// for image and text
</div>
</div>
this works fine, but file name does not display anymore.
$(document).ready(function(){ $("img.attach2").click(function(){ $("input.attach1").click(); return false; }); });
Generally, when you find yourself fighting against a framework standard practices, it is time to reconsider your approach. In this case, the behavior of ModelState. For instance, when you don't want model state after a POST, consider a redirect to the get.
[HttpPost]
public ActionResult Edit(MyCmsPage page, string submitButton)
{
if (ModelState.IsValid) {
SomeRepository.SaveChanges(page);
return RedirectToAction("GenerateSeoTitle",new { page.Id });
}
return View(page);
}
public ActionResult GenerateSeoTitle(int id) {
var page = SomeRepository.Find(id);
page.GenerateSeoTitle();
return View("Edit",page);
}
EDITED to answer culture comment:
Here is what I use to handle a multi-cultural MVC application. First the route handler subclasses:
public class SingleCultureMvcRouteHandler : MvcRouteHandler {
protected override IHttpHandler GetHttpHandler(RequestContext requestContext)
{
var culture = requestContext.RouteData.Values["culture"].ToString();
if (string.IsNullOrWhiteSpace(culture))
{
culture = "en";
}
var ci = new CultureInfo(culture);
Thread.CurrentThread.CurrentUICulture = ci;
Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture(ci.Name);
return base.GetHttpHandler(requestContext);
}
}
public class MultiCultureMvcRouteHandler : MvcRouteHandler
{
protected override IHttpHandler GetHttpHandler(RequestContext requestContext)
{
var culture = requestContext.RouteData.Values["culture"].ToString();
if (string.IsNullOrWhiteSpace(culture))
{
culture = "en";
}
var ci = new CultureInfo(culture);
Thread.CurrentThread.CurrentUICulture = ci;
Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture(ci.Name);
return base.GetHttpHandler(requestContext);
}
}
public class CultureConstraint : IRouteConstraint
{
private string[] _values;
public CultureConstraint(params string[] values)
{
this._values = values;
}
public bool Match(HttpContextBase httpContext,Route route,string parameterName,
RouteValueDictionary values, RouteDirection routeDirection)
{
// Get the value called "parameterName" from the
// RouteValueDictionary called "value"
string value = values[parameterName].ToString();
// Return true is the list of allowed values contains
// this value.
return _values.Contains(value);
}
}
public enum Culture
{
es = 2,
en = 1
}
And here is how I wire up the routes. After creating the routes, I prepend my subagent (example.com/subagent1, example.com/subagent2, etc) then the culture code. If all you need is the culture, simply remove the subagent from the route handlers and routes.
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.IgnoreRoute("Content/{*pathInfo}");
routes.IgnoreRoute("Cache/{*pathInfo}");
routes.IgnoreRoute("Scripts/{pathInfo}.js");
routes.IgnoreRoute("favicon.ico");
routes.IgnoreRoute("apple-touch-icon.png");
routes.IgnoreRoute("apple-touch-icon-precomposed.png");
/* Dynamically generated robots.txt */
routes.MapRoute(
"Robots.txt", "robots.txt",
new { controller = "Robots", action = "Index", id = UrlParameter.Optional }
);
routes.MapRoute(
"Sitemap", // Route name
"{subagent}/sitemap.xml", // URL with parameters
new { subagent = "aq", controller = "Default", action = "Sitemap"}, new[] { "aq3.Controllers" } // Parameter defaults
);
routes.MapRoute(
"Rss Feed", // Route name
"{subagent}/rss", // URL with parameters
new { subagent = "aq", controller = "Default", action = "RSS"}, new[] { "aq3.Controllers" } // Parameter defaults
);
/* remap wordpress tags to mvc blog posts */
routes.MapRoute(
"Tag", "tag/{title}",
new { subagent = "aq", controller = "Default", action = "ThreeOhOne", id = UrlParameter.Optional}, new[] { "aq3.Controllers" }
).RouteHandler = new MultiCultureMvcRouteHandler(); ;
routes.MapRoute(
"Custom Errors", "Error/{*errorType}",
new { controller = "Error", action = "Index", id = UrlParameter.Optional}, new[] { "aq3.Controllers" }
);
/* dynamic images not loaded from content folder */
routes.MapRoute(
"Stock Images",
"{subagent}/Images/{*filename}",
new { subagent = "aq", controller = "Image", action = "Show", id = UrlParameter.Optional, culture = "en"}, new[] { "aq3.Controllers" }
);
/* localized routes follow */
routes.MapRoute(
"Localized Images",
"Images/{*filename}",
new { subagent = "aq", controller = "Image", action = "Show", id = UrlParameter.Optional}, new[] { "aq3.Controllers" }
).RouteHandler = new MultiCultureMvcRouteHandler();
routes.MapRoute(
"Blog Posts",
"Blog/{*postname}",
new { subagent = "aq", controller = "Blog", action = "Index", id = UrlParameter.Optional}, new[] { "aq3.Controllers" }
).RouteHandler = new MultiCultureMvcRouteHandler();
routes.MapRoute(
"Office Posts",
"Office/{*address}",
new { subagent = "aq", controller = "Offices", action = "Address", id = UrlParameter.Optional }, new[] { "aq3.Controllers" }
).RouteHandler = new MultiCultureMvcRouteHandler();
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
new { subagent = "aq", controller = "Home", action = "Index", id = UrlParameter.Optional }, new[] { "aq3.Controllers" } // Parameter defaults
).RouteHandler = new MultiCultureMvcRouteHandler();
foreach (System.Web.Routing.Route r in routes)
{
if (r.RouteHandler is MultiCultureMvcRouteHandler)
{
r.Url = "{subagent}/{culture}/" + r.Url;
//Adding default culture
if (r.Defaults == null)
{
r.Defaults = new RouteValueDictionary();
}
r.Defaults.Add("culture", Culture.en.ToString());
//Adding constraint for culture param
if (r.Constraints == null)
{
r.Constraints = new RouteValueDictionary();
}
r.Constraints.Add("culture", new CultureConstraint(Culture.en.ToString(), Culture.es.ToString()));
}
}
}
I had an issue using this in a user control (in a page this worked fine); the Button1 is inside an updatepanel
, and the scriptmanager
is on the usercontrol
.
protected void Button1_Click(object sender, EventArgs e)
{
string scriptstring = "alert('Welcome');";
ScriptManager.RegisterStartupScript(this, this.GetType(), "alertscript", scriptstring, true);
}
Now it seems you have to be careful with the first two arguments, they need to reference your page, not your control
ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "alertscript", scriptstring, true);
Had the same problem. If server is configured correctly and .htacces is not the answer, might want to look the svg source you are embedding. Mine were created with text editor, rendered well on Chrome&Safari inside html5 code, once embedded, nothing was visible. Added correct version, dimensions etc to the svg code and works like a charm. Also, all styles inline.
Ie
<svg version="1.1" baseProfile="full" width="24" height="24" xmlns="http://www.w3.org/2000/svg">
<rect x="0" y="0" rx="2" ry="2" width="24" height="24" style="fill:#fbc800;width:24px;height:24px;" />
</svg>
Your JSON string is malformed: the type of center
is an array of invalid objects. Replace [
and ]
with {
and }
in the JSON string around longitude
and latitude
so they will be objects:
[
{
"name" : "New York",
"number" : "732921",
"center" : {
"latitude" : 38.895111,
"longitude" : -77.036667
}
},
{
"name" : "San Francisco",
"number" : "298732",
"center" : {
"latitude" : 37.783333,
"longitude" : -122.416667
}
}
]
I made a friendly formatter for sniffing curl requests to help with debugging ( see comments for usage ). It contains's every known output parameter you can write out in an easy to read format.
https://gist.github.com/manifestinteractive/ce8dec10dcb4725b8513
Add a style with the attribute text-decoration:none;
:
There are a number of different ways of doing this.
Inline style:
<a href="xxx.html" style="text-decoration:none;">goto this link</a>
Inline stylesheet:
<html>
<head>
<style type="text/css">
a {
text-decoration:none;
}
</style>
</head>
<body>
<a href="xxx.html">goto this link</a>
</body>
</html>
External stylesheet:
<html>
<head>
<link rel="Stylesheet" href="stylesheet.css" />
</head>
<body>
<a href="xxx.html">goto this link</a>
</body>
</html>
stylesheet.css:
a {
text-decoration:none;
}
Might be better to use a choice, don't have to type (or possibly mistype) your expressions more than once, and allows you to follow additional different behaviors.
I very often use count(/html/body) = 0
, as the specific number of nodes is more interesting than the set. For example... when there is unexpectedly more than 1 node that matches your expression.
<xsl:choose>
<xsl:when test="/html/body">
<!-- Found the node(s) -->
</xsl:when>
<!-- more xsl:when here, if needed -->
<xsl:otherwise>
<!-- No node exists -->
</xsl:otherwise>
</xsl:choose>
Find any files whose name is ".kube/config
", and content include eks_use1d
:
locate ".kube/config" | xargs -i sh -c 'echo \\n{};cat {} | grep eks_use1d'
Here's one way:
create table #work
(
something decimal(8,3) not null
)
insert #work values ( 0 )
insert #work values ( 12345.6789 )
insert #work values ( 3.1415926 )
insert #work values ( 45 )
insert #work values ( 9876.123456 )
insert #work values ( -12.5678 )
select convert(varchar,convert(decimal(8,2),something))
from #work
if you want it right-aligned, something like this should do you:
select str(something,8,2) from #work
A trunk is considered your main code base, a branch offshoot of the trunk. Like, you create a branch if you want to implement a new feature, but don't want to affect the main trunk.
TortoiseSVN has good documentation, and a great diff tool.
I use Visual studio, and I use VisualSVN and TortoiseSVN.
The problem is that variables declared in one case
are still visible in the subsequent case
s unless an explicit { }
block is used, but they will not be initialized because the initialization code belongs to another case
.
In the following code, if foo
equals 1, everything is ok, but if it equals 2, we'll accidentally use the i
variable which does exist but probably contains garbage.
switch(foo) {
case 1:
int i = 42; // i exists all the way to the end of the switch
dostuff(i);
break;
case 2:
dostuff(i*2); // i is *also* in scope here, but is not initialized!
}
Wrapping the case in an explicit block solves the problem:
switch(foo) {
case 1:
{
int i = 42; // i only exists within the { }
dostuff(i);
break;
}
case 2:
dostuff(123); // Now you cannot use i accidentally
}
To further elaborate, switch
statements are just a particularly fancy kind of a goto
. Here's an analoguous piece of code exhibiting the same issue but using a goto
instead of a switch
:
int main() {
if(rand() % 2) // Toss a coin
goto end;
int i = 42;
end:
// We either skipped the declaration of i or not,
// but either way the variable i exists here, because
// variable scopes are resolved at compile time.
// Whether the *initialization* code was run, though,
// depends on whether rand returned 0 or 1.
std::cout << i;
}
I had the same problem, here's how I solved it. Following the first section of this very excellent Django tutorial, I did the following:
python manage.py startapp new_app
settings.py
file, adding the following to the list of INSTALLED_APPS
: 'new_app',
new_app
package named new_app_tags
.{% extends 'base_template_name.html' %}
: {% load new_app_tags %}
new_app_tags
module file, create a custom template tag (see below).{% multiply_by_two | "5.0" %}
Example from step 5 above:
from django import template
register = template.Library()
@register.simple_tag
def multiply_by_two(value):
return float(value) * 2.0
For Windows, first install the git base from here: https://git-scm.com/downloads
Next, set the environment variable:
C:\Program Files\Git\git-bash.exe
To test it, open the command window: press Windows+R, type cmd and then type ssh.
select time, coalesce(count(case when activities = 3 then 1 end), 0) as count
from MyTable
group by time
Output:
| TIME | COUNT |
-----------------
| 13:00 | 2 |
| 13:15 | 2 |
| 13:30 | 0 |
| 13:45 | 1 |
If you want to count all the activities in one query, you can do:
select time,
coalesce(count(case when activities = 1 then 1 end), 0) as count1,
coalesce(count(case when activities = 2 then 1 end), 0) as count2,
coalesce(count(case when activities = 3 then 1 end), 0) as count3,
coalesce(count(case when activities = 4 then 1 end), 0) as count4,
coalesce(count(case when activities = 5 then 1 end), 0) as count5
from MyTable
group by time
The advantage of this over grouping by activities, is that it will return a count of 0 even if there are no activites of that type for that time segment.
Of course, this will not return rows for time segments with no activities of any type. If you need that, you'll need to use a left join with table that lists all the possible time segments.
You can use the -notmatch operator to get the lines that don't have the characters you are interested in.
Get-Content $FileName | foreach-object {
if ($_ -notmatch $arrayofStringsNotInterestedIn) { $) }
Do it like this:
SSLSocket socket = (SSLSocket) sslFactory.createSocket(host, port);
socket.setEnabledProtocols(new String[]{"SSLv3", "TLSv1"});
Here's a script that will use the Google API to acquire the users postal code and populate an input field.
function postalCodeLookup(input) {
var head= document.getElementsByTagName('head')[0],
script= document.createElement('script');
script.src= '//maps.googleapis.com/maps/api/js?sensor=false';
head.appendChild(script);
script.onload = function() {
if (navigator.geolocation) {
var a = input,
fallback = setTimeout(function () {
fail('10 seconds expired');
}, 10000);
navigator.geolocation.getCurrentPosition(function (pos) {
clearTimeout(fallback);
var point = new google.maps.LatLng(pos.coords.latitude, pos.coords.longitude);
new google.maps.Geocoder().geocode({'latLng': point}, function (res, status) {
if (status == google.maps.GeocoderStatus.OK && typeof res[0] !== 'undefined') {
var zip = res[0].formatted_address.match(/,\s\w{2}\s(\d{5})/);
if (zip) {
a.value = zip[1];
} else fail('Unable to look-up postal code');
} else {
fail('Unable to look-up geolocation');
}
});
}, function (err) {
fail(err.message);
});
} else {
alert('Unable to find your location.');
}
function fail(err) {
console.log('err', err);
a.value('Try Again.');
}
};
}
You can adjust accordingly to acquire different information. For more info, check out the Google Maps API documentation.
I found the approach given by cimmanon and Kurt Mueller almost worked, but that I needed a parent reference (i.e., I need to add the '&' prefix to each vendor prefix); like this:
@mixin placeholder {
&::-webkit-input-placeholder {@content}
&:-moz-placeholder {@content}
&::-moz-placeholder {@content}
&:-ms-input-placeholder {@content}
}
I use the mixin like this:
input {
@include placeholder {
font-family: $base-font-family;
color: red;
}
}
With the parent reference in place, then correct css gets generated, e.g.:
input::-webkit-input-placeholder {
font-family: Constantia, "Lucida Bright", Lucidabright, "Lucida Serif", Lucida, "DejaVu Serif", "Liberation Serif", Georgia, serif;
color: red;
}
Without the parent reference (&), then a space is inserted before the vendor prefix and the CSS processor ignores the declaration; that looks like this:
input::-webkit-input-placeholder {
font-family: Constantia, "Lucida Bright", Lucidabright, "Lucida Serif", Lucida, "DejaVu Serif", "Liberation Serif", Georgia, serif;
color: red;
}
It will take some work, but is certainly not impossible.
What I have done is:
Microsoft.CSharp.CSharpCodeProvider
(CompileAssemblyFromSource)Activator.CreateInstance
)This way you can deal with the C# code you already know, instead of having to emit MSIL.
But this works best if your class implements some interface (or is derived from some baseclass), else how is the calling code (read: compiler) to know about that class that will be generated at runtime?
So in your build.gradle
file, add this:
compile 'com.android.support:design:27.1.1'
AndroidX Note: Google is introducing new AndroidX extension libraries to replace the older Support Libraries. To use AndroidX, first make sure you've updated your gradle.properties
file, edited build.gradle
to set compileSdkVersion
to 28
(or higher), and use the following line instead of the previous compile
one.
implementation 'com.google.android.material:material:1.0.0'
Next, in your themes.xml
or styles.xml
or whatever, make sure you set this- it's your app's accent color-- and the color of your FAB unless you override it (see below):
<item name="colorAccent">@color/floating_action_button_color</item>
In the layout's XML:
<RelativeLayout
...
xmlns:app="http://schemas.android.com/apk/res-auto">
<android.support.design.widget.FloatingActionButton
android:id="@+id/myFAB"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/ic_plus_sign"
app:elevation="4dp"
... />
</RelativeLayout>
Or if you are using the AndroidX material library above, you'd instead use this:
<RelativeLayout
...
xmlns:app="http://schemas.android.com/apk/res-auto">
<com.google.android.material.floatingactionbutton.FloatingActionButton
android:id="@+id/myFAB"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:srcCompat="@drawable/ic_plus_sign"
app:elevation="4dp"
... />
</RelativeLayout>
You can see more options in the docs (material docs here) (setRippleColor
, etc.), but one of note is:
app:fabSize="mini"
Another interesting one-- to change the background color of just one FAB, add:
app:backgroundTint="#FF0000"
(for example to change it to red) to the XML above.
Anyway, in code, after the Activity/Fragment's view is inflated....
FloatingActionButton myFab = (FloatingActionButton) myView.findViewById(R.id.myFAB);
myFab.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
doMyThing();
}
});
Observations:
Here's a way to remove or change the padding if there's too much:
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
RelativeLayout.LayoutParams p = (RelativeLayout.LayoutParams) myFab.getLayoutParams();
p.setMargins(0, 0, 0, 0); // get rid of margins since shadow area is now the margin
myFab.setLayoutParams(p);
}
Also, I was going to programmatically place the FAB on the "seam" between two areas in a RelativeLayout by grabbing the FAB's height, dividing by two, and using that as the margin offset. But myFab.getHeight() returned zero, even after the view was inflated, it seemed. Instead I used a ViewTreeObserver to get the height only after it's laid out and then set the position. See this tip here. It looked like this:
ViewTreeObserver viewTreeObserver = closeButton.getViewTreeObserver();
if (viewTreeObserver.isAlive()) {
viewTreeObserver.addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
@Override
public void onGlobalLayout() {
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN) {
closeButton.getViewTreeObserver().removeGlobalOnLayoutListener(this);
} else {
closeButton.getViewTreeObserver().removeOnGlobalLayoutListener(this);
}
// not sure the above is equivalent, but that's beside the point for this example...
RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams) closeButton.getLayoutParams();
params.setMargins(0, 0, 16, -closeButton.getHeight() / 2); // (int left, int top, int right, int bottom)
closeButton.setLayoutParams(params);
}
});
}
Not sure if this is the right way to do it, but it seems to work.
If you want the FAB on a "seam" you can use layout_anchor
and layout_anchorGravity
here is an example:
<android.support.design.widget.FloatingActionButton
android:layout_height="wrap_content"
android:layout_width="wrap_content"
app:layout_anchor="@id/appbar"
app:layout_anchorGravity="bottom|right|end"
android:src="@drawable/ic_discuss"
android:layout_margin="@dimen/fab_margin"
android:clickable="true"/>
Remember that you can automatically have the button jump out of the way when a Snackbar comes up by wrapping it in a CoordinatorLayout.
More:
you can also use:
SELECT CASE
WHEN upper(t.name) like 'P%' THEN
'productive'
WHEN upper(t.name) like 'T%' THEN
'test'
WHEN upper(t.name) like 'D%' THEN
'development'
ELSE
'unknown'
END as type
FROM table t
Here is a more general solution:
int increment = 3;
for(int i = 0; i < theData.Length; i += increment)
{
for(int j = 0; j < increment; j++)
{
if(i+j < theData.Length) {
//theData[i + j] for the current index
}
}
}
you can go:
var cp = require('child_process');
and then:
cp.exec('./myScript.sh', function(err, stdout, stderr) {
// handle err, stdout, stderr
});
to run a command in your $SHELL.
Or go
cp.spawn('./myScript.sh', [args], function(err, stdout, stderr) {
// handle err, stdout, stderr
});
to run a file WITHOUT a shell.
Or go
cp.execFile();
which is the same as cp.exec() but doesn't look in the $PATH.
You can also go
cp.fork('myJS.js', function(err, stdout, stderr) {
// handle err, stdout, stderr
});
to run a javascript file with node.js, but in a child process (for big programs).
You might also have to access stdin and stdout with event listeners. e.g.:
var child = cp.spawn('./myScript.sh', [args]);
child.stdout.on('data', function(data) {
// handle stdout as `data`
});
KEY
is normally a synonym for INDEX
. The key attribute PRIMARY KEY
can also be specified as just KEY
when given in a column definition. This was implemented for compatibility with other database systems.
column_definition:
data_type [NOT NULL | NULL] [DEFAULT default_value]
[AUTO_INCREMENT] [UNIQUE [KEY] | [PRIMARY] KEY]
...
Ref: http://dev.mysql.com/doc/refman/5.1/en/create-table.html
There is another workaround you can use to update using a join. This example below assumes you want to de-normalize a table by including a lookup value (in this case storing a users name in the table). The update includes a join to find the name and the output is evaluated in a CASE statement that supports the name being found or not found. The key to making this work is ensuring all the columns coming out of the join have unique names. In the sample code, notice how b.user_name conflicts with the a.user_name column and must be aliased with the unique name "user_user_name".
UPDATE
(
SELECT a.user_id, a.user_name, b.user_name as user_user_name
FROM some_table a
LEFT OUTER JOIN user_table b ON a.user_id = b.user_id
WHERE a.user_id IS NOT NULL
)
SET user_name = CASE
WHEN user_user_name IS NOT NULL THEN user_user_name
ELSE 'UNKNOWN'
END;
This happens when a keyword argument is specified that overwrites a positional argument. For example, let's imagine a function that draws a colored box. The function selects the color to be used and delegates the drawing of the box to another function, relaying all extra arguments.
def color_box(color, *args, **kwargs):
painter.select_color(color)
painter.draw_box(*args, **kwargs)
Then the call
color_box("blellow", color="green", height=20, width=30)
will fail because two values are assigned to color
: "blellow"
as positional and "green"
as keyword. (painter.draw_box
is supposed to accept the height
and width
arguments).
This is easy to see in the example, but of course if one mixes up the arguments at call, it may not be easy to debug:
# misplaced height and width
color_box(20, 30, color="green")
Here, color
is assigned 20
, then args=[30]
and color
is again assigned "green"
.
If your string is a file path, as in your example, you can also use Unix style file paths:
string foo = "D:/Projects/Some/Kind/Of/Pathproblem/wuhoo.xml";
But the other answers have the more general solutions to string escaping in C#.
You can use the old Stupid Scanner trick oneliner to do that without any additional dependency like guava:
String text = new Scanner(AppropriateClass.class.getResourceAsStream("foo.txt"), "UTF-8").useDelimiter("\\A").next();
Guys, don't use 3rd party stuff unless you really need that. There is a lot of functionality in the JDK already.
Here is a simplified version (the gist) of Mick Cullen's answer -- in part to prove that it needn't be very complex to implement this; in part to give a quick reference for anyone who isn't interested in reading pages and pages of code.
You have to make you app use connect-busboy:
var busboy = require("connect-busboy");
app.use(busboy());
This will not do anything until you trigger it. Within the call that handles uploading, do the following:
app.post("/upload", function(req, res) {
if(req.busboy) {
req.busboy.on("file", function(fieldName, fileStream, fileName, encoding, mimeType) {
//Handle file stream here
});
return req.pipe(req.busboy);
}
//Something went wrong -- busboy was not loaded
});
Let's break this down:
req.busboy
is set (the middleware was loaded correctly)"file"
listener on req.busboy
req
to req.busboy
Inside the file listener there are a couple of interesting things, but what really matters is the fileStream
: this is a Readable, that can then be written to a file, like you usually would.
Pitfall: You must handle this Readable, or express will never respond to the request, see the busboy API (file section).
So what is this "require?"
require()
is not part of the standard JavaScript API. But in Node.js, it's a built-in function with a special purpose: to load modules.
Modules are a way to split an application into separate files instead of having all of your application in one file. This concept is also present in other languages with minor differences in syntax and behavior, like C's include
, Python's import
, and so on.
One big difference between Node.js modules and browser JavaScript is how one script's code is accessed from another script's code.
In browser JavaScript, scripts are added via the <script>
element. When they execute, they all have direct access to the global scope, a "shared space" among all scripts. Any script can freely define/modify/remove/call anything on the global scope.
In Node.js, each module has its own scope. A module cannot directly access things defined in another module unless it chooses to expose them. To expose things from a module, they must be assigned to exports
or module.exports
. For a module to access another module's exports
or module.exports
, it must use require()
.
In your code, var pg = require('pg');
loads the pg
module, a PostgreSQL client for Node.js. This allows your code to access functionality of the PostgreSQL client's APIs via the pg
variable.
Why does it work in node but not in a webpage?
require()
, module.exports
and exports
are APIs of a module system that is specific to Node.js. Browsers do not implement this module system.
Also, before I got it to work in node, I had to do
npm install pg
. What's that about?
NPM is a package repository service that hosts published JavaScript modules. npm install
is a command that lets you download packages from their repository.
Where did it put it, and how does Javascript find it?
The npm cli puts all the downloaded modules in a node_modules
directory where you ran npm install
. Node.js has very detailed documentation on how modules find other modules which includes finding a node_modules
directory.
Universal extension method for DataTable. May be somebody be interesting. Idea creating dynamic properties I take from another post: https://stackoverflow.com/a/15819760/8105226
public static IEnumerable<dynamic> AsEnumerable(this DataTable dt)
{
List<dynamic> result = new List<dynamic>();
Dictionary<string, object> d;
foreach (DataRow dr in dt.Rows)
{
d = new Dictionary<string, object>();
foreach (DataColumn dc in dt.Columns)
d.Add(dc.ColumnName, dr[dc]);
result.Add(GetDynamicObject(d));
}
return result.AsEnumerable<dynamic>();
}
public static dynamic GetDynamicObject(Dictionary<string, object> properties)
{
return new MyDynObject(properties);
}
public sealed class MyDynObject : DynamicObject
{
private readonly Dictionary<string, object> _properties;
public MyDynObject(Dictionary<string, object> properties)
{
_properties = properties;
}
public override IEnumerable<string> GetDynamicMemberNames()
{
return _properties.Keys;
}
public override bool TryGetMember(GetMemberBinder binder, out object result)
{
if (_properties.ContainsKey(binder.Name))
{
result = _properties[binder.Name];
return true;
}
else
{
result = null;
return false;
}
}
public override bool TrySetMember(SetMemberBinder binder, object value)
{
if (_properties.ContainsKey(binder.Name))
{
_properties[binder.Name] = value;
return true;
}
else
{
return false;
}
}
}
List is interface and ArrayList is implemented concrete class. It is always recommended to use.
List<String> arrayList = new ArrayList<String>();
Because here list reference is flexible. It can also hold LinkedList or Vector
object.
It has really different usage scenarios. When you use GROUP BY you merge some of the records for the columns that are same and you have an aggregation of the result set.
However when you use PARTITION BY your result set is same but you just have an aggregation over the window functions and you don't merge the records, you will still have the same count of records.
Here is a rally helpful article explaining the difference: http://alevryustemov.com/sql/sql-partition-by/
My problem is cookies are not working "within" the same session. –
Burak: I had the same problem. Enabling cookies fixed the issue.
CookieManager.getInstance().setAcceptCookie(true);
simplest way to center your div element is to use this class with following properties.
.light {
margin: auto;
width: 50%;
border: 3px solid green;
padding: 10px;
}
First of all, there's no such thing as a JSON object. What you've got in your question is a JavaScript object literal (see here for a great discussion on the difference). Here's how you would go about serializing what you've got to JSON though:
I would use an anonymous type filled with your results
type:
string json = JsonConvert.SerializeObject(new
{
results = new List<Result>()
{
new Result { id = 1, value = "ABC", info = "ABC" },
new Result { id = 2, value = "JKL", info = "JKL" }
}
});
Also, note that the generated JSON has result items with id
s of type Number
instead of strings. I doubt this will be a problem, but it would be easy enough to change the type of id
to string
in the C#.
I'd also tweak your results
type and get rid of the backing fields:
public class Result
{
public int id { get ;set; }
public string value { get; set; }
public string info { get; set; }
}
Furthermore, classes conventionally are PascalCased
and not camelCased
.
Here's the generated JSON from the code above:
{
"results": [
{
"id": 1,
"value": "ABC",
"info": "ABC"
},
{
"id": 2,
"value": "JKL",
"info": "JKL"
}
]
}
For any wanderer that comes across this in the future. If your application and database are on different machines and you are getting the above error especially when using TransactionScope, enable Network DTC access. Steps to do this are:
Important: Do not edit/change the user account and password in the DTC Logon account field, leave it as is, you will end up re-installing windows if you do.
More about string can be found in String Class and String Tutorials
You need to do two things. First add the changes with
git add .
git stash
git checkout <some branch>
It should solve your issue as it solved to me.
this worked for me:
rsync /dev/null node:existing-dir/new-dir/
I do get this message :
skipping non-regular file "null"
but I don't have to worry about having an empty directory hanging around.
Just put quotes around the Environment variable (as you have done) :
if "%DevEnvDir%" == "C:\Program Files (x86)\Microsoft Visual Studio 10.0\Common7\IDE\"
but it's the way you put opening bracket without a space that is confusing it.
Works for me...
C:\if "%gtk_basepath%" == "C:\Program Files\GtkSharp\2.12\" (echo yes)
yes
Pending intent is an intent which will start at some point in the future. Normal intent starts immediately when it is passed to startActivity(Intent)
or StartService(Intent)
.
constructor(
public sanitizer: DomSanitizer, ) {
}
I had been struggling for 4 hours. the problem was in img tag. When you use square bracket to 'src' ex: [src]. you can not use this angular expression {{}}. you just give directly from an object example below. if you give angular expression {{}}. you will get interpolation error.
first i used ngFor to iterate the countries
*ngFor="let country of countries"
second you put this in the img tag. this is it.
<img [src]="sanitizer.bypassSecurityTrustResourceUrl(country.flag)"
height="20" width="20" alt=""/>
This code
int a = 5;
printf("%x\n", a);
prints
5
This code
int a = 5;
printf("0x%x\n", a);
prints
0x5
This code
int a = 89778116;
printf("%x\n", a);
prints
559e7c4
If you capitalize the x in the format it capitalizes the hex value:
int a = 89778116;
printf("%X\n", a);
prints
559E7C4
If you want to print pointers you use the p format specifier:
char* str = "foo";
printf("0x%p\n", str);
prints
0x01275744
For what it's worth I have read that the "one" place a cursor will out perform its set-based counterpart is in a running total. Over a small table the speed of summing up the rows over the order by columns favors the set-based operation but as the table increases in row size the cursor will become faster because it can simply carry the running total value to the next pass of the loop. Now where you should do a running total is a different argument...
Git tags are just pointers to the commit. So you use them the same way as you do HEAD, branch names or commit sha hashes. You can use tags with any git command that accepts commit/revision arguments. You can try it with git rev-parse tagname
to display the commit it points to.
In your case you have at least these two alternatives:
Reset the current branch to specific tag:
git reset --hard tagname
Generate revert commit on top to get you to the state of the tag:
git revert tag
This might introduce some conflicts if you have merge commits though.
To add vertical modal centering to bootstrap modal.js I added this at the end of the Modal.prototype.show
function:
var $modalDialog = $('.modal-dialog'),
modalHeight = $modalDialog.height(),
browserHeight = window.innerHeight;
$modalDialog.css({'margin-top' : modalHeight >= browserHeight ? 0 : (browserHeight - modalHeight)/2});
Do this way:-
String newline = System.getProperty("line.separator");
private static final String mText = "SHOP MA" + newline +
+ "----------------------------" + newline +
+ "Pannampitiya" + newline +
+ "09-10-2012 harsha no: 001" + newline +
+ "No Item Qty Price Amount" + newline +
+ "1 Bread 1 50.00 50.00" + newline +
+ "____________________________" + newline;
If you just want to get the information of current directory, you can type:
pwd
and you don't need to use the Nautilus, or you can use a teamviewer software to remote connect to the computer, you can get everything you want.
Use IFS (internal field separator) tool in bash, defines the character using to separate lines into tokens, by default includes <tab> /<space> /<newLine>
step 1: Load the file data and insert into list:
# declaring array list and index iterator
declare -a array=()
i=0
# reading file in row mode, insert each line into array
while IFS= read -r line; do
array[i]=$line
let "i++"
# reading from file path
done < "<yourFullFilePath>"
step 2: now iterate and print the output:
for line in "${array[@]}"
do
echo "$line"
done
echo specific index in array: Accessing to a variable in array:
echo "${array[0]}"
if not exists (select * from sysobjects where name='cars' and xtype='U')
create table cars (
Name varchar(64) not null
)
go
The above will create a table called cars
if the table does not already exist.
How about the simple way of
for (var i = 0; i < n; i++) {
sum = sum + Int(multiples[i])!
}
//where n = number of elements in the array
If you want to do it without cli, you can do it fully on Github website.
New pull request
.Create new pull request
.if (f <= LONG_MIN || f >= LONG_MAX || f == (long)f) /* it's an integer */
rather than extension methods, just try a couple of static methods
public static class Utility
{
public static string GetDescriptionFromEnumValue(Enum value)
{
DescriptionAttribute attribute = value.GetType()
.GetField(value.ToString())
.GetCustomAttributes(typeof (DescriptionAttribute), false)
.SingleOrDefault() as DescriptionAttribute;
return attribute == null ? value.ToString() : attribute.Description;
}
public static T GetEnumValueFromDescription<T>(string description)
{
var type = typeof(T);
if (!type.IsEnum)
throw new ArgumentException();
FieldInfo[] fields = type.GetFields();
var field = fields
.SelectMany(f => f.GetCustomAttributes(
typeof(DescriptionAttribute), false), (
f, a) => new { Field = f, Att = a })
.Where(a => ((DescriptionAttribute)a.Att)
.Description == description).SingleOrDefault();
return field == null ? default(T) : (T)field.Field.GetRawConstantValue();
}
}
and use here
var result1 = Utility.GetDescriptionFromEnumValue(
Animal.GiantPanda);
var result2 = Utility.GetEnumValueFromDescription<Animal>(
"Lesser Spotted Anteater");
http://vim.wikia.com/wiki/Search_and_replace
Try this search and replace:
:%s/foo/bar/gc
Change each 'foo' to 'bar', but ask for confirmation first.
Press y or n to change or keep your text.
This seems to work as well
SELECT *
FROM makerar m1
WHERE m1.avg = (SELECT MAX(avg)
FROM makerar m2
WHERE m1.cname = m2.cname
)
You could do it this way:
-- Notice how STATE got moved inside the condition:
CASE WHEN STATE = 2 AND RetailerProcessType IN (1, 2) THEN '"AUTHORISED"'
WHEN STATE = 1 AND RetailerProcessType = 2 THEN '"PENDING"'
ELSE '"DECLINED"'
END
The reason you can do an AND
here is that you are not checking the CASE
of STATE
, but instead you are CASING Conditions.
The key part here is that the STATE
condition is a part of the WHEN
.
The simplest solution would be to use Pillow lib:
from PIL import Image
image = Image.fromarray(<your_numpy_array>.astype(np.uint8))
And you can use it as an image.
Since this isn't closed, i would like to submit a new entry for anyone looking to have something working properly for them... using an amalgamation of what i found here, as well as using DirectoryServices to debug the code itself and find the proper code to use, here's what i found that works for me in every situation... note that my solution extends DirectoryInfo object... :
public static bool IsReadable(this DirectoryInfo me)
{
AuthorizationRuleCollection rules;
WindowsIdentity identity;
try
{
rules = me.GetAccessControl().GetAccessRules(true, true, typeof(System.Security.Principal.SecurityIdentifier));
identity = WindowsIdentity.GetCurrent();
}
catch (Exception ex)
{ //Posible UnauthorizedAccessException
return false;
}
bool isAllow=false;
string userSID = identity.User.Value;
foreach (FileSystemAccessRule rule in rules)
{
if (rule.IdentityReference.ToString() == userSID || identity.Groups.Contains(rule.IdentityReference))
{
if ((rule.FileSystemRights.HasFlag(FileSystemRights.Read) ||
rule.FileSystemRights.HasFlag(FileSystemRights.ReadAndExecute) ||
rule.FileSystemRights.HasFlag(FileSystemRights.ReadAttributes) ||
rule.FileSystemRights.HasFlag(FileSystemRights.ReadData) ||
rule.FileSystemRights.HasFlag(FileSystemRights.ReadExtendedAttributes) ||
rule.FileSystemRights.HasFlag(FileSystemRights.ReadPermissions)) && rule.AccessControlType == AccessControlType.Deny)
return false;
else if ((rule.FileSystemRights.HasFlag(FileSystemRights.Read) ||
rule.FileSystemRights.HasFlag(FileSystemRights.ReadAndExecute) ||
rule.FileSystemRights.HasFlag(FileSystemRights.ReadAttributes) ||
rule.FileSystemRights.HasFlag(FileSystemRights.ReadData) ||
rule.FileSystemRights.HasFlag(FileSystemRights.ReadExtendedAttributes) ||
rule.FileSystemRights.HasFlag(FileSystemRights.ReadPermissions)) && rule.AccessControlType == AccessControlType.Allow)
isAllow = true;
}
}
return isAllow;
}
public static bool IsWriteable(this DirectoryInfo me)
{
AuthorizationRuleCollection rules;
WindowsIdentity identity;
try
{
rules = me.GetAccessControl().GetAccessRules(true, true, typeof(System.Security.Principal.SecurityIdentifier));
identity = WindowsIdentity.GetCurrent();
}
catch (Exception ex)
{ //Posible UnauthorizedAccessException
return false;
}
bool isAllow = false;
string userSID = identity.User.Value;
foreach (FileSystemAccessRule rule in rules)
{
if (rule.IdentityReference.ToString() == userSID || identity.Groups.Contains(rule.IdentityReference))
{
if ((rule.FileSystemRights.HasFlag(FileSystemRights.Write) ||
rule.FileSystemRights.HasFlag(FileSystemRights.WriteAttributes) ||
rule.FileSystemRights.HasFlag(FileSystemRights.WriteData) ||
rule.FileSystemRights.HasFlag(FileSystemRights.WriteExtendedAttributes) ||
rule.FileSystemRights.HasFlag(FileSystemRights.CreateDirectories) ||
rule.FileSystemRights.HasFlag(FileSystemRights.CreateFiles)) && rule.AccessControlType == AccessControlType.Deny)
return false;
else if ((rule.FileSystemRights.HasFlag(FileSystemRights.Write) ||
rule.FileSystemRights.HasFlag(FileSystemRights.WriteAttributes) ||
rule.FileSystemRights.HasFlag(FileSystemRights.WriteData) ||
rule.FileSystemRights.HasFlag(FileSystemRights.WriteExtendedAttributes) ||
rule.FileSystemRights.HasFlag(FileSystemRights.CreateDirectories) ||
rule.FileSystemRights.HasFlag(FileSystemRights.CreateFiles)) && rule.AccessControlType == AccessControlType.Allow)
isAllow = true;
}
}
return me.IsReadable() && isAllow;
}
One hackish way to define an exit
method in context:
class Bar; def exit; end; end
This works because exit
in the initializer will be resolved as self.exit
1. In addition, this approach allows using the object after it has been created, as in: b = B.new
.
But really, one shouldn't be doing this: don't have exit
(or even puts
) there to begin with.
(And why is there an "infinite" loop and/or user input in an intiailizer? This entire problem is primarily the result of poorly structured code.)
1 Remember Kernel#exit is only a method. Since Kernel is included in every Object, then it's merely the case that exit
normally resolves to Object#exit
. However, this can be changed by introducing an overridden method as shown - nothing fancy.
The original code for the Cocoa frameworks came from the NeXTSTEP libraries Foundation and AppKit (those names are still used by Apple's Cocoa frameworks), and the NextStep engineers chose to prefix their symbols with NS.
Because Objective-C is an extension of C and thus doesn't have namespaces like in C++, symbols must be prefixed with a unique prefix so that they don't collide. This is particularly important for symbols defined in a framework.
If you are writing an application, such that your code is only likely ever to use your symbols, you don't have to worry about this. But if you're writing a framework or library for others' use, you should also prefix your symbols with a unique prefix. CocoaDev has a page where many developers in the Cocoa community have listed their "chosen" prefixes. You may also find this SO discussion helpful.
I still had the problem after all these suggestions. Some class inside App_Code was being compiled to two DLL's. Something like this (simplified):
warning CS0436: The type 'HcmDbGeographyModelBinder' in
'<user_profile_dir>\AppData\Local\Temp\Temporary ASP.NET Files\temp\3b1ed8ee\11405e8e\App_Code.oqr0kusq.0.cs'
conflicts with the imported type 'HcmDbGeographyModelBinder' in
'<user_profile_dir>\AppData\Local\Temp\Temporary ASP.NET Files\temp\3b1ed8ee\11405e8e\assembly\dl3\ea0aa3ee\6022e6d5_2cc8cf01\HCM.Web.Backoffice.DLL'.
I just renamed the "App_Code" folder to "Code". This is a MVC5 project, so there shouldn't be a problem with serving .cs files inside the web project's root.
where
is probably what you're looking for. So
data=data.where(data=='-', None)
From the panda docs:
where
[returns] an object of same shape as self and whose corresponding entries are from self where cond is True and otherwise are from other).
@JS5 , I also faced the same issue as you: ImageButton causing exceptions inside UpdatePanel only on production server and IE. After some research I found this:
There is an issue with ImageButtons and UpdatePanels. The update to .NET 4.5 is fixed there. It has something to do with Microsoft changed the x,y axis of a button click from Int to Double so you can tell where on the button you clicked and it's throwing a conversion error.
I'm using NetFramework 2.0 and IIS 6, so, the suggested solution was to downgrade IE compatibility adding a meta tag:
<meta http-equiv="X-UA-Compatible" content="IE=9" />
I've done this via Page_Load method only on the page I needed to:
Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs)
Dim tag As HtmlMeta = New HtmlMeta()
tag.HttpEquiv = "X-UA-Compatible"
tag.Content = "IE=9"
Header.Controls.Add(tag)
End Sub
Hope this helps someone.
Use the following
1.) Choose the image you want to set in your title bar.
2.) Convert it to ".ico" format. (You can use the following link online)
http://image.online-convert.com/convert-to-ico
3.) Save the file as "favicon.ico" in the same folder as your .html file
4.) Add this inside your head tag <link rel="shortcut icon" href="favicon.ico"/>
Follow the instructions at https://gist.github.com/application2000/73fd6f4bf1be6600a2cf9f56315a2d91 to set up the gcc version you need - gcc 5 or gcc 6 - on Ubuntu 14.04. The instructions include configuring update-alternatives
to allow you to switch between versions as you need to.
SELECT DISTINCT *
FROM people
WHERE names = 'Smith'
ORDER BY
names
LIMIT 10
Yes, MySQL allows multiple NULLs in a column with a unique constraint.
CREATE TABLE table1 (x INT NULL UNIQUE);
INSERT table1 VALUES (1);
INSERT table1 VALUES (1); -- Duplicate entry '1' for key 'x'
INSERT table1 VALUES (NULL);
INSERT table1 VALUES (NULL);
SELECT * FROM table1;
Result:
x
NULL
NULL
1
This is not true for all databases. SQL Server 2005 and older, for example, only allows a single NULL value in a column that has a unique constraint.
I think this will probably answer your question. Here's what I wrote there:
Here's a very general answer. Say the camera's at (Xc, Yc, Zc) and the point you want to project is P = (X, Y, Z). The distance from the camera to the 2D plane onto which you are projecting is F (so the equation of the plane is Z-Zc=F). The 2D coordinates of P projected onto the plane are (X', Y').
Then, very simply:
X' = ((X - Xc) * (F/Z)) + Xc
Y' = ((Y - Yc) * (F/Z)) + Yc
If your camera is the origin, then this simplifies to:
X' = X * (F/Z)
Y' = Y * (F/Z)
I've used CSS Grid to fix that. CSS Grid will make all the elements in the same row, all the same height.
I haven't looked into making all the elements in all the rows the same height though.
Anyway, here's how it can be done:
HTML:
<div class="grid-container">
<div class="card">...</div>
<div class="card">...</div>
</div>
CSS:
.grid-container {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
}
Here's a complete JSFiddle. https://jsfiddle.net/bluegrounds/owjvhstq/4/