Use block level buttons, those that span the full width of a parent
You can achieve this by adding btn-block
class your button element.
Documentation here
This will spool the output from the anonymous block into a file called output_<YYYYMMDD>.txt
located in the root of the local PC C: drive where <YYYYMMDD>
is the current date:
SET SERVEROUTPUT ON FORMAT WRAPPED
SET VERIFY OFF
SET FEEDBACK OFF
SET TERMOUT OFF
column date_column new_value today_var
select to_char(sysdate, 'yyyymmdd') date_column
from dual
/
DBMS_OUTPUT.ENABLE(1000000);
SPOOL C:\output_&today_var..txt
DECLARE
ab varchar2(10) := 'Raj';
cd varchar2(10);
a number := 10;
c number;
d number;
BEGIN
c := a+10;
--
SELECT ab, c
INTO cd, d
FROM dual;
--
DBMS_OUTPUT.put_line('cd: '||cd);
DBMS_OUTPUT.put_line('d: '||d);
END;
SPOOL OFF
SET TERMOUT ON
SET FEEDBACK ON
SET VERIFY ON
PROMPT
PROMPT Done, please see file C:\output_&today_var..txt
PROMPT
Hope it helps...
EDIT:
After your comment to output a value for every iteration of a cursor (I realise each value will be the same in this example but you should get the gist of what i'm doing):
BEGIN
c := a+10;
--
FOR i IN 1 .. 10
LOOP
c := a+10;
-- Output the value of C
DBMS_OUTPUT.put_line('c: '||c);
END LOOP;
--
END;
Press Ctrl+C
When you start the server it mentions this in the startup text.
You can pass vector by reference just like this:
void do_something(int el, std::vector<int> &arr){
arr.push_back(el);
}
However, note that this function would always add a new element at the back of the vector, whereas your array function actually modifies the first element (or initializes it value).
In order to achieve exactly the same result you should write:
void do_something(int el, std::vector<int> &arr){
if (arr.size() == 0) { // can't modify value of non-existent element
arr.push_back(el);
} else {
arr[0] = el;
}
}
In this way you either add the first element (if the vector is empty) or modify its value (if there first element already exists).
toISOString()
will return current UTC time only not the current local time. If you want to get the current local time in yyyy-MM-ddTHH:mm:ss.SSSZ
format then you should get the current time using following two methods
document.write(new Date(new Date().toString().split('GMT')[0]+' UTC').toISOString());
_x000D_
document.write(new Date(new Date().getTime() - new Date().getTimezoneOffset() * 60000).toISOString());
_x000D_
I just updated matplotlib to 1.1.0 on my system and it now allows me to save to jpg with savefig
.
To upgrade to matplotlib 1.1.0 with pip
, use this command:
pip install -U 'http://sourceforge.net/projects/matplotlib/files/matplotlib/matplotlib-1.1.0/matplotlib-1.1.0.tar.gz/download'
EDIT (to respond to comment):
pylab
is simply an aggregation of the matplotlib.pyplot and numpy namespaces (as well as a few others) jinto a single namespace.
On my system, pylab
is just this:
from matplotlib.pylab import *
import matplotlib.pylab
__doc__ = matplotlib.pylab.__doc__
You can see that pylab
is just another namespace in your matplotlib installation. Therefore, it doesn't matter whether or not you import it with pylab
or with matplotlib.pyplot
.
If you are still running into problem, then I'm guessing the macosx backend doesn't support saving plots to jpg. You could try using a different backend. See here for more information.
You need to decode the byte string and turn it in to a character (Unicode) string.
On Python 2
encoding = 'utf-8'
'hello'.decode(encoding)
or
unicode('hello', encoding)
On Python 3
encoding = 'utf-8'
b'hello'.decode(encoding)
or
str(b'hello', encoding)
You can also search for specific methods. For e.g. If you want to search for isEmpty()
method of the string class you have to got to - Search -> Java -> type java.lang.String.isEmpty()
and in the 'Search For' option use Method.
You can then select the scope that you require.
@Nishit, JSONObject does not natively understand how to parse through a StringBuilder; instead you appear to be using the JSONObject(java.lang.Object bean) constructor to create the JSONObject, however passing it a StringBuilder.
See this link for more information on that particular constructor.
http://www.json.org/javadoc/org/json/JSONObject.html#JSONObject%28java.lang.Object%29
When a constructor calls for a java.lang.Object class, more than likely it's really telling you that you're expected to create your own class (since all Classes ultimately extend java.lang.Object) and that it will interface with that class in a specific way, albeit normally it will call for an interface instead (hence the name) OR it can accept any class and interface with it "abstractly" such as calling .toString() on it. Bottom line, you typically can't just pass it any class and expect it to work.
At any rate, this particular constructor is explained as such:
Construct a JSONObject from an Object using bean getters. It reflects on all of the public methods of the object. For each of the methods with no parameters and a name starting with "get" or "is" followed by an uppercase letter, the method is invoked, and a key and the value returned from the getter method are put into the new JSONObject. The key is formed by removing the "get" or "is" prefix. If the second remaining character is not upper case, then the first character is converted to lower case. For example, if an object has a method named "getName", and if the result of calling object.getName() is "Larry Fine", then the JSONObject will contain "name": "Larry Fine".
So, what this means is that it's expecting you to create your own class that implements get or is methods (i.e.
public String getName() {...}
or
public boolean isValid() {...}
So, to solve your problem, if you really want that higher level of control and want to do some manipulation (e.g. modify some values, etc.) but still use StringBuilder to dynamically generate the code, you can create a class that extends the StringBuilder class so that you can use the append feature, but implement get/is methods to allow JSONObject to pull the data out of it, however this is likely not what you want/need and depending on the JSON, you might spend a lot of time and energy creating the private fields and get/is methods (or use an IDE to do it for you) or it might be all for naught if you don't necessarily know the breakdown of the JSON string.
So, you can very simply call toString()
on the StringBuilder which will provide a String representation of the StringBuilder instance and passing that to the JSONObject constructor, such as below:
...
StringBuilder jsonString = new StringBuilder();
while((readAPIResponse = br.readLine()) != null){
jsonString.append(readAPIResponse);
}
JSONObject jsonObj = new JSONObject(jsonString.toString());
...
Although almost all web sites still place Jquery and other javascript on header :D , even check stackoverflow.com .
I also suggest you to put on before end tag of body. You can check loading time after placing on either places. Script tag will pause your webpage to load further.
and after placing javascript on footer, you may get unusual looks of your webpage until it loads javascript, so place css on your header section.
you need to forward declare the name of the class if you don't want a header:
class ClassTwo;
Important: This only works in some cases, see Als's answer for more information..
Just use;
$('#selectedDueDate').val(dateText).trigger('input');
If one or both of the files you wish to compare isn't in an Eclipse project:
Open the Quick Access search box
Type compare and select Compare With Other Resource
Select the files to compare ? OK
You can also create a keyboard shortcut for Compare With Other Resource by going to Window ? Preferences ? General ? Keys
I Using below simple way to create a project 1- First in a directory that desire to make it project, create a .project file with below contents:
<projectDescription>
<name>Project-Name</name>
<comment></comment>
<projects>
</projects>
<buildSpec>
</buildSpec>
<natures>
</natures>
</projectDescription>
2- Now instead of "Project-Name", write your project name, maybe current directory name
3- Now save this file to directory that desire to make that directory as project with name ".project" ( for save like this, use Notepad )
4- Now go to Eclips and open project and add your files to it.
I would use:
awk 'FNR <= 1' file_*.txt
As @Kusalananda points out there are many ways to capture the first line in command line but using the head -n 1
may not be the best option when using wildcards since it will print additional info. Changing 'FNR == i'
to 'FNR <= i'
allows to obtain the first i lines.
For example, if you have n files named file_1.txt, ... file_n.txt:
awk 'FNR <= 1' file_*.txt
hello
...
bye
But with head
wildcards print the name of the file:
head -1 file_*.txt
==> file_1.csv <==
hello
...
==> file_n.csv <==
bye
I would prefer to not use ts-node and always run from dist folder.
To do that, just setup your package.json with default config:
....
"main": "dist/server.js",
"scripts": {
"build": "tsc",
"prestart": "npm run build",
"start": "node .",
"dev": "nodemon"
},
....
and then add nodemon.json config file:
{
"watch": ["src"],
"ext": "ts",
"ignore": ["src/**/*.spec.ts"],
"exec": "npm restart"
}
Here, i use "exec": "npm restart"
so all ts file will re-compile to js file and then restart the server.
To run while in dev environment,
npm run dev
Using this setup I will always run from the distributed files and no need for ts-node.
I do recomend doing it in 2 filles (.h .cpp)
But if u lazy just add inline
before the function
So it will look something like this
inline void functionX()
{ }
more about inline functions:
The inline functions are a C++ enhancement feature to increase the execution time of a program. Functions can be instructed to compiler to make them inline so that compiler can replace those function definition wherever those are being called. Compiler replaces the definition of inline functions at compile time instead of referring function definition at runtime. NOTE- This is just a suggestion to compiler to make the function inline, if function is big (in term of executable instruction etc) then, compiler can ignore the “inline” request and treat the function as normal function.
more info here
Save yourself some pain...
using System.Linq;
int[] ints = new [] { 10, 20, 10, 34, 113 };
List<int> lst = ints.OfType<int>().ToList(); // this isn't going to be fast.
Can also just...
List<int> lst = new List<int> { 10, 20, 10, 34, 113 };
or...
List<int> lst = new List<int>();
lst.Add(10);
lst.Add(20);
lst.Add(10);
lst.Add(34);
lst.Add(113);
or...
List<int> lst = new List<int>(new int[] { 10, 20, 10, 34, 113 });
or...
var lst = new List<int>();
lst.AddRange(new int[] { 10, 20, 10, 34, 113 });
Trident provides the ::-ms-check
pseudo-element for checkbox and radio button controls. For example:
<input type="checkbox">
<input type="radio">
::-ms-check {
color: red;
background: black;
padding: 1em;
}
This displays as follows in IE10 on Windows 8:
curl -H "Access-Control-Request-Method: GET" -H "Origin: http://localhost" --head http://www.example.com/
Access-Control-Allow-*
then your resource supports CORS.Rationale for alternative answer
I google this question every now and then and the accepted answer is never what I need. First it prints response body which is a lot of text. Adding --head
outputs only headers. Second when testing S3 URLs we need to provide additional header -H "Access-Control-Request-Method: GET"
.
Hope this will save time.
This is like default hint color, worked for me:
editText.setHintTextColor(Color.GRAY);
You can simply use the zoom property:
#myContainer{
zoom: 0.5;
-moz-transform: scale(0.5);
}
Where myContainer contains all the elements you're editing. This is supported in all major browsers.
The accepted answer uses the Apache Commons package but this is how I did it using Java's native libraries
Java 11 and up
import java.util.Base64;
public class Base64Encoding {
public static void main(String[] args) {
Base64.Encoder enc = Base64.getEncoder();
Base64.Decoder dec = Base64.getDecoder();
String str = "77+9x6s=";
// encode data using BASE64
String encoded = enc.encodeToString(str.getBytes());
System.out.println("encoded value is \t" + encoded);
// Decode data
String decoded = new String(dec.decode(encoded));
System.out.println("decoded value is \t" + decoded);
System.out.println("original value is \t" + str);
}
}
Java 6 - 10
import java.io.UnsupportedEncodingException;
import javax.xml.bind.DatatypeConverter;
public class EncodeString64 {
public static void main(String[] args) throws UnsupportedEncodingException {
String str = "77+9x6s=";
// encode data using BASE64
String encoded = DatatypeConverter.printBase64Binary(str.getBytes());
System.out.println("encoded value is \t" + encoded);
// Decode data
String decoded = new String(DatatypeConverter.parseBase64Binary(encoded));
System.out.println("decoded value is \t" + decoded);
System.out.println("original value is \t" + str);
}
}
The better way would be to try/catch
the encoding/decoding steps but hopefully you get the idea.
Great Answer Lain!
There were a couple things I did to make this work in a broader set of devices. At the end I will list the clients I tested on.
I added a new build constructor that did not contain the parameter attachments and did not use MimeMultipart("mixed"). There is no need for mixed if you are sending only inline images.
public Multipart build(String messageText, String messageHtml, List<URL> messageHtmlInline) throws MessagingException {
final Multipart mpAlternative = new MimeMultipart("alternative");
{
// Note: MUST RENDER HTML LAST otherwise iPad mail client only renders
// the last image and no email
addTextVersion(mpAlternative,messageText);
addHtmlVersion(mpAlternative,messageHtml, messageHtmlInline);
}
return mpAlternative;
}
In addTextVersion method I added charset when adding content this probably could/should be passed in, but I just added it statically.
textPart.setContent(messageText, "text/plain");
to
textPart.setContent(messageText, "text/plain; charset=UTF-8");
The last item was adding to the addImagesInline method. I added setting the image filename to the header by the following code. If you don't do this then at least on Android default mail client it will have inline images that have a name of Unknown and will not automatically download them and present in email.
for (URL img : embeded) {
final MimeBodyPart htmlPartImg = new MimeBodyPart();
DataSource htmlPartImgDs = new URLDataSource(img);
htmlPartImg.setDataHandler(new DataHandler(htmlPartImgDs));
String fileName = img.getFile();
fileName = getFileName(fileName);
String newFileName = cids.get(fileName);
boolean imageNotReferencedInHtml = newFileName == null;
if (imageNotReferencedInHtml) continue;
htmlPartImg.setHeader("Content-ID", "<"+newFileName+">");
htmlPartImg.setDisposition(BodyPart.INLINE);
**htmlPartImg.setFileName(newFileName);**
parent.addBodyPart(htmlPartImg);
}
So finally, this is the list of clients I tested on. Outlook 2010, Outlook Web App, Internet Explorer 11, Firefox, Chrome, Outlook using Apple’s native app, Email going through Gmail - Browser mail client, Internet Explorer 11, Firefox, Chrome, Android default mail client, osx IPhone default mail client, Gmail mail client on Android, Gmail mail client on IPhone, Email going through Yahoo - Browser mail client, Internet Explorer 11, Firefox, Chrome, Android default mail client, osx IPhone default mail client.
Hope that helps anyone else.
Try this in your code:
import Foo from './Foo';
import Bar from './Bar';
// without default
export {
Foo,
Bar,
}
Btw, you can also do it this way:
// bundle.js
export { default as Foo } from './Foo'
export { default as Bar } from './Bar'
export { default } from './Baz'
// and import somewhere..
import Baz, { Foo, Bar } from './bundle'
Using export
export const MyFunction = () => {}
export const MyFunction2 = () => {}
const Var = 1;
const Var2 = 2;
export {
Var,
Var2,
}
// Then import it this way
import {
MyFunction,
MyFunction2,
Var,
Var2,
} from './foo-bar-baz';
The difference with export default
is that you can export something, and apply the name where you import it:
// export default
export default class UserClass {
constructor() {}
};
// import it
import User from './user'
There are two ways to do that (Python 2.6+):
class Klass(object):
@staticmethod
def static_method():
print "Hello World"
Klass.static_method()
your module file, called klass.py
def static_method():
print "Hello World"
your code:
import klass
klass.static_method()
PHP runs on the server-side thus you have to use a client-side technology which is capable of showing popup windows: JavaScript.
So you should output a specific JS block via PHP if your form contains errors and you want to show that popup.
I have just cooked up another solution for this, where it's not longer necessary to use a -much to high- max-height value. It needs a few lines of javascript code to calculate the inner height of the collapsed DIV but after that, it's all CSS.
1) Fetching and setting height
Fetch the inner height of the collapsed element (using scrollHeight
). My element has a class .section__accordeon__content
and I actually run this in a forEach()
loop to set the height for all panels, but you get the idea.
document.querySelectorAll( '.section__accordeon__content' ).style.cssText = "--accordeon-height: " + accordeonPanel.scrollHeight + "px";
2) Use the CSS variable to expand the active item
Next, use the CSS variable to set the max-height
value when the item has an .active
class.
.section__accordeon__content.active {
max-height: var(--accordeon-height);
}
Final example
So the full example goes like this: first loop through all accordeon panels and store their scrollHeight
values as CSS variables. Next use the CSS variable as the max-height
value on the active/expanded/open state of the element.
Javascript:
document.querySelectorAll( '.section__accordeon__content' ).forEach(
function( accordeonPanel ) {
accordeonPanel.style.cssText = "--accordeon-height: " + accordeonPanel.scrollHeight + "px";
}
);
CSS:
.section__accordeon__content {
max-height: 0px;
overflow: hidden;
transition: all 425ms cubic-bezier(0.465, 0.183, 0.153, 0.946);
}
.section__accordeon__content.active {
max-height: var(--accordeon-height);
}
And there you have it. A adaptive max-height animation using only CSS and a few lines of JavaScript code (no jQuery required).
Hope this helps someone in the future (or my future self for reference).
You need to add a name
attribute to your dropdown list, then you need to add a required
attribute, and then you can reference the error using myForm.[input name].$error.required
:
HTML:
<form name="myForm" ng-controller="Ctrl" ng-submit="save(myForm)" novalidate>
<input type="text" name="txtServiceName" ng-model="ServiceName" required>
<span ng-show="myForm.txtServiceName.$error.required">Enter Service Name</span>
<br/>
<select name="service_id" class="Sitedropdown" style="width: 220px;"
ng-model="ServiceID"
ng-options="service.ServiceID as service.ServiceName for service in services"
required>
<option value="">Select Service</option>
</select>
<span ng-show="myForm.service_id.$error.required">Select service</span>
</form>
Controller:
function Ctrl($scope) {
$scope.services = [
{ServiceID: 1, ServiceName: 'Service1'},
{ServiceID: 2, ServiceName: 'Service2'},
{ServiceID: 3, ServiceName: 'Service3'}
];
$scope.save = function(myForm) {
console.log('Selected Value: '+ myForm.service_id.$modelValue);
alert('Data Saved! without validate');
};
}
Here's a working plunker.
These files are from Maven wrapper. It works similarly to the Gradle wrapper.
This allows you to run the Maven project without having Maven installed and present on the path. It downloads the correct Maven version if it's not found (as far as I know by default in your user home directory).
The mvnw
file is for Linux (bash) and the mvnw.cmd
is for the Windows environment.
To create or update all necessary Maven Wrapper files execute the following command:
mvn -N io.takari:maven:wrapper
To use a different version of maven you can specify the version as follows:
mvn -N io.takari:maven:wrapper -Dmaven=3.3.3
Both commands require maven on PATH
(add the path to maven bin
to Path
on System Variables) if you already have mvnw in your project you can use ./mvnw
instead of mvn
in the commands.
You can make SQL server to select last N rows using this SQL:
select * from tbl_name order by id desc limit N;
plt.hist(hmag, 30, range=[6.5, 12.5], facecolor='gray', align='mid')
I think if you need to develop something quick with no Strange things in the middle, and you need the facility to have entities representing your tables:
Linq2Sql can be a good allied, using it with LinQ unleashes a great developing timing.
That's the more precise answer and worked for me!!!! ! A cleaner way of undoing the damage is to revert your whole /mysql/data/ folder. Windows has built-in folder versioning — right click on /mysql/data/ and select Restore previous versions. You can then delete the current contents of the folder and replace it with the older version's contents. as mentioned above by Ryan Williams.
I have been using this protocol / extension in one of my apps, and it's a little more readable. I like how it recognizes backspaces and explicitly tells you when a character is a backspace.
Some things to consider:
1.Whatever implements this protocol extension needs to specify a character limit. That's typically going to be your ViewController, but you could implement character limit as a computed property and return something else, for example a character limit on one of your models.
2. You will need to call this method inside of your text field's shouldChangeCharactersInRange delegate method. Otherwise you won't be able to block text entry by returning false, etc.
3. You will probably want to allow backspace characters through. That's why I added the extra function to detect backspaces. Your shouldChangeCharacters method can check for this and return 'true' early on so you always allow backspaces.
protocol TextEntryCharacterLimited{
var characterLimit:Int { get }
}
extension TextEntryCharacterLimited{
func charactersInTextField(textField:UITextField, willNotExceedCharacterLimitWithReplacementString string:String, range:NSRange) -> Bool{
let startingLength = textField.text?.characters.count ?? 0
let lengthToAdd = string.characters.count
let lengthToReplace = range.length
let newLength = startingLength + lengthToAdd - lengthToReplace
return newLength <= characterLimit
}
func stringIsBackspaceWith(string:String, inRange range:NSRange) -> Bool{
if range.length == 1 && string.characters.count == 0 { return true }
return false
}
}
If any of you are interested, I have a Github repo where I've taken some of this character limit behavior and put into an iOS framework. There's a protocol you can implement to get a Twitter-like character limit display that shows you how far you've gone above the character limit.
You can just ask for cancellation but not really terminate it. See this answer.
I found a simple way to auto-detect file encodings - change the file to a text file (on a mac rename the file extension to .txt) and drag it to a Mozilla Firefox window (or File -> Open). Firefox will detect the encoding - you can see what it came up with under View -> Character Encoding.
I changed my file's encoding using TextMate once I knew the correct encoding. File -> Reopen using encoding and choose your encoding. Then File -> Save As and change the encoding to UTF-8 and line endings to LF (or whatever you want)
There is now (as of v1.10.7) a fourth way to instantiate mocks, which is using a JUnit4 rule called MockitoRule.
@RunWith(JUnit4.class) // or a different runner of your choice
public class YourTest
@Rule public MockitoRule rule = MockitoJUnit.rule();
@Mock public YourMock yourMock;
@Test public void yourTestMethod() { /* ... */ }
}
JUnit looks for subclasses of TestRule annotated with @Rule, and uses them to wrap the test Statements that the Runner provides. The upshot of this is that you can extract @Before methods, @After methods, and even try...catch wrappers into rules. You can even interact with these from within your test, the way that ExpectedException does.
MockitoRule behaves almost exactly like MockitoJUnitRunner, except that you can use any other runner, such as Parameterized (which allows your test constructors to take arguments so your tests can be run multiple times), or Robolectric's test runner (so its classloader can provide Java replacements for Android native classes). This makes it strictly more flexible to use in recent JUnit and Mockito versions.
In summary:
Mockito.mock()
: Direct invocation with no annotation support or usage validation.MockitoAnnotations.initMocks(this)
: Annotation support, no usage validation.MockitoJUnitRunner
: Annotation support and usage validation, but you must use that runner.MockitoRule
: Annotation support and usage validation with any JUnit runner.See also: How JUnit @Rule works?
I think most of these points have missed the basic fact that Thrift is an RPC framework, which happens to have the ability to serialize data using a variety of methods (binary, XML, etc).
Protocol Buffers are designed purely for serialization, it's not a framework like Thrift.
Or simply use the JFreechart library - http://www.jfree.org/jfreechart/ .
Instead of only using the path to your script in the task scheduler, you should start PowerShell with your script in the task scheduler, e.g.
C:\WINDOWS\system32\WindowsPowerShell\v1.0\powershell.exe -NoLogo -NonInteractive -File "C:\Path\To\Your\PS1File.ps1"
See powershell /?
for an explanation of those switches.
If you still get problems you should read this question.
I switch between zsh and bash somewhat frequently. For a while, I used to have to source my bash_profile every switch. Then I found out you can (typically) do
exec bash --login
or just
exec bash -l
There is no builtin conversion from a hexadecimal string to a UIColor
(or CGColor
) that I'm aware of. However, you can easily write a couple of functions for this purpose - for example, see iphone development accessing uicolor components
This may happen when two beans have same names.
Module1Beans.java
:
@Configuration
public class Module1Beans {
@Bean
public GoogleAPI retrofitService(){
Retrofit retrofit = new Retrofit.Builder()
.baseUrl("https://www.google.com/")
.addConverterFactory(JacksonConverterFactory.create())
.build();
return retrofit.create(GoogleAPI.class);
}
}
Module2Beans.java
:
@Configuration
public class Module2Beans {
@Bean
public GithubAPI retrofitService(){
Retrofit retrofit = new Retrofit.Builder()
.baseUrl("https://www.github.com/")
.addConverterFactory(JacksonConverterFactory.create())
.build();
return retrofit.create(GithubAPI.class);
}
}
A bean named retrofitService
is first created, and it's type is GoogleAPI
, then covered by a GithubAPI
becauce they're both created by a retrofitService()
method.
Now when you @Autowired
a GoogleAPI
you'll get a message like Field googleAPI in com.example.GoogleService required a bean of type 'com.example.rest.GoogleAPI' that could not be found.
If all you want is calling ravel
on your (nested, I s'pose?) list, you can do that directly, numpy
will do the casting for you:
L = [[1,None,3],["The", "quick", object]]
np.ravel(L)
# array([1, None, 3, 'The', 'quick', <class 'object'>], dtype=object)
Also worth mentioning that you needn't go through numpy
at all.
Of course there is. Check out mysql_query
, and mysql_fetch_row
if you use MySQL.
Example from PHP manual:
<?php
$result = mysql_query("SELECT id,email FROM people WHERE id = '42'");
if (!$result) {
echo 'Could not run query: ' . mysql_error();
exit;
}
$row = mysql_fetch_row($result);
echo $row[0]; // 42
echo $row[1]; // the email value
?>
I would suggest to remove the rows from the underlying DataTable, or if you don't need the datatable anymore, set the datasource to null.
You can try this...
<!--First Solution-->_x000D_
width: calc(100% - 100px);_x000D_
<!--Second Solution-->_x000D_
width: calc(100vh - 100px);
_x000D_
vw: viewport width
vh: viewport height
In laravel 5.3
I want to show the get param in my view
Step 1 : my route
Route::get('my_route/{myvalue}', 'myController@myfunction');
Step 2 : Write a function inside your controller
public function myfunction($myvalue)
{
return view('get')->with('myvalue', $myvalue);
}
Now you're returning the parameter that you passed to the view
Step 3 : Showing it in my View
Inside my view you i can simply echo it by using
{{ $myvalue }}
So If you have this in your url
http://127.0.0.1/yourproject/refral/[email protected]
Then it will print [email protected] in you view file
hope this helps someone.
I worked the same problem for showing multiple markers in Kotlin using a fragment
first declare a list of markers
private lateinit var markers: MutableList<Marker>
initialize this in the oncreate method of the frament
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
//initialize markers list
markers = mutableListOf()
return inflater.inflate(R.layout.fragment_driver_map, container, false)
}
on the OnMapReadyCallback add the markers to the markers list
private val callback = OnMapReadyCallback { googleMap ->
map = googleMap
markers.add(
map.addMarker(
MarkerOptions().position(riderLatLng)
.title("Driver")
.snippet("Driver")
.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_RED))))
markers.add(
map.addMarker(
MarkerOptions().position(driverLatLng)
.title("Driver")
.snippet("Driver")
.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_GREEN))))
Still on the callback
//create builder
val builder = LatLngBounds.builder()
//loop through the markers list
for (marker in markers) {
builder.include(marker.position)
}
//create a bound
val bounds = builder.build()
//set a 200 pixels padding from the edge of the screen
val cu = CameraUpdateFactory.newLatLngBounds(bounds,200)
//move and animate the camera
map.moveCamera(cu)
//animate camera by providing zoom and duration args, callBack set to null
map.animateCamera(CameraUpdateFactory.zoomTo(10f), 2000, null)
Merry coding guys
This sub will populate a Collection with all files matching the filename or pattern you pass in.
Sub GetFiles(StartFolder As String, Pattern As String, _
DoSubfolders As Boolean, ByRef colFiles As Collection)
Dim f As String, sf As String, subF As New Collection, s
If Right(StartFolder, 1) <> "\" Then StartFolder = StartFolder & "\"
f = Dir(StartFolder & Pattern)
Do While Len(f) > 0
colFiles.Add StartFolder & f
f = Dir()
Loop
If DoSubfolders then
sf = Dir(StartFolder, vbDirectory)
Do While Len(sf) > 0
If sf <> "." And sf <> ".." Then
If (GetAttr(StartFolder & sf) And vbDirectory) <> 0 Then
subF.Add StartFolder & sf
End If
End If
sf = Dir()
Loop
For Each s In subF
GetFiles CStr(s), Pattern, True, colFiles
Next s
End If
End Sub
Usage:
Dim colFiles As New Collection
GetFiles "C:\Users\Marek\Desktop\Makro\", FName & ".xls", True, colFiles
If colFiles.Count > 0 Then
'work with found files
End If
Use this method for validating your email format. Pass email as string , it returns true if format is correct otherwise false.
/**
* validate your email address format. [email protected]
*/
public boolean emailValidator(String email)
{
Pattern pattern;
Matcher matcher;
final String EMAIL_PATTERN = "^[_A-Za-z0-9-]+(\\.[_A-Za-z0-9-]+)*@[A-Za-z0-9]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$";
pattern = Pattern.compile(EMAIL_PATTERN);
matcher = pattern.matcher(email);
return matcher.matches();
}
How about this :
I used CustomViewPager
and next, override scrollTo method
I checked the movement when doing a lot of small swipes, it doesn't scroll to other pages.
public class CustomViewPager extends ViewPager {
private boolean enabled;
public CustomViewPager(Context context, AttributeSet attrs) {
super(context, attrs);
this.enabled = true;
}
@Override
public boolean onTouchEvent(MotionEvent event) {
if (this.enabled) {
return super.onTouchEvent(event);
}
return false;
}
@Override
public boolean onInterceptTouchEvent(MotionEvent event) {
if (this.enabled) {
return super.onInterceptTouchEvent(event);
}
return false;
}
public void setPagingEnabled(boolean enabled) {
this.enabled = enabled;
}
@Override
public void scrollTo(int x, int y) {
if(enabled) {
super.scrollTo(x, y);
}
}
}
You can use method named compareTo
, x.compareTo(y)
. It will return 0 if x and y are equal, 1 if x is greater than y and -1 if x is smaller than y
You can't put a CLOB in the WHERE clause. From the documentation:
Large objects (LOBs) are not supported in comparison conditions. However, you can use PL/SQL programs for comparisons on CLOB data.
If your values are always less than 4k, you can use:
UPDATE IMS_TEST
SET TEST_Category = 'just testing'
WHERE to_char(TEST_SCRIPT) = 'something'
AND ID = '10000239';
It is strange to search by a CLOB anyways.. could you not just search by the ID column?
self
is an object reference to the object itself, therefore, they are same.
Python methods are not called in the context of the object itself.
self
in Python may be used to deal with custom object models or something.
Try running mysqld --help --verbose | grep my.cnf | tr " " "\n"
Output will be something like
/etc/my.cnf
/etc/mysql/my.cnf
/usr/local/etc/my.cnf
~/.my.cnf
I am using below solution for IIS hosting in ASP.NET compatibility mode. Credits to Rodney Viana's MSDN blog.
Add following to your web.config under appSettings:
<add key="LogPath" value="C:\\logpath" />
<add key="LogRequestResponse" value="true" />
Replace your global.asax.cs with below (also fix namespace name):
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.SessionState;
using System.Text;
using System.IO;
using System.Configuration;
namespace Yournamespace
{
public class Global : System.Web.HttpApplication
{
protected static bool LogFlag;
protected static string fileNameBase;
protected static string ext = "log";
// One file name per day
protected string FileName
{
get
{
return String.Format("{0}{1}.{2}", fileNameBase, DateTime.Now.ToString("yyyy-MM-dd"), ext);
}
}
protected void Application_Start(object sender, EventArgs e)
{
LogFlag = bool.Parse(ConfigurationManager.AppSettings["LogRequestResponse"].ToString());
fileNameBase = ConfigurationManager.AppSettings["LogPath"].ToString() + @"\C5API-";
}
protected void Session_Start(object sender, EventArgs e)
{
}
protected void Application_BeginRequest(object sender, EventArgs e)
{
if (LogFlag)
{
// Creates a unique id to match Rquests with Responses
string id = String.Format("Id: {0} Uri: {1}", Guid.NewGuid(), Request.Url);
FilterSaveLog input = new FilterSaveLog(HttpContext.Current, Request.Filter, FileName, id);
Request.Filter = input;
input.SetFilter(false);
FilterSaveLog output = new FilterSaveLog(HttpContext.Current, Response.Filter, FileName, id);
output.SetFilter(true);
Response.Filter = output;
}
}
protected void Application_AuthenticateRequest(object sender, EventArgs e)
{
}
protected void Application_Error(object sender, EventArgs e)
{
}
protected void Session_End(object sender, EventArgs e)
{
}
protected void Application_End(object sender, EventArgs e)
{
}
}
class FilterSaveLog : Stream
{
protected static string fileNameGlobal = null;
protected string fileName = null;
protected static object writeLock = null;
protected Stream sinkStream;
protected bool inDisk;
protected bool isClosed;
protected string id;
protected bool isResponse;
protected HttpContext context;
public FilterSaveLog(HttpContext Context, Stream Sink, string FileName, string Id)
{
// One lock per file name
if (String.IsNullOrWhiteSpace(fileNameGlobal) || fileNameGlobal.ToUpper() != fileNameGlobal.ToUpper())
{
fileNameGlobal = FileName;
writeLock = new object();
}
context = Context;
fileName = FileName;
id = Id;
sinkStream = Sink;
inDisk = false;
isClosed = false;
}
public void SetFilter(bool IsResponse)
{
isResponse = IsResponse;
id = (isResponse ? "Reponse " : "Request ") + id;
//
// For Request only read the incoming stream and log it as it will not be "filtered" for a WCF request
//
if (!IsResponse)
{
AppendToFile(String.Format("at {0} --------------------------------------------", DateTime.Now));
AppendToFile(id);
if (context.Request.InputStream.Length > 0)
{
context.Request.InputStream.Position = 0;
byte[] rawBytes = new byte[context.Request.InputStream.Length];
context.Request.InputStream.Read(rawBytes, 0, rawBytes.Length);
context.Request.InputStream.Position = 0;
AppendToFile(rawBytes);
}
else
{
AppendToFile("(no body)");
}
}
}
public void AppendToFile(string Text)
{
byte[] strArray = Encoding.UTF8.GetBytes(Text);
AppendToFile(strArray);
}
public void AppendToFile(byte[] RawBytes)
{
bool myLock = System.Threading.Monitor.TryEnter(writeLock, 100);
if (myLock)
{
try
{
using (FileStream stream = new FileStream(fileName, FileMode.OpenOrCreate, FileAccess.ReadWrite))
{
stream.Position = stream.Length;
stream.Write(RawBytes, 0, RawBytes.Length);
stream.WriteByte(13);
stream.WriteByte(10);
}
}
catch (Exception ex)
{
string str = string.Format("Unable to create log. Type: {0} Message: {1}\nStack:{2}", ex, ex.Message, ex.StackTrace);
System.Diagnostics.Debug.WriteLine(str);
System.Diagnostics.Debug.Flush();
}
finally
{
System.Threading.Monitor.Exit(writeLock);
}
}
}
public override bool CanRead
{
get { return sinkStream.CanRead; }
}
public override bool CanSeek
{
get { return sinkStream.CanSeek; }
}
public override bool CanWrite
{
get { return sinkStream.CanWrite; }
}
public override long Length
{
get
{
return sinkStream.Length;
}
}
public override long Position
{
get { return sinkStream.Position; }
set { sinkStream.Position = value; }
}
//
// For WCF this code will never be reached
//
public override int Read(byte[] buffer, int offset, int count)
{
int c = sinkStream.Read(buffer, offset, count);
return c;
}
public override long Seek(long offset, System.IO.SeekOrigin direction)
{
return sinkStream.Seek(offset, direction);
}
public override void SetLength(long length)
{
sinkStream.SetLength(length);
}
public override void Close()
{
sinkStream.Close();
isClosed = true;
}
public override void Flush()
{
sinkStream.Flush();
}
// For streamed responses (i.e. not buffered) there will be more than one Response (but the id will match the Request)
public override void Write(byte[] buffer, int offset, int count)
{
sinkStream.Write(buffer, offset, count);
AppendToFile(String.Format("at {0} --------------------------------------------", DateTime.Now));
AppendToFile(id);
AppendToFile(buffer);
}
}
}
It should create log file in the folder LogPath with request and response XML.
If the default value for a given type is an acceptable result:
if (v1.HasValue)
v2 = v1.GetValueOrDefault();
If you want a different default value when the result is undefined:
v2 = v1.GetValueOrDefault(255); // or any valid value for int in place of 255
If you just want the value returned (no matter if the method failed or not):
v2 = v1.GetValueOrDefault();
.NET 4.7.2.: GetValueOrDefault()
returns the field value without any checking.
if the last element type is article too, last-of-type
will not work as expected.
maybe i not really understand how it work.
In other words...
IDE Even your notepad is an IDE. Every software you write/compile code with is an IDE.
Library A bunch of code which simplifies functions/methods for quick use.
API A programming interface for functions/configuration which you work with, its usage is often documented.
SDK Extras and/or for development/testing purposes.
ToolKit Tiny apps for quick use, often GUIs.
GUI Apps with a graphical interface, requires no knowledge of programming unlike APIs.
Framework Bunch of APIs/huge Library/Snippets wrapped in a namespace/or encapsulated from outer scope for compact handling without conflicts with other code.
MVC
A design pattern separated in Models, Views and Controllers for huge applications. They are not dependent on each other and can be changed/improved/replaced without to take care of other code.
Example:
Car (Model)
The object that is being presented.
Example in IT: A HTML form.
Camera (View)
Something that is able to see the object(car).
Example in IT: Browser that renders a website with the form.
Driver (Controller)
Someone who drives that car.
Example in IT: Functions which handle form data that's being submitted.
Snippets Small codes of only a few lines, may not be even complete but worth for a quick share.
Plug-ins Exclusive functions for specified frameworks/APIs/libraries only.
Add-ons Additional modules or services for specific GUIs.
Just another approach:
string mystr = "hello";
MessageBox.show(mystr.Substring(0, 1));
You can simply update the record with this and get the updated data in response
router.patch('/:id', (req, res, next) => {
const id = req.params.id;
Product.findByIdAndUpdate(id, req.body, {
new: true
},
function(err, model) {
if (!err) {
res.status(201).json({
data: model
});
} else {
res.status(500).json({
message: "not found any relative data"
})
}
});
});
$myVar = $someVar ?? 42;
Is equivalent to :
$myVar = isset($someVar) ? $someVar : 42;
For constants, the behaviour is the same when using a constant that already exists :
define("FOO", "bar");
define("BAR", null);
$MyVar = FOO ?? "42";
$MyVar2 = BAR ?? "42";
echo $MyVar . PHP_EOL; // bar
echo $MyVar2 . PHP_EOL; // 42
However, for constants that don't exist, this is different :
$MyVar3 = IDONTEXIST ?? "42"; // Raises a warning
echo $MyVar3 . PHP_EOL; // IDONTEXIST
Warning: Use of undefined constant IDONTEXIST - assumed 'IDONTEXIST' (this will throw an Error in a future version of PHP)
Php will convert the non-existing constant to a string.
You can use constant("ConstantName")
that returns the value of the constant or null if the constant doesn't exist, but it will still raise a warning. You can prepended the function with the error control operator @
to ignore the warning message :
$myVar = @constant("IDONTEXIST") ?? "42"; // No warning displayed anymore
echo $myVar . PHP_EOL; // 42
copy paste pl sql developer in program files x86 and program files both. if client is installed in other partition/drive then copy pl sql developer to that drive also. and run from pl sql developer folder instead of desktop shortcut.
ultimate solution ! chill
You are most likely looking for the IIS_IUSRS account.
You can just use padding. Like so:
http://jsfiddle.net/davidja/KG8Kv/
HTML
<table>
<tr>
<td>item1</td>
<td>item2</td>
<td>item2</td>
</tr>
</table>
CSS
td {padding:10px 25px 10px 25px;}
OR
tr td:first-child {padding-left:0px;}
td {padding:10px 0px 10px 50px;}
at -l
to list jobs, which gives return like this:
age2%> at -l
11 2014-10-21 10:11 a hoppent
10 2014-10-19 13:28 a hoppent
atrm 10
kills job 10
Or so my sysadmin told me, and it
apt-get install php7.3-mbstring
solved the issue on ubuntu, php version is php-fpm 7.3
let's say our main thread starts the threads t1 and t2. Now, when t1.join() is called, the main thread suspends itself till thread t1 dies and then resumes itself. Similarly, when t2.join() executes, the main thread suspends itself again till the thread t2 dies and then resumes.
So, this is how it works.
Also, the while loop was not really needed here.
Unfortunately you're probably done with the animation and presentation already. In the hopes this answer can help future questioners, however, this blog post has a walkthrough of steps that can loop a single slide as a sort of sub-presentation.
First, click Slide Show > Set Up Show.
Put a checkmark to Loop continuously until 'Esc'.
Click Ok. Now, Click Slide Show > Custom Shows. Click New.
Select the slide you are looping, click Add. Click Ok and Close.
Click on the slide you are looping. Click Slide Show > Slide Transition. Under Advance slide, put a checkmark to Automatically After. This will allow the slide to loop automatically. Do NOT Apply to all slides.
Right click on the thumbnail of the current slide, select Hide Slide.
Now, you will need to insert a new slide just before the slide you are looping. On the new slide, insert an action button. Set the hyperlink to the custom show you have created. Put a checkmark on "Show and Return"
This has worked for me.
You could create a new List
and addAll()
of your other List
s to it. Then return an unmodifiable list with Collections.unmodifiableList()
.
You can simply use DataColumnCollection.IndexOf
So that you can get the index of the required column by name then use it with your row:
row[dt.Columns.IndexOf("ColumnName")] = columnValue;
type()
is a better solution than isinstance()
, particularly for booleans
:
True
and False
are just keywords that mean 1
and 0
in python. Thus,
isinstance(True, int)
and
isinstance(False, int)
both return True
. Both booleans are an instance of an integer. type()
, however, is more clever:
type(True) == int
returns False
.
Use -A and -B switches (mean lines-after and lines-before):
grep -A 1 -B 1 FAILED file.txt
java.lang.VerifyError
can be the result when you have compiled against a different library than you are using at runtime.
For example, this happened to me when trying to run a program that was compiled against Xerces 1, but Xerces 2 was found on the classpath. The required classes (in org.apache.*
namespace) were found at runtime, so ClassNotFoundException
was not the result. There had been changes to the classes and methods, so that the method signatures found at runtime did not match what was there at compile-time.
Normally, the compiler will flag problems where method signatures do not match. The JVM will verify the bytecode again when the class is loaded, and throws VerifyError
when the bytecode is trying to do something that should not be allowed -- e.g. calling a method that returns String
and then stores that return value in a field that holds a List
.
The variable item
is a string. An index looks like this:
>>> mystring = 'helloworld'
>>> print mystring[0]
'h'
The above example uses the 0
index of the string to refer to the first character.
Strings can't have string indices (like dictionaries can). So this won't work:
>>> mystring = 'helloworld'
>>> print mystring['stringindex']
TypeError: string indices must be integers
Hans and DarkDust answer covered i386/i686 and amd64/x86_64, so there's no sense in revisiting them. This answer will focus on X32, and provide some info learned after a X32 port.
x32 is an ABI for amd64/x86_64 CPUs using 32-bit integers, longs and pointers. The idea is to combine the smaller memory and cache footprint from 32-bit data types with the larger register set of x86_64. (Reference: Debian X32 Port page).
x32 can provide up to about 30% reduction in memory usage and up to about 40% increase in speed. The use cases for the architecture are:
x32 is a somewhat recent addition. It requires kernel support (3.4 and above), distro support (see below), libc support (2.11 or above), and GCC 4.8 and above (improved address size prefix support).
For distros, it was made available in Ubuntu 13.04 or Fedora 17. Kernel support only required pointer to be in the range from 0x00000000 to 0xffffffff. From the System V Application Binary Interface, AMD64 (With LP64 and ILP32 Programming Models), Section 10.4, p. 132 (its the only sentence):
10.4 Kernel Support
Kernel should limit stack and addresses returned from system calls between 0x00000000 to 0xffffffff.
When booting a kernel with the support, you must use syscall.x32=y
option. When building a kernel, you must include the CONFIG_X86_X32=y
option. (Reference: Debian X32 Port page and X32 System V Application Binary Interface).
Here is some of what I have learned through a recent port after the Debian folks reported a few bugs on us after testing:
__x86_64__
(and friends) and __ILP32__
, but not __i386__
/__i686__
(and friends)__ILP32__
alone because it shows up unexpectedly under Clang and Sun Studiopushq
and popq
adcq
If you are looking for a test platform, then you can use Debian 8 or above. Their wiki page at Debian X32 Port has all the information. The 3-second tour: (1) enable X32 in the kernel at boot; (2) use debootstrap
to install the X32 chroot environment, and (3) chroot debian-x32
to enter into the environment and test your software.
In my case I was using jquery on my typescript file:
import * as $ from "jquery";
But this line gives me back an Object $
and it does not allow to use as a function (I can not use $('my-selector')
). It solves my problem this lines, I hope it could help anyone else:
import * as JQuery from "jquery";
const $ = JQuery.default;
Sometimes spacing and Order of parameters in connection string matters (based on personal experience and a long night :S)
So stick to the standard format here
Server=myServerAddress; Port=1234; Database=myDataBase; Uid=myUsername; Pwd=myPassword;
This works in Oracle:
insert into pager (PAG_ID,PAG_PARENT,PAG_NAME,PAG_ACTIVE)
select 8000,0,'Multi 8000',1 from dual
union all select 8001,0,'Multi 8001',1 from dual
The thing to remember here is to use the from dual
statement.
This is for InfluxDB shell version: 1.8.2
Delete works without time field too. As you can see from the series of screen shots:
Note: The tag name has to be in single quotes only. Not double.
Kindly use this one liner:
Sheets.Add(After:=Sheets(Sheets.Count)).Name = "new_sheet_name"
It seems that you have invalid JSON. In that case, that's totally dependent on the data the server sends you which you have not shown. I would suggest running the response through a JSON validator.
Also, System.currentTimeMillies()
changes when you change your systems clock, while System.nanoTime()
doesn't, so the latter is safer to measure durations.
Try this:
mynewlist = [s for s in mylist if s.isdigit()]
From the docs:
str.isdigit()
Return true if all characters in the string are digits and there is at least one character, false otherwise.
For 8-bit strings, this method is locale-dependent.
As noted in the comments, isdigit()
returning True
does not necessarily indicate that the string can be parsed as an int via the int()
function, and it returning False
does not necessarily indicate that it cannot be. Nevertheless, the approach above should work in your case.
Do this:
var left: Node? = null
fun show() {
val left = left
if (left != null) {
queue.add(left) // safe cast succeeds
}
}
Which seems to be the first option provided by the accepted answer, but that's what you're looking for.
The ChildActionOnly
attribute ensures that an action method can be called only as a child method
from within a view. An action method doesn’t need to have this attribute to be used as a child action, but
we tend to use this attribute to prevent the action methods from being invoked as a result of a user
request.
Having defined an action method, we need to create what will be rendered when the action is
invoked. Child actions are typically associated with partial views, although this is not compulsory.
[ChildActionOnly] allowing restricted access via code in View
State Information implementation for specific page URL. Example: Payment Page URL (paying only once) razor syntax allows to call specific actions conditional
SMS Push uses SMS as a carrier, WAP uses download via WAP.
Use formatting:
"%s" % (x)
Example:
x = time.ctime(); str = "%s" % (x); print str
Output: Thu Jan 11 20:40:05 2018
Here is a function to get the IP address using a filter for local and LAN IP addresses:
function get_IP_address()
{
foreach (array('HTTP_CLIENT_IP',
'HTTP_X_FORWARDED_FOR',
'HTTP_X_FORWARDED',
'HTTP_X_CLUSTER_CLIENT_IP',
'HTTP_FORWARDED_FOR',
'HTTP_FORWARDED',
'REMOTE_ADDR') as $key){
if (array_key_exists($key, $_SERVER) === true){
foreach (explode(',', $_SERVER[$key]) as $IPaddress){
$IPaddress = trim($IPaddress); // Just to be safe
if (filter_var($IPaddress,
FILTER_VALIDATE_IP,
FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE)
!== false) {
return $IPaddress;
}
}
}
}
}
Converting String array into stream and mapping to int is the best option available in java 8.
String[] stringArray = new String[] { "0", "1", "2" };
int[] intArray = Stream.of(stringArray).mapToInt(Integer::parseInt).toArray();
System.out.println(Arrays.toString(intArray));
As everybody says, bash doesn't have a proper language-supported try/catch syntax. You can launch bash with the -e
argument or use set -e
inside the script to abort the entire bash process if any command has a non-zero exit code. (You can also set +e
to temporarily allow failing commands.)
So, one technique to simulate a try/catch block is to launch a sub-process to do the work with -e
enabled. Then in the main process, check the return code of the sub-process.
Bash supports heredoc strings, so you don't have to write two separate files to handle this. In the below example, the TRY heredoc will run in a separate bash instance, with -e
enabled, so the sub-process will crash if any command returns a non-zero exit code. Then, back in the main process, we can check the return code to handle a catch block.
#!/bin/bash
set +e
bash -e <<TRY
echo hello
cd /does/not/exist
echo world
TRY
if [ $? -ne 0 ]; then
echo caught exception
fi
It's not a proper language-supported try/catch block, but it may scratch a similar itch for you.
In my case I was modifying the request to append a header (using Fiddler) to an https
request, but I did not configure it to decrypt https traffic. You can export a manually-created certificate from Fiddler, so you can trust/import the certificate by your browsers. See above link for details, some steps include:
It seems to work when I replace the
Runtime.getRuntime().exec("rmiregistry 2020");
by
LocateRegistry.createRegistry(2020);
anyone an idea why? What's the difference?
Alternative and much easier way is to use shapes instead of 9-patches. It is already explained here: https://stackoverflow.com/a/24725831/512011
You can use it without doing anything special. If you have a local image called blah
you can do FROM blah
. If you do FROM blah
in your Dockerfile, but don't have a local image called blah
, then Docker will try to pull it from the registry.
In other words, if a Dockerfile does FROM ubuntu
, but you have a local image called ubuntu
different from the official one, your image will override it.
Slack now supports hyperlinks natively in the message composer using the Link
button or shortcuts:
cmd
+shift
+U
ctrl
+shift
+U
https://slack.com/help/articles/202288908-Format-your-messages-Format-your-messages
My code for the same is as follows;i have used the log10 method:
from math import *
def digit_count(number):
if number>1 and round(log10(number))>=log10(number) and number%10!=0 :
return round(log10(number))
elif number>1 and round(log10(number))<log10(number) and number%10!=0:
return round(log10(number))+1
elif number%10==0 and number!=0:
return int(log10(number)+1)
elif number==1 or number==0:
return 1
I had to specify in case of 1 and 0 because log10(1)=0 and log10(0)=ND and hence the condition mentioned isn't satisfied. However, this code works only for whole numbers.
int intLength(int i) {
int l=0;
for(;i;i/=10) l++;
return l==0 ? 1 : l;
}
Here's a tiny efficient one
Another way...
This is nice if you can't remember the regex or don't care to look it up. But the regex mentioned by others is a nice solution as well.
I agree with kazanaki's answer, and it helped me. I wanted to select the whole entity, so I used
select DISTINCT(c) from Customer c
In my case I have many-to-many relationship, and I want to load entities with collections in one query.
I used LEFT JOIN FETCH and at the end I had to make the result distinct.
To get a timestamp
from Date()
, you'll need to divide getTime()
by 1000
, i.e. :
Date currentDate = new Date();
currentDate.getTime() / 1000;
// 1397132691
or simply:
long unixTime = System.currentTimeMillis() / 1000L;
As I understand Copy-Item -Exclude
then you are doing it correct. What I usually do, get 1'st, and then do after, so what about using Get-Item
as in
Get-Item -Path $copyAdmin -Exclude $exclude |
Copy-Item -Path $copyAdmin -Destination $AdminPath -Recurse -force
The jQuery solution is good, but it will need to either deal with on click events (for mobile or tablet) as hover won't work properly... Could maybe do some window re-size detection?
Andres Ilich's answer seems to work well, but it should be wrapped in a media query:
@media (min-width: 980px) {
.dropdown-menu .sub-menu {
left: 100%;
position: absolute;
top: 0;
visibility: hidden;
margin-top: -1px;
}
.dropdown-menu li:hover .sub-menu {
visibility: visible;
}
.dropdown:hover .dropdown-menu {
display: block;
}
.nav-tabs .dropdown-menu, .nav-pills .dropdown-menu, .navbar .dropdown-menu {
margin-top: 0;
}
.navbar .sub-menu:before {
border-bottom: 7px solid transparent;
border-left: none;
border-right: 7px solid rgba(0, 0, 0, 0.2);
border-top: 7px solid transparent;
left: -7px;
top: 10px;
}
.navbar .sub-menu:after {
border-top: 6px solid transparent;
border-left: none;
border-right: 6px solid #fff;
border-bottom: 6px solid transparent;
left: 10px;
top: 11px;
left: -6px;
}
}
Git has a fairly complete set of traces embedded which you can use to debug your git problems.
To turn them on, you can define the following variables:
GIT_TRACE
for general traces,GIT_TRACE_PACK_ACCESS
for tracing of packfile access,GIT_TRACE_PACKET
for packet-level tracing for network operations,GIT_TRACE_PERFORMANCE
for logging the performance data,GIT_TRACE_SETUP
for information about discovering the repository and environment it’s interacting with,GIT_MERGE_VERBOSITY
for debugging recursive merge strategy (values: 0-5),GIT_CURL_VERBOSE
for logging all curl messages (equivalent to curl -v
),GIT_TRACE_SHALLOW
for debugging fetching/cloning of shallow repositories.Possible values can include:
true
, 1
or 2
to write to stderr,/
to trace output to the specified file.For more details, see: Git Internals - Environment Variables
For SSH issues, try the following commands:
echo 'ssh -vvv "$*"' > ssh && chmod +x ssh
GIT_SSH="$PWD/ssh" git pull origin master
or use ssh
to validate your credentials, e.g.
ssh -vvvT [email protected]
or over HTTPS port:
ssh -vvvT -p 443 [email protected]
Note: Reduce number of -v
to reduce the verbosity level.
$ GIT_TRACE=1 git status
20:11:39.565701 git.c:350 trace: built-in: git 'status'
$ GIT_TRACE_PERFORMANCE=$PWD/gc.log git gc
Counting objects: 143760, done.
...
$ head gc.log
20:12:37.214410 trace.c:420 performance: 0.090286000 s: git command: 'git' 'pack-refs' '--all' '--prune'
20:12:37.378101 trace.c:420 performance: 0.156971000 s: git command: 'git' 'reflog' 'expire' '--all'
...
$ GIT_TRACE_PACKET=true git pull origin master
20:16:53.062183 pkt-line.c:80 packet: fetch< 93eb028c6b2f8b1d694d1173a4ddf32b48e371ce HEAD\0multi_ack thin-pack side-band side-band-64k ofs-delta shallow no-progress include-tag multi_ack_detailed symref=HEAD:refs/heads/master agent=git/2:2.6.5~update-ref-initial-update-1494-g76b680d
...
Use jps to list running java processes. The command returns the process id along with the main class. You can use kill command to kill the process with the returned id or use following one liner script.
kill $(jps | grep <MainClass> | awk '{print $1}')
MainClass is a class in your running java program which contains the main method.
Use the value attribute of the button element to pass the id, as
<button onClick={this.handleRemove} value={id}>Remove</button>
and then in handleRemove, read the value from event as:
handleRemove(event) {
...
remove(event.target.value);
...
}
This way you avoid creating a new function (when compared to using an arrow function) every time this component is re-rendered.
Getters and setters coming from data hiding. Data Hiding means We are hiding data from outsiders or outside person/thing cannot access our data.This is a useful feature in OOP.
As a example:
If you create a public variable, you can access that variable and change value in anywhere(any class). But if you create as private that variable cannot see/access in any class except declared class.
public
andprivate
are access modifiers.
So how can we access that variable outside:
This is the place getters and setters coming from. You can declare variable as private then you can implement getter and setter for that variable.
Example(Java):
private String name;
public String getName(){
return this.name;
}
public void setName(String name){
this.name= name;
}
Advantage:
When anyone want to access or change/set value to balance
variable, he/she must have permision.
//assume we have person1 object
//to give permission to check balance
person1.getName()
//to give permission to set balance
person1.setName()
You can set value in constructor also but when later on when you want to update/change value, you have to implement setter method.
Override the equals method in your class and use Collection#equals() method to check for equality.
function Double round2(Double val) {
return new BigDecimal(val.toString()).setScale(2,RoundingMode.HALF_UP).doubleValue();
}
Note the toString()!!!!
This is because BigDecimal converts the exact binary form of the double!!!
These are the various suggested methods and their fail cases.
// Always Good!
new BigDecimal(val.toString()).setScale(2,RoundingMode.HALF_UP).doubleValue()
Double val = 260.775d; //EXPECTED 260.78
260.77 - WRONG - new BigDecimal(val).setScale(2,RoundingMode.HALF_UP).doubleValue()
Double val = 260.775d; //EXPECTED 260.78
260.77 - TRY AGAIN - Math.round(val * 100.d) / 100.0d
Double val = 256.025d; //EXPECTED 256.03d
256.02 - OOPS - new DecimalFormat("0.00").format(val)
// By default use half even, works if you change mode to half_up
Double val = 256.025d; //EXPECTED 256.03d
256.02 - FAIL - (int)(val * 100 + 0.5) / 100.0;
struct TIME {
static var ti = mach_timebase_info()
static var k: Double = 1
static var mach_stamp: Double {
if ti.denom == 0 {
mach_timebase_info(&ti)
k = Double(ti.numer) / Double(ti.denom) * 1e-6
}
return Double(mach_absolute_time()) * k
}
static var stamp: Double { return NSDate.timeIntervalSinceReferenceDate() * 1000 }
}
do {
let mach_start = TIME.mach_stamp
usleep(200000)
let mach_diff = TIME.mach_stamp - mach_start
let start = TIME.stamp
usleep(200000)
let diff = TIME.stamp - start
print(mach_diff, diff)
}
That's because your hidden fields have duplicate IDs, so jQuery only returns the first in the set. Give them classes instead, like .uid
and grab them via:
var uids = $(".uid").map(function() {
return this.value;
}).get();
Demo: http://jsfiddle.net/karim79/FtcnJ/
EDIT: say your output looks like the following (notice, IDs have changed to classes)
<fieldset><legend>John Smith</legend>
<img src='foo.jpg'/><br>
<a href="#" class="aaf">add as friend</a>
<input name="uid" type="hidden" value='<?php echo $row->uid;?>' class="uid">
</fieldset>
You can target the 'uid' relative to the clicked anchor like this:
$("a.aaf").click(function() {
alert($(this).next('.uid').val());
});
Important: do not have any duplicate IDs. They will cause problems. They are invalid, bad and you should not do it.
It depends what is the character and what encoding it is in:
An ASCII character in 8-bit ASCII encoding is 8 bits (1 byte), though it can fit in 7 bits.
An ISO-8895-1 character in ISO-8859-1 encoding is 8 bits (1 byte).
A Unicode character in UTF-8 encoding is between 8 bits (1 byte) and 32 bits (4 bytes).
A Unicode character in UTF-16 encoding is between 16 (2 bytes) and 32 bits (4 bytes), though most of the common characters take 16 bits. This is the encoding used by Windows internally.
A Unicode character in UTF-32 encoding is always 32 bits (4 bytes).
An ASCII character in UTF-8 is 8 bits (1 byte), and in UTF-16 - 16 bits.
The additional (non-ASCII) characters in ISO-8895-1 (0xA0-0xFF) would take 16 bits in UTF-8 and UTF-16.
That would mean that there are between 0.03125 and 0.125 characters in a bit.
This is working as documented. Any paths specified in PYTHONPATH
are documented as normally coming after the working directory but before the standard interpreter-supplied paths. sys.path.append()
appends to the existing path. See here and here. If you want a particular directory to come first, simply insert it at the head of sys.path:
import sys
sys.path.insert(0,'/path/to/mod_directory')
That said, there are usually better ways to manage imports than either using PYTHONPATH
or manipulating sys.path
directly. See, for example, the answers to this question.
Apart from other answer There are calculator provided by Youtube to check your usage. It is good to identify your usage. https://developers.google.com/youtube/v3/determine_quota_cost
This is a more general solution that allows multiple elements to be watched, and dynamically adding and removing elements from the queue.
It holds a global queue (autoCloseQueue) - an object container for elements that should be closed on outside clicks.
Each queue object key should be the DOM Element id, and the value should be an object with 2 callback functions:
{onPress: someCallbackFunction, onOutsidePress: anotherCallbackFunction}
Put this in your document ready callback:
window.autoCloseQueue = {}
$(document).click(function(event) {
for (id in autoCloseQueue){
var element = autoCloseQueue[id];
if ( ($(e.target).parents('#' + id).length) > 0) { // This is a click on the element (or its child element)
console.log('This is a click on an element (or its child element) with id: ' + id);
if (typeof element.onPress == 'function') element.onPress(event, id);
} else { //This is a click outside the element
console.log('This is a click outside the element with id: ' + id);
if (typeof element.onOutsidePress == 'function') element.onOutsidePress(event, id); //call the outside callback
delete autoCloseQueue[id]; //remove the element from the queue
}
}
});
Then, when the DOM element with id 'menuscontainer' is created, just add this object to the queue:
window.autoCloseQueue['menuscontainer'] = {onOutsidePress: clickOutsideThisElement}
In Oracle, (+) denotes the "optional" table in the JOIN. So in your query,
SELECT a.id, b.id, a.col_2, b.col_2, ...
FROM a,b
WHERE a.id=b.id(+)
it's a LEFT OUTER JOIN of table 'b' to table 'a'. It will return all data of table 'a' without losing its data when the other side (optional table 'b') has no data.
The modern standard syntax for the same query would be
SELECT a.id, b.id, a.col_2, b.col_2, ...
FROM a
LEFT JOIN b ON a.id=b.id
or with a shorthand for a.id=b.id
(not supported by all databases):
SELECT a.id, b.id, a.col_2, b.col_2, ...
FROM a
LEFT JOIN b USING(id)
Older syntax, in both Oracle and other databases:
SELECT a.id, b.id, a.col_2, b.col_2, ...
FROM a,b
WHERE a.id=b.id
More modern syntax:
SELECT a.id, b.id, a.col_2, b.col_2, ...
FROM a
INNER JOIN b ON a.id=b.id
Or simply:
SELECT a.id, b.id, a.col_2, b.col_2, ...
FROM a
JOIN b ON a.id=b.id
It will only return all data where both 'a' & 'b' tables 'id' value is same, means common part.
This is just the same as a LEFT JOIN, but switches which table is optional.
Old Oracle syntax:
SELECT a.id, b.id, a.col_2, b.col_2, ...
FROM a,b
WHERE a.id(+)=b.id
Modern standard syntax:
SELECT a.id, b.id, a.col_2, b.col_2, ...
FROM a
RIGHT JOIN b ON a.id=b.id
https://asktom.oracle.com/pls/asktom/f?p=100:11:::::P11_QUESTION_ID:6585774577187
the position:fixed; property should do the work, I used it on my Website and it worked fine. http://www.w3schools.com/css/css_positioning.asp
All you have to do is add:
#include <string>
using namespace std;
at the top. (BTW I know this was posted in 2013 but I just wanted to answer)
If you plan on getting a random value a lot, you might want to define a function for it.
First, put this in your code somewhere:
Array.prototype.sample = function(){
return this[Math.floor(Math.random()*this.length)];
}
Now:
[1,2,3,4].sample() //=> a random element
Code released into the public domain under the terms of the CC0 1.0 license.
keep it Compact.
Each time you press a key, the function edValueKeyPress()
is called.
You've also declared and initialized some variables in that function - which slow down the process and requires more CPU and memory as well.
You can simply use this code - derived from simple substitution.
function edValueKeyPress()
{
document.getElementById("lblValue").innerText =""+document.getElementById("edValue").value;
}
That's all you want, and it's faster!
try
block should be around open. Not around prompt.
while True:
prompt = input("\n Hello to Sudoku valitator,"
"\n \n Please type in the path to your file and press 'Enter': ")
try:
sudoku = open(prompt, 'r').readlines()
except FileNotFoundError:
print("Wrong file or file path")
else:
break
use mydb
db.createUser( { user: "test", pwd: "secret", roles: [ "readWrite", "dbAdmin"],passwordDigestor:"server" } )
volatile is a field modifier, while synchronized modifies code blocks and methods. So we can specify three variations of a simple accessor using those two keywords:
int i1; int geti1() {return i1;} volatile int i2; int geti2() {return i2;} int i3; synchronized int geti3() {return i3;}
geti1()
accesses the value currently stored ini1
in the current thread. Threads can have local copies of variables, and the data does not have to be the same as the data held in other threads.In particular, another thread may have updatedi1
in it's thread, but the value in the current thread could be different from that updated value. In fact Java has the idea of a "main" memory, and this is the memory that holds the current "correct" value for variables. Threads can have their own copy of data for variables, and the thread copy can be different from the "main" memory. So in fact, it is possible for the "main" memory to have a value of 1 fori1
, for thread1 to have a value of 2 fori1
and for thread2 to have a value of 3 fori1
if thread1 and thread2 have both updated i1 but those updated value has not yet been propagated to "main" memory or other threads.On the other hand,
geti2()
effectively accesses the value ofi2
from "main" memory. A volatile variable is not allowed to have a local copy of a variable that is different from the value currently held in "main" memory. Effectively, a variable declared volatile must have it's data synchronized across all threads, so that whenever you access or update the variable in any thread, all other threads immediately see the same value. Generally volatile variables have a higher access and update overhead than "plain" variables. Generally threads are allowed to have their own copy of data is for better efficiency.There are two differences between volitile and synchronized.
Firstly synchronized obtains and releases locks on monitors which can force only one thread at a time to execute a code block. That's the fairly well known aspect to synchronized. But synchronized also synchronizes memory. In fact synchronized synchronizes the whole of thread memory with "main" memory. So executing
geti3()
does the following:
- The thread acquires the lock on the monitor for object this .
- The thread memory flushes all its variables, i.e. it has all of its variables effectively read from "main" memory .
- The code block is executed (in this case setting the return value to the current value of i3, which may have just been reset from "main" memory).
- (Any changes to variables would normally now be written out to "main" memory, but for geti3() we have no changes.)
- The thread releases the lock on the monitor for object this.
So where volatile only synchronizes the value of one variable between thread memory and "main" memory, synchronized synchronizes the value of all variables between thread memory and "main" memory, and locks and releases a monitor to boot. Clearly synchronized is likely to have more overhead than volatile.
http://javaexp.blogspot.com/2007/12/difference-between-volatile-and.html
If you installed tomcat
manually, run the shutdown.sh(/.../tomcat/bin)
from the terminal to shut it down easily.
To declare different layouts and bitmaps you'd like to use for the different screens, you must place these alternative resources in separate directories/folders.
This means that if you generate a 200x200
image for xhdpi
devices, you should generate the same resource in 150x150
for hdpi
, 100x100
for mdpi
, and 75x75
for ldpi
devices.
Then, place the files in the appropriate drawable resource directory:
MyProject/
res/
drawable-xhdpi/
awesomeimage.png
drawable-hdpi/
awesomeimage.png
drawable-mdpi/
awesomeimage.png
drawable-ldpi/
awesomeimage.png
Any time you reference @drawable/awesomeimage
, the system selects the appropriate bitmap based on the screen's density.
I was going insane trying to get my js files to refresh and I tried everything. Then I did a header check and remembered I was using Cloudflare!
In Cloudflare you can use dev mode to disable proxy.
In Angular 10, you can do something like the following...
import { Component, OnInit } from '@angular/core';
import { Router, NavigationEnd } from '@angular/router';
import { filter } from 'rxjs/operators';
@Component({
selector: 'app-my-class',
templateUrl: './my-class.component.html',
styleUrls: ['./my-class.component.scss']
})
export class MyClassComponent implements OnInit {
constructor(private router: Router) {}
ngOnInit(): void {
this.router.events
.pipe(filter(event => event instanceof NavigationEnd))
.subscribe((event: NavigationEnd) => {
// code goes here...
});
}
}
You could use a bit of workaround by placing a sass file in folder what you would like to import and import all files in that file like this:
file path:main/current/_current.scss
@import "placeholders";
@import "colors";
and in next dir level file you just use import for file what imported all files from that dir:
file path:main/main.scss
@import "EricMeyerResetCSSv20";
@import "clearfix";
@import "current";
That way you have same number of files, like you are importing the whole dir. Beware of order, file that comes last will override the matching stiles.
You just need to bind your event
for ex-
// place this code to your constructor
this._handleDelete = this._handleDelete.bind(this);
// and your setState function will work perfectly
_handleDelete(id){
this.state.list.splice(id, 1);
this.setState({ list: this.state.list });
// this.setState({list: list});
}
You can just forget SQL all together and go with a "NoSQL" approach. RavenDB, MongoDB and CouchDB jump to mind as possible solutions. With a NoSQL approach, you are not using the relational model..you aren't even constrained to schemas.
As you can see in the Java Source of the java.lang.String class:
/**
* Allocates a new <code>String</code> that contains characters from
* a subarray of the character array argument. The <code>offset</code>
* argument is the index of the first character of the subarray and
* the <code>count</code> argument specifies the length of the
* subarray. The contents of the subarray are copied; subsequent
* modification of the character array does not affect the newly
* created string.
*
* @param value array that is the source of characters.
* @param offset the initial offset.
* @param count the length.
* @exception IndexOutOfBoundsException if the <code>offset</code>
* and <code>count</code> arguments index characters outside
* the bounds of the <code>value</code> array.
*/
public String(char value[], int offset, int count) {
if (offset < 0) {
throw new StringIndexOutOfBoundsException(offset);
}
if (count < 0) {
throw new StringIndexOutOfBoundsException(count);
}
// Note: offset or count might be near -1>>>1.
if (offset > value.length - count) {
throw new StringIndexOutOfBoundsException(offset + count);
}
this.value = new char[count];
this.count = count;
System.arraycopy(value, offset, this.value, 0, count);
}
Parameter references are surrounded by <code></code>
tags, which means that the Javadoc syntax does not provide any way to do such a thing. (I think String.class is a good example of javadoc usage).
After all this, I found a new easier method try this ..
It can join multiple photos together:
public static System.Drawing.Bitmap CombineBitmap(string[] files)
{
//read all images into memory
List<System.Drawing.Bitmap> images = new List<System.Drawing.Bitmap>();
System.Drawing.Bitmap finalImage = null;
try
{
int width = 0;
int height = 0;
foreach (string image in files)
{
//create a Bitmap from the file and add it to the list
System.Drawing.Bitmap bitmap = new System.Drawing.Bitmap(image);
//update the size of the final bitmap
width += bitmap.Width;
height = bitmap.Height > height ? bitmap.Height : height;
images.Add(bitmap);
}
//create a bitmap to hold the combined image
finalImage = new System.Drawing.Bitmap(width, height);
//get a graphics object from the image so we can draw on it
using (System.Drawing.Graphics g = System.Drawing.Graphics.FromImage(finalImage))
{
//set background color
g.Clear(System.Drawing.Color.Black);
//go through each image and draw it on the final image
int offset = 0;
foreach (System.Drawing.Bitmap image in images)
{
g.DrawImage(image,
new System.Drawing.Rectangle(offset, 0, image.Width, image.Height));
offset += image.Width;
}
}
return finalImage;
}
catch (Exception ex)
{
if (finalImage != null)
finalImage.Dispose();
throw ex;
}
finally
{
//clean up memory
foreach (System.Drawing.Bitmap image in images)
{
image.Dispose();
}
}
}
I got in trouble at work one time. I was accused of using "magic numbers" in array declarations.
Like this:
int Marylyn[256], Ann[1024];
The company policy was to avoid these magic numbers because, it was explained to me, that these numbers were not portable; that they impeded easy maintenance. I argued that when I am reading the code, I want to know exactly how big the array is. I lost the argument and so, on a Friday afternoon I replaced the offending "magic numbers" with #defines, like this:
#define TWO_FIFTY_SIX 256
#define TEN_TWENTY_FOUR 1024
int Marylyn[TWO_FIFTY_SIX], Ann[TEN_TWENTY_FOUR];
On the following Monday afternoon I was called in and accused of having passive defiant tendencies.
Please make sure that your home partition is mounted with executable permissions. That is the default, but if you happen to mount it without exec option, you will get this error.
I has similar problem in context of Stripe:
Error: Stripe no longer supports API requests made with TLS 1.0. Please initiate HTTPS connections with TLS 1.2 or later. You can learn more about this at https://stripe.com/blog/upgrading-tls.
Forcing TLS 1.2 using CURL parameter is temporary solution or even it can't be applied because of lack of room to place an update. By default TLS test function https://gist.github.com/olivierbellone/9f93efe9bd68de33e9b3a3afbd3835cf showed following configuration:
SSL version: NSS/3.21 Basic ECC
SSL version number: 0
OPENSSL_VERSION_NUMBER: 1000105f
TLS test (default): TLS 1.0
TLS test (TLS_v1): TLS 1.2
TLS test (TLS_v1_2): TLS 1.2
I updated libraries using following command:
yum update nss curl openssl
and then saw this:
SSL version: NSS/3.21 Basic ECC
SSL version number: 0
OPENSSL_VERSION_NUMBER: 1000105f
TLS test (default): TLS 1.2
TLS test (TLS_v1): TLS 1.2
TLS test (TLS_v1_2): TLS 1.2
Please notice that default TLS version changed to 1.2! That globally solved problem. This will help PayPal users too: https://www.paypal.com/au/webapps/mpp/tls-http-upgrade (update before end of June 2017)
Perhaps your subquery (SELECT ename FROM EMP WHERE empno = mgr)
thinks, give me the employee records that are their own managers! (i.e., where the empno of a row is the same as the mgr of the same row.)
have you considered perhaps rewriting this to use an inner (self) join? (I'm asking, becuase i'm not even sure if the following will work or not.)
SELECT t1.ename, t1.empno, t2.ename as MANAGER, t1.mgr
from emp as t1
inner join emp t2 ON t1.mgr = t2.empno
order by t1.empno;
I would recommend using Git Graph extension.
FWIW, htpasswd -n username
will output the result directly to stdout, and avoid touching files altogether.
You could use a CASE statement, like
SELECT name
,address
,CASE WHEN a < b THEN '1'
ELSE '2' END AS one_or_two
FROM ...
Another option is to use VBA in Excel, and write a macro to parse the spreadsheet data and write it into SQL.
One example is here: http://www.ozgrid.com/forum/showthread.php?t=26621&page=1
Sub InsertARecord()
Dim cnt As ADODB.Connection
Dim rst As ADODB.Recordset
Dim stCon As String, stSQL As String
Set cnt = New ADODB.Connection
Set rst = New ADODB.Recordset
stCon = "Provider=MSDASQL.1;Persist Security Info=False;Data Source=JOEY"
cnt.ConnectionString = stCon
stSQL = "INSERT INTO MyTable (Price)"
stSQL = stSQL & "VALUES (500)"
cnt.Open
rst.Open stSQL, cnt, adOpenStatic, adLockReadOnly, adCmdText
If CBool(rst.State And adStateOpen) = True Then rst.Close
Set rst = Nothing
If CBool(cnt.State And adStateOpen) = True Then cnt.Close
Set cnt = Nothing
End Sub
It sounds to me like you want to be able to easily pass a string created using printf-style formatting to the function you already have that takes a simple string. You can create a wrapper function using stdarg.h
facilities and vsnprintf()
(which may not be readily available, depending on your compiler/platform):
#include <stdarg.h>
#include <stdio.h>
// a function that accepts a string:
void foo( char* s);
// You'd like to call a function that takes a format string
// and then calls foo():
void foofmt( char* fmt, ...)
{
char buf[100]; // this should really be sized appropriately
// possibly in response to a call to vsnprintf()
va_list vl;
va_start(vl, fmt);
vsnprintf( buf, sizeof( buf), fmt, vl);
va_end( vl);
foo( buf);
}
int main()
{
int val = 42;
foofmt( "Some value: %d\n", val);
return 0;
}
For platforms that don't provide a good implementation (or any implementation) of the snprintf()
family of routines, I've successfully used a nearly public domain snprintf()
from Holger Weiss.
I have used this with success in Chrome, Firefox, and Safari. Haven't been able to test it in IE yet.
if($(document).scrollTop() !=0){
$('html, body').animate({ scrollTop: 0 }, 'fast');
}
The reason for the "if" statement is to check if the user is all ready at the top of the site. If so, don't do the animation. That way we don't have to worry so much about screen resolution.
The reason I use $(document).scrollTop
instead of ie. $('html,body')
is cause Chrome always return 0 for some reason.
Thanks a ton for Bhaskar Karambelkar's answer which explains in detail and fixed my issue. But also I would like to re phrase the answer in three simple steps for someone who is in a hurry to fix
wsdlLocation= "http://localhost/wsdl/yourwsdlname.wsdl"
Create an xml file jax-ws-catalog.xml under META-INF as below
<catalog xmlns="urn:oasis:names:tc:entity:xmlns:xml:catalog"
prefer="system">
<system systemId="http://localhost/wsdl/yourwsdlname.wsdl" uri="wsdl/yourwsdlname.wsdl" />
</catalog>
Now package your jar. No more reference to the local directory, it's all packaged and referenced within
Why do you pass -c
? That will just show the number of matches. Similarly, there is no reason to use -r
. I suggest you read man grep
.
To grep for 2 words existing on the same line, simply do:
grep "word1" FILE | grep "word2"
grep "word1" FILE
will print all lines that have word1 in them from FILE, and then grep "word2"
will print the lines that have word2 in them. Hence, if you combine these using a pipe, it will show lines containing both word1 and word2.
If you just want a count of how many lines had the 2 words on the same line, do:
grep "word1" FILE | grep -c "word2"
Also, to address your question why does it get stuck : in grep -c "word1"
, you did not specify a file. Therefore, grep
expects input from stdin
, which is why it seems to hang. You can press Ctrl+D to send an EOF (end-of-file) so that it quits.
Assuming you want to list grants on all objects a particular user has received:
select * from all_tab_privs_recd where grantee = 'your user'
This will not return objects owned by the user. If you need those, use all_tab_privs
view instead.
Try remove the backdrop, if you don't realy need it (data-backdrop= "false"):
<div class="modal fade" data-backdrop="false" role="dialog" id="my-modal" aria-labelledby="modal-title">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h3 class="modal-title" id="modal-title">No Backdrop</h3>
</div>
<div class="modal-body">
<p>
Look! No backdrop here!
</p>
</div>
<div class="modal-footer">
<button class="btn btn-default" data-dismiss="modal">Cancel</button>
<button class="btn btn-primary">Ok</button> </div>
</div>
</div>
</div>
Try rewriting your success handler to:
success : handleData
The success property of the ajax method only requires a reference to a function.
In your handleData function you can take up to 3 parameters:
object data
string textStatus
jqXHR jqXHR
To select the sibling, you'd need something like:
$(this).next();
So, Shog9's comment is not correct. First of all, you'd need to name the variable "clicked" outside of the div click function, otherwise, it is lost after the click occurs.
var clicked;
$("div a").click(function(){
clicked = $(this).next();
// Do what you need to do to the newly defined click here
});
// But you can also access the "clicked" element here
A non-zero exit status code, usually indicates abnormal termination. if n != 0
, its up to the programmer to apply a meaning to the various n's.
From https://docs.oracle.com/javase/7/docs/api/java/lang/System.html.
I don't suppose performance matters much here, but I can't resist. The zip() function completely recopies both vectors (more of a matrix transpose, actually) just to get the data in "Pythonic" order. It would be interesting to time the nuts-and-bolts implementation:
import math
def cosine_similarity(v1,v2):
"compute cosine similarity of v1 to v2: (v1 dot v2)/{||v1||*||v2||)"
sumxx, sumxy, sumyy = 0, 0, 0
for i in range(len(v1)):
x = v1[i]; y = v2[i]
sumxx += x*x
sumyy += y*y
sumxy += x*y
return sumxy/math.sqrt(sumxx*sumyy)
v1,v2 = [3, 45, 7, 2], [2, 54, 13, 15]
print(v1, v2, cosine_similarity(v1,v2))
Output: [3, 45, 7, 2] [2, 54, 13, 15] 0.972284251712
That goes through the C-like noise of extracting elements one-at-a-time, but does no bulk array copying and gets everything important done in a single for loop, and uses a single square root.
ETA: Updated print call to be a function. (The original was Python 2.7, not 3.3. The current runs under Python 2.7 with a from __future__ import print_function
statement.) The output is the same, either way.
CPYthon 2.7.3 on 3.0GHz Core 2 Duo:
>>> timeit.timeit("cosine_similarity(v1,v2)",setup="from __main__ import cosine_similarity, v1, v2")
2.4261788514654654
>>> timeit.timeit("cosine_measure(v1,v2)",setup="from __main__ import cosine_measure, v1, v2")
8.794677709375264
So, the unpythonic way is about 3.6 times faster in this case.
To disable inputting password:
sudo visudo
Then add a new line like below and save then:
# The user can run installer as root without inputting password
yourusername ALL=(root) NOPASSWD: /usr/sbin/installer
Then you run installer without password:
sudo installer -pkg ...
As @Graham42 noted, mouse option has changed in version 2.1. Scrolling now requires for you to enter copy mode first. To enable scrolling almost identical to how it was before 2.1 add following to your .tmux.conf
.
set-option -g mouse on
# make scrolling with wheels work
bind -n WheelUpPane if-shell -F -t = "#{mouse_any_flag}" "send-keys -M" "if -Ft= '#{pane_in_mode}' 'send-keys -M' 'select-pane -t=; copy-mode -e; send-keys -M'"
bind -n WheelDownPane select-pane -t= \; send-keys -M
This will enable scrolling on hover over a pane and you will be able to scroll that pane line by line.
Source: https://groups.google.com/d/msg/tmux-users/TRwPgEOVqho/Ck_oth_SDgAJ
To dynamically change the color of a text box goto properties, goto font/Color and set the following expression
=SWITCH(Fields!CurrentRiskLevel.Value = "Low", "Green",
Fields!CurrentRiskLevel.Value = "Moderate", "Blue",
Fields!CurrentRiskLevel.Value = "Medium", "Yellow",
Fields!CurrentRiskLevel.Value = "High", "Orange",
Fields!CurrentRiskLevel.Value = "Very High", "Red"
)
Same way for tolerance
=SWITCH(Fields!Tolerance.Value = "Low", "Red",
Fields!Tolerance.Value = "Moderate", "Orange",
Fields!Tolerance.Value = "Medium", "Yellow",
Fields!Tolerance.Value = "High", "Blue",
Fields!Tolerance.Value = "Very High", "Green")
<?php
// Checks if key exists (doesn't care about it's value).
// @link http://php.net/manual/en/function.array-key-exists.php
if (array_key_exists(20120504, $search_array)) {
echo $search_array[20120504];
}
// Checks against NULL
// @link http://php.net/manual/en/function.isset.php
if (isset($search_array[20120504])) {
echo $search_array[20120504];
}
// No warning or error if key doesn't exist plus checks for emptiness.
// @link http://php.net/manual/en/function.empty.php
if (!empty($search_array[20120504])) {
echo $search_array[20120504];
}
?>
This Worked for me. For getting the latest code from master to my branch
git rebase origin/master
select name from sysibm.systables
where name like '%ISP%'
and type = 'T'
Axtavt answer is correct.
This is how your resolver should look like (annotations based):
@Bean
UrlBasedViewResolver resolver(){
UrlBasedViewResolver resolver = new UrlBasedViewResolver();
resolver.setPrefix("/views/");
resolver.setSuffix(".jsp");
resolver.setViewClass(JstlView.class);
return resolver;
}
Obviously the name of your views directory should change based on your project.
You want to use %p
to print a pointer. From the spec:
p
The argument shall be a pointer tovoid
. The value of the pointer is converted to a sequence of printing characters, in an implementation-defined manner.
And don't forget the cast, e.g.
printf("%p\n",(void*)&a);
A handle is like a primary key value of a record in a database.
edit 1: well, why the downvote, a primary key uniquely identifies a database record, and a handle in the Windows system uniquely identifies a window, an opened file, etc, That's what I'm saying.
To round to the nearest X (without being VBA specific)
N = X * int(N / X + 0.5)
Where int(...) returns the next lowest whole number.
If your available rounding function already rounds to the nearest whole number then omit the addition of 0.5
Maybe what comes from the server is already evaluated as JSON object? For example, using jQuery get method:
$.get('/service', function(data) {
var obj = data;
/*
"obj" is evaluated at this point if server responded
with "application/json" or similar.
*/
for (var i = 0; i < obj.length; i++) {
console.log(obj[i].Name);
}
});
Alternatively, if you need to turn JSON object into JSON string literal, you can use JSON.stringify
:
var json = [{"Id":"10","Name":"Matt"},{"Id":"1","Name":"Rock"}];
var jsonString = JSON.stringify(json);
But in this case I don't understand why you can't just take the json
variable and refer to it instead of stringifying and parsing.
Kotlin Solution:
1) Paste this extension function somewhere.
fun LocalDate.toDate(): Date = Date.from(this.atStartOfDay(ZoneId.systemDefault()).toInstant())
2) Use it, and never google this again.
val myDate = myLocalDate.toDate()
This gives the desired result -
body {
background-image: url("\images\dark-cloud.jpg");
background-size: 100% 100%;
background-attachment: fixed;
opacity: .8;
}
Setting the opacity of the background.
To fully delete the .git
repository in your computer (in Windows 8 and above):
.git
repository is normally hidden in windows .git
repository then you can delete itI'm probably late but this worked for me:
<target name="build" />
You can use The fullscreen API You can see an example here
The fullscreen API provides an easy way for web content to be presented using the user's entire screen. This article provides information about using this API.
Clean the project and build it again
There are two reasons you might get this message:
%FrameworkDir%\%FrameworkVersion%\aspnet_regiis -i
. Read the message carefully. On Windows8/IIS8 it may say that this is no longer supported and you may have to use Turn Windows Features On/Off dialog in Install/Uninstall a Program in Control Panel.Tensorflow isn't available for python 3.8
(as of Dec 4th 2019) according to their documentation page. You will have to downgrade to python 3.7
.
Try This:
table.table tr th{background-color:blue !important; font-color:white !important;}
hope this helps..
this is a simple alternative that gives all responses, Fullname, Path, filename.
Dim FilePath, FileOnly, PathOnly As String
FilePath = ThisWorkbook.FullName
FileOnly = ThisWorkbook.Name
PathOnly = Left(FilePath, Len(FilePath) - Len(FileOnly))
Using unset
To remove an element at particular index, we can use unset
and then do copy to another array. Only just unset
is not required in this case. Because unset
does not remove the element it just sets null string to the particular index in array.
declare -a arr=('aa' 'bb' 'cc' 'dd' 'ee')
unset 'arr[1]'
declare -a arr2=()
i=0
for element in "${arr[@]}"
do
arr2[$i]=$element
((++i))
done
echo "${arr[@]}"
echo "1st val is ${arr[1]}, 2nd val is ${arr[2]}"
echo "${arr2[@]}"
echo "1st val is ${arr2[1]}, 2nd val is ${arr2[2]}"
Output is
aa cc dd ee
1st val is , 2nd val is cc
aa cc dd ee
1st val is cc, 2nd val is dd
Using :<idx>
We can remove some set of elements using :<idx>
also. For example if we want to remove 1st element we can use :1
as mentioned below.
declare -a arr=('aa' 'bb' 'cc' 'dd' 'ee')
arr2=("${arr[@]:1}")
echo "${arr2[@]}"
echo "1st val is ${arr2[1]}, 2nd val is ${arr2[2]}"
Output is
bb cc dd ee
1st val is cc, 2nd val is dd
I've created a tiny utility called super-array where you can access items in an array by a unique identifier with O(1) complexity. Example:
const SuperArray = require('super-array');
const myArray = new SuperArray([
{id: 'ab1', name: 'John'},
{id: 'ab2', name: 'Peter'},
]);
console.log(myArray.get('ab1')); // {id: 'ab1', name: 'John'}
console.log(myArray.get('ab2')); // {id: 'ab2', name: 'Peter'}
To answer the question as asked (without repeating unduly what appears in other answers)
Lexers and parsers are not very different, as suggested by the accepted answer. Both are based on simple language formalisms: regular languages for lexers and, almost always, context-free (CF) languages for parsers. They both are associated with fairly simple computational models, the finite state automaton and the push-down stack automaton. Regular languages are a special case of context-free languages, so that lexers could be produced with the somewhat more complex CF technology. But it is not a good idea for at least two reasons.
A fundamental point in programming is that a system component should be buit with the most appropriate technology, so that it is easy to produce, to understand and to maintain. The technology should not be overkill (using techniques much more complex and costly than needed), nor should it be at the limit of its power, thus requiring technical contortions to achieve the desired goal.
That is why "It seems fashionable to hate regular expressions". Though they can do a lot, they sometimes require very unreadable coding to achieve it, not to mention the fact that various extensions and restrictions in implementation somewhat reduce their theoretical simplicity. Lexers do not usually do that, and are usually a simple, efficient, and appropriate technology to parse token. Using CF parsers for token would be overkill, though it is possible.
Another reason not to use CF formalism for lexers is that it might then be tempting to use the full CF power. But that might raise sructural problems regarding the reading of programs.
Fundamentally, most of the structure of program text, from which meaning is extracted, is a tree structure. It expresses how the parse sentence (program) is generated from syntax rules. Semantics is derived by compositional techniques (homomorphism for the mathematically oriented) from the way syntax rules are composed to build the parse tree. Hence the tree structure is essential. The fact that tokens are identified with a regular set based lexer does not change the situation, because CF composed with regular still gives CF (I am speaking very loosely about regular transducers, that transform a stream of characters into a stream of token).
However, CF composed with CF (via CF transducers ... sorry for the math), does not necessarily give CF, and might makes things more general, but less tractable in practice. So CF is not the appropriate tool for lexers, even though it can be used.
One of the major differences between regular and CF is that regular languages (and transducers) compose very well with almost any formalism in various ways, while CF languages (and transducers) do not, not even with themselves (with a few exceptions).
(Note that regular transducers may have others uses, such as formalization of some syntax error handling techniques.)
BNF is just a specific syntax for presenting CF grammars.
EBNF is a syntactic sugar for BNF, using the facilities of regular notation to give terser version of BNF grammars. It can always be transformed into an equivalent pure BNF.
However, the regular notation is often used in EBNF only to emphasize these parts of the syntax that correspond to the structure of lexical elements, and should be recognized with the lexer, while the rest with be rather presented in straight BNF. But it is not an absolute rule.
To summarize, the simpler structure of token is better analyzed with the simpler technology of regular languages, while the tree oriented structure of the language (of program syntax) is better handled by CF grammars.
I would suggest also looking at AHR's answer.
But this leaves a question open: Why trees?
Trees are a good basis for specifying syntax because
they give a simple structure to the text
there are very convenient for associating semantics with the text on the basis of that structure, with a mathematically well understood technology (compositionality via homomorphisms), as indicated above. It is a fundamental algebraic tool to define the semantics of mathematical formalisms.
Hence it is a good intermediate representation, as shown by the success of Abstract Syntax Trees (AST). Note that AST are often different from parse tree because the parsing technology used by many professionals (Such as LL or LR) applies only to a subset of CF grammars, thus forcing grammatical distorsions which are later corrected in AST. This can be avoided with more general parsing technology (based on dynamic programming) that accepts any CF grammar.
Statement about the fact that programming languages are context-sensitive (CS) rather than CF are arbitrary and disputable.
The problem is that the separation of syntax and semantics is arbitrary. Checking declarations or type agreement may be seen as either part of syntax, or part of semantics. The same would be true of gender and number agreement in natural languages. But there are natural languages where plural agreement depends on the actual semantic meaning of words, so that it does not fit well with syntax.
Many definitions of programming languages in denotational semantics place declarations and type checking in the semantics. So stating as done by Ira Baxter that CF parsers are being hacked to get a context sensitivity required by syntax is at best an arbitrary view of the situation. It may be organized as a hack in some compilers, but it does not have to be.
Also it is not just that CS parsers (in the sense used in other answers here) are hard to build, and less efficient. They are are also inadequate to express perspicuously the kinf of context-sensitivity that might be needed. And they do not naturally produce a syntactic structure (such as parse-trees) that is convenient to derive the semantics of the program, i.e. to generate the compiled code.
Option 2 is correct: The nested <ul>
is a child of the <li>
it belongs in.
If you validate, option 1 comes up as an error in html 5 -- credit: user3272456
<ul>
as child of <li>
The proper way to make HTML nested list is with the nested <ul>
as a child of the <li>
to which it belongs. The nested list should be inside of the <li>
element of the list in which it is nested.
<ul>
<li>Parent/Item
<ul>
<li>Child/Subitem
</li>
</ul>
</li>
</ul>
A list item can contain another entire list — this is known as "nesting" a list. It is useful for things like tables of contents, such as the one at the start of this article:
- Chapter One
- Section One
- Section Two
- Section Three
- Chapter Two
- Chapter Three
The key to nesting lists is to remember that the nested list should relate to one specific list item. To reflect that in the code, the nested list is contained inside that list item. The code for the list above looks something like this:
<ol>
<li>Chapter One
<ol>
<li>Section One</li>
<li>Section Two </li>
<li>Section Three </li>
</ol>
</li>
<li>Chapter Two</li>
<li>Chapter Three </li>
</ol>
Note how the nested list starts after the <li>
and the text of the containing list item (“Chapter One”); then ends before the </li>
of the containing list item. Nested lists often form the basis for website navigation menus, as they are a good way to define the hierarchical structure of the website.
Theoretically you can nest as many lists as you like, although in practice it can become confusing to nest lists too deeply. For very large lists, you may be better off splitting the content up into several lists with headings instead, or even splitting it up into separate pages.
Use the AddWithValue
method:
comm.Parameters.AddWithValue("@person", "Myname");
comm.Parameters.AddWithValue("@address", "Myaddress");
In line with the answer given by Denis de Bernardy..
If you want id to be returned afterwards as well and want to insert more things into Table2:
with rows as (
INSERT INTO Table1 (name) VALUES ('a_title') RETURNING id
)
INSERT INTO Table2 (val, val2, val3)
SELECT id, 'val2value', 'val3value'
FROM rows
RETURNING val
Since the UI of the facebook has changed recently, here's the latest update for setting the sandbox mode ON/OFF :
Click on the Apps menu on the top bar.
Select the respective app from the drop down.
Go to 'Status & Review' from the table in the left side of the page.
Do you want to make this app and all its live features available to the general public? - Select switch to set YES/NO value.
Update: The YES/NO button will be disabled until and unless you provide your contact email.
Go to "Settings" in the left menu.
Update your Contact Email.
Hit the "Save" button at the bottom of the page.
Update: 'Status & Review' is replaced by 'App Review' now
I read a fantastic explanation on Reddit by jng, using the odometer as an analogy.
It is a useful convention. The same circuits and logic operations that add / subtract positive numbers in binary still work on both positive and negative numbers if using the convention, that's why it's so useful and omnipresent.
Imagine the odometer of a car, it rolls around at (say) 99999. If you increment 00000 you get 00001. If you decrement 00000, you get 99999 (due to the roll-around). If you add one back to 99999 it goes back to 00000. So it's useful to decide that 99999 represents -1. Likewise, it is very useful to decide that 99998 represents -2, and so on. You have to stop somewhere, and also by convention, the top half of the numbers are deemed to be negative (50000-99999), and the bottom half positive just stand for themselves (00000-49999). As a result, the top digit being 5-9 means the represented number is negative, and it being 0-4 means the represented is positive - exactly the same as the top bit representing sign in a two's complement binary number.
Understanding this was hard for me too. Once I got it and went back to re-read the books articles and explanations (there was no internet back then), it turned out a lot of those describing it didn't really understand it. I did write a book teaching assembly language after that (which did sell quite well for 10 years).
One thing I found out is that your folder holding your php/html files cannot be named the same name as the folder in your HTDOCS carrying your project.
When a number as a decimal it is usually a float
in Python.
If you want to remove the decimal and keep it an integer (int
). You can call the int()
method on it like so...
>>> int(2.0)
2
However, int
rounds down so...
>>> int(2.9)
2
If you want to round to the nearest integer you can use round
:
>>> round(2.9)
3.0
>>> round(2.4)
2.0
And then call int()
on that:
>>> int(round(2.9))
3
>>> int(round(2.4))
2
Well, there are lots of exceptions to throw, but here is how you throw an exception:
throw new IllegalArgumentException("INVALID");
Also, yes, you can create your own custom exceptions.
A note about exceptions. When you throw an exception (like above) and you catch the exception: the String
that you supply in the exception can be accessed throw the getMessage()
method.
try{
methodThatThrowsException();
}catch(IllegalArgumentException e)
{
e.getMessage();
}
I would like to add to some of the other answers here, if you don't need the first item but say the second number for example you can use rownumber in a subquery and base your result set off of that.
SELECT * FROM
(
SELECT
ROW_NUM() OVER (PARTITION BY Id ORDER BY record_date, other_cols) as rownum,
*
FROM products P
) INNER
WHERE rownum = 2
This also allows you to order off multiple columns in the subquery which may help if two record_dates have identical values. You can also partition off of multiple columns if needed by delimiting them with a comma
I've been using Bitvise SSH Server for a number of years. It is a wonderful product and it is easy to setup and maintain. It gives you great control over how users connect to the server with support for security groups.
Try this simple code.
1. Components side code: to get both body and header property. Here there's a token in body and Authorization
in the header.
loginUser() {
this.userService.loginTest(this.loginCred).
subscribe(res => {
let output1 = res;
console.log(output1.body.token);
console.log(output1.headers.get('Authorization'));
})
}
2. Service side code: sending login data in the body and observe the response in Observable
any which be subscribed in the component side.
loginTest(loginCred: LoginParams): Observable<any> {
const header1= {'Content-Type':'application/json',};
const body = JSON.stringify(loginCred);
return this.http.post<any>(this.baseURL+'signin',body,{
headers: header1,
observe: 'response',
responseType: 'json'
});
}
It is true use the base
(something) to call the base class constructor, but in case of overloading use the this
keyword
public ClassName() : this(par1,par2)
{
// do not call the constructor it is called in the this.
// the base key- word is used to call a inherited constructor
}
// Hint used overload as often as needed do not write the same code 2 or more times
What you want is a SQL case statement. The form of these is either:
select case [expression or column]
when [value] then [result]
when [value2] then [result2]
else [value3] end
or:
select case
when [expression or column] = [value] then [result]
when [expression or column] = [value2] then [result2]
else [value3] end
In your example you are after:
declare @temp as varchar(100)
set @temp='Measure'
select case @temp
when 'Measure' then Measure
else OtherMeasure end
from Measuretable
In addition to remove ugly cast warnings as most mentioned ,Class.cast is run-time cast mostly used with generic casting ,due to generic info will be erased at run time and some how each generic will be considered Object , this leads to not to throw an early ClassCastException.
for example serviceLoder use this trick when creating the objects,check S p = service.cast(c.newInstance()); this will throw a class cast exception when S P =(S) c.newInstance(); won't and may show a warning 'Type safety: Unchecked cast from Object to S'.(same as Object P =(Object) c.newInstance();)
-simply it checks that the casted object is instance of casting class then it will use the cast operator to cast and hide the warning by suppressing it.
java implementation for dynamic cast:
@SuppressWarnings("unchecked")
public T cast(Object obj) {
if (obj != null && !isInstance(obj))
throw new ClassCastException(cannotCastMsg(obj));
return (T) obj;
}
private S nextService() {
if (!hasNextService())
throw new NoSuchElementException();
String cn = nextName;
nextName = null;
Class<?> c = null;
try {
c = Class.forName(cn, false, loader);
} catch (ClassNotFoundException x) {
fail(service,
"Provider " + cn + " not found");
}
if (!service.isAssignableFrom(c)) {
fail(service,
"Provider " + cn + " not a subtype");
}
try {
S p = service.cast(c.newInstance());
providers.put(cn, p);
return p;
} catch (Throwable x) {
fail(service,
"Provider " + cn + " could not be instantiated",
x);
}
throw new Error(); // This cannot happen
}
Your fns is a cellstr array. You need to index in to it with {} instead of () to get the single string out as char.
fns{i}
teststruct.(fns{i})
Indexing in to it with () returns a 1-long cellstr array, which isn't the same format as the char array that the ".(name)" dynamic field reference wants. The formatting, especially in the display output, can be confusing. To see the difference, try this.
name_as_char = 'a'
name_as_cellstr = {'a'}
TelephonyManager tManager = (TelephonyManager)myActivity.getSystemService(Context.TELEPHONY_SERVICE);
String uid = tManager.getDeviceId();
getSystemService is a method from the Activity class. getDeviceID() will return the MDN or MEID of the device depending on which radio the phone uses (GSM or CDMA).
Each device MUST return a unique value here (assuming it's a phone). This should work for any Android device with a sim slot or CDMA radio. You're on your own with that Android powered microwave ;-)
As of PostgreSQL 9.4, you can use the ?
operator:
select info->>'name' from rabbits where (info->'food')::jsonb ? 'carrots';
You can even index the ?
query on the "food"
key if you switch to the jsonb type instead:
alter table rabbits alter info type jsonb using info::jsonb;
create index on rabbits using gin ((info->'food'));
select info->>'name' from rabbits where info->'food' ? 'carrots';
Of course, you probably don't have time for that as a full-time rabbit keeper.
Update: Here's a demonstration of the performance improvements on a table of 1,000,000 rabbits where each rabbit likes two foods and 10% of them like carrots:
d=# -- Postgres 9.3 solution
d=# explain analyze select info->>'name' from rabbits where exists (
d(# select 1 from json_array_elements(info->'food') as food
d(# where food::text = '"carrots"'
d(# );
Execution time: 3084.927 ms
d=# -- Postgres 9.4+ solution
d=# explain analyze select info->'name' from rabbits where (info->'food')::jsonb ? 'carrots';
Execution time: 1255.501 ms
d=# alter table rabbits alter info type jsonb using info::jsonb;
d=# explain analyze select info->'name' from rabbits where info->'food' ? 'carrots';
Execution time: 465.919 ms
d=# create index on rabbits using gin ((info->'food'));
d=# explain analyze select info->'name' from rabbits where info->'food' ? 'carrots';
Execution time: 256.478 ms
Here's an explanation I wrote recently to help with the void of information on this attribute. http://www.marklio.com/marklio/PermaLink,guid,ecc34c3c-be44-4422-86b7-900900e451f9.aspx (Internet Archive Wayback Machine link)
To quote the most relevant bits:
[Installing .NET] v4 is “non-impactful”. It should not change the behavior of existing components when installed.
The useLegacyV2RuntimeActivationPolicy attribute basically lets you say, “I have some dependencies on the legacy shim APIs. Please make them work the way they used to with respect to the chosen runtime.”
Why don’t we make this the default behavior? You might argue that this behavior is more compatible, and makes porting code from previous versions much easier. If you’ll recall, this can’t be the default behavior because it would make installation of v4 impactful, which can break existing apps installed on your machine.
The full post explains this in more detail. At RTM, the MSDN docs on this should be better.
This is the configuration file for Maven. It can be specified at two levels:
User Level. This settings.xml file provides configuration for a single user, and is normally provided in ${user.home}/.m2/settings.xml.
NOTE: This location can be overridden with the CLI option:
-s /path/to/user/settings.xml
Global Level. This settings.xml file provides configuration for all Maven users on a machine (assuming they're all using the same Maven installation). It's normally provided in ${maven.home}/conf/settings.xml.
NOTE: This location can be overridden with the CLI option:
-gs /path/to/global/settings.xml
For simple csv files, such as the following
id,col1,col2,col3
row1,r1c1,r1c2,r1c3
row2,r2c1,r2c2,r2c3
row3,r3c1,r3c2,r3c3
row4,r4c1,r4c2,r4c3
You can convert it to a Python dictionary using only built-ins
with open(csv_file) as f:
csv_list = [[val.strip() for val in r.split(",")] for r in f.readlines()]
(_, *header), *data = csv_list
csv_dict = {}
for row in data:
key, *values = row
csv_dict[key] = {key: value for key, value in zip(header, values)}
This should yield the following dictionary
{'row1': {'col1': 'r1c1', 'col2': 'r1c2', 'col3': 'r1c3'},
'row2': {'col1': 'r2c1', 'col2': 'r2c2', 'col3': 'r2c3'},
'row3': {'col1': 'r3c1', 'col2': 'r3c2', 'col3': 'r3c3'},
'row4': {'col1': 'r4c1', 'col2': 'r4c2', 'col3': 'r4c3'}}
Note: Python dictionaries have unique keys, so if your csv file has duplicate ids
you should append each row to a list.
for row in data:
key, *values = row
if key not in csv_dict:
csv_dict[key] = []
csv_dict[key].append({key: value for key, value in zip(header, values)})
I think you should call the super.draw()
method first before you do anything in surfaceView's draw method.
Here's one for Laravel 5, Bootstrap 4 and without Blade syntax (for those who find it infinitely harder to read).
To use, instead of:
{!! $users->render() !!}
Use:
@include('partials/pagination', ['paginator' => $users])
Where partials/pagination
is your blade template file with the below contents pasted in.
// Number of links to show. Odd numbers work better
$linkCount = 7;
$pageCount = $paginator->lastPage();
if ($pageCount > 1)
{
$currentPage = $paginator->currentPage();
$pagesEitherWay = floor($linkCount / 2);
$paginationHtml = '<ul class="pagination">';
// Previous item
$previousDisabled = $currentPage == 1 ? 'disabled' : '';
$paginationHtml .= '<li class="page-item '.$previousDisabled.'">
<a class="page-link" href="'.$paginator->url($currentPage - 1).'" aria-label="Previous">
<span aria-hidden="true">«</span>
<span class="sr-only">Previous</span>
</a>
</li>';
// Set the first and last pages
$startPage = ($currentPage - $pagesEitherWay) < 1 ? 1 : $currentPage - $pagesEitherWay;
$endPage = ($currentPage + $pagesEitherWay) > $pageCount ? $pageCount : ($currentPage + $pagesEitherWay);
// Alter if the start is too close to the end of the list
if ($startPage > $pageCount - $linkCount)
{
$startPage = ($pageCount - $linkCount) + 1;
$endPage = $pageCount;
}
// Alter if the end is too close to the start of the list
if ($endPage <= $linkCount)
{
$startPage = 1;
$endPage = $linkCount < $pageCount ? $linkCount : $pageCount;
}
// Loop through and collect
for ($i = $startPage; $i <= $endPage; $i++)
{
$disabledClass = $i == $currentPage ? 'disabled' : '';
$paginationHtml .= '<li class="page-item '.$disabledClass.'">
<a class="page-link" href="'.$paginator->url($i).'">'.$i.'</a>
</li>';
}
// Next item
$nextDisabled = $currentPage == $pageCount ? 'disabled' : '';
$paginationHtml .= '<li class="page-item '.$nextDisabled.'">
<a class="page-link" href="'.$paginator->url($currentPage + 1).'" aria-label="Next">
<span aria-hidden="true">»</span>
<span class="sr-only">Next</span>
</a>
</li>';
$paginationHtml .= '</ul>';
echo $paginationHtml;
}