You can use above function for casting not similar class objects (PHP >= 5.3)
/**
* Class casting
*
* @param string|object $destination
* @param object $sourceObject
* @return object
*/
function cast($destination, $sourceObject)
{
if (is_string($destination)) {
$destination = new $destination();
}
$sourceReflection = new ReflectionObject($sourceObject);
$destinationReflection = new ReflectionObject($destination);
$sourceProperties = $sourceReflection->getProperties();
foreach ($sourceProperties as $sourceProperty) {
$sourceProperty->setAccessible(true);
$name = $sourceProperty->getName();
$value = $sourceProperty->getValue($sourceObject);
if ($destinationReflection->hasProperty($name)) {
$propDest = $destinationReflection->getProperty($name);
$propDest->setAccessible(true);
$propDest->setValue($destination,$value);
} else {
$destination->$name = $value;
}
}
return $destination;
}
EXAMPLE:
class A
{
private $_x;
}
class B
{
public $_x;
}
$a = new A();
$b = new B();
$x = cast('A',$b);
$x = cast('B',$a);
Just add a muted
attribute and everything will work fine.
The source of this answer is here: https://webkit.org/blog/6784/new-video-policies-for-ios/
By default, WebKit will have the following policies:
<video autoplay>
elements will now honor the autoplay attribute, for elements which meet the following conditions:
<video>
elements will be allowed to autoplay without a user gesture if their source media contains no audio tracks.<video muted>
elements will also be allowed to autoplay without a user gesture.- If a
<video>
element gains an audio track or becomes un-muted without a user gesture, playback will pause.<video autoplay>
elements will only begin playing when visible on-screen such as when they are scrolled into the viewport, made visible through CSS, and inserted into the DOM.<video autoplay>
elements will pause if they become non-visible, such as by being scrolled out of the viewport.
<video>
elements will now honor the play() method, for elements which meet the following conditions:
<video>
elements will be allowed to play() without a user gesture if their source media contains no audio tracks, or if their muted property is set to true.- If a
<video>
element gains an audio track or becomes un-muted without a user gesture, playback will pause.<video>
elements will be allowed to play() when not visible on-screen or when out of the viewport.- video.play() will return a Promise, which will be rejected if any of these conditions are not met.
On iPhone,
<video playsinline>
elements will now be allowed to play inline, and will not automatically enter fullscreen mode when playback begins.<video>
elements without playsinline attributes will continue to require fullscreen mode for playback on iPhone. When exiting fullscreen with a pinch gesture,<video>
elements without playsinline will continue to play inline.
The cleaner solution without NullPointerException is:
map.replace(key, map.get(key) + 1);
Your path should be like this : "http://websitedomain//folderpath/66.jpg">
<img src="http://websitedomain/folderpath/66.jpg" width="400" height="400" ></img>
You can use sum
to sum the elements of a list, however if your list is coming from raw_input
, you probably want to convert the items to int
or float
first:
l = raw_input().split(' ')
sum(map(int, l))
Unlike languages that employ 'true' lexical scoping, Python opts to have specific 'namespaces' for variables, whether it be global
, nonlocal
, or local. It could be argued that making developers consciously code with such namespaces in mind is more explicit, thus more understandable. I would argue that such complexities make the language more unwieldy, but I guess it's all down to personal preference.
Here are some examples regarding global
:-
>>> global_var = 5
>>> def fn():
... print(global_var)
...
>>> fn()
5
>>> def fn_2():
... global_var += 2
... print(global_var)
...
>>> fn_2()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 2, in fn_2
UnboundLocalError: local variable 'global_var' referenced before assignment
>>> def fn_3():
... global global_var
... global_var += 2
... print(global_var)
...
>>> fn_3()
7
The same patterns can be applied to nonlocal
variables too, but this keyword is only available to the latter Python versions.
In case you're wondering, nonlocal
is used where a variable isn't global, but isn't within the function definition it's being used. For example, a def
within a def
, which is a common occurrence partially due to a lack of multi-statement lambdas. There's a hack to bypass the lack of this feature in the earlier Pythons though, I vaguely remember it involving the use of a single-element list...
Note that writing to variables is where these keywords are needed. Just reading from them isn't ambiguous, thus not needed. Unless you have inner def
s using the same variable names as the outer ones, which just should just be avoided to be honest.
You need antMatcher
for multiple HttpSecurity
, see Spring Security Reference:
5.7 Multiple HttpSecurity
We can configure multiple HttpSecurity instances just as we can have multiple
<http>
blocks. The key is to extend theWebSecurityConfigurationAdapter
multiple times. For example, the following is an example of having a different configuration for URL’s that start with/api/
.@EnableWebSecurity public class MultiHttpSecurityConfig { @Autowired public void configureGlobal(AuthenticationManagerBuilder auth) { 1 auth .inMemoryAuthentication() .withUser("user").password("password").roles("USER").and() .withUser("admin").password("password").roles("USER", "ADMIN"); } @Configuration @Order(1) 2 public static class ApiWebSecurityConfigurationAdapter extends WebSecurityConfigurerAdapter { protected void configure(HttpSecurity http) throws Exception { http .antMatcher("/api/**") 3 .authorizeRequests() .anyRequest().hasRole("ADMIN") .and() .httpBasic(); } } @Configuration 4 public static class FormLoginWebSecurityConfigurerAdapter extends WebSecurityConfigurerAdapter { @Override protected void configure(HttpSecurity http) throws Exception { http .authorizeRequests() .anyRequest().authenticated() .and() .formLogin(); } } }
1 Configure Authentication as normal
2 Create an instance of
WebSecurityConfigurerAdapter
that contains@Order
to specify whichWebSecurityConfigurerAdapter
should be considered first.3 The
http.antMatcher
states that thisHttpSecurity
will only be applicable to URLs that start with/api/
4 Create another instance of
WebSecurityConfigurerAdapter
. If the URL does not start with/api/
this configuration will be used. This configuration is considered afterApiWebSecurityConfigurationAdapter
since it has an@Order
value after1
(no@Order
defaults to last).
In your case you need no antMatcher
, because you have only one configuration. Your modified code:
http
.authorizeRequests()
.antMatchers("/high_level_url_A/sub_level_1").hasRole('USER')
.antMatchers("/high_level_url_A/sub_level_2").hasRole('USER2')
.somethingElse() // for /high_level_url_A/**
.antMatchers("/high_level_url_A/**").authenticated()
.antMatchers("/high_level_url_B/sub_level_1").permitAll()
.antMatchers("/high_level_url_B/sub_level_2").hasRole('USER3')
.somethingElse() // for /high_level_url_B/**
.antMatchers("/high_level_url_B/**").authenticated()
.anyRequest().permitAll()
I also tried to work with an SQL-IN-like thing - querying against an Entity Data Model. My approach is a string builder to compose a big OR-expression. That's terribly ugly, but I'm afraid it's the only way to go right now.
Now well, that looks like this:
Queue<Guid> productIds = new Queue<Guid>(Products.Select(p => p.Key));
if(productIds.Count > 0)
{
StringBuilder sb = new StringBuilder();
sb.AppendFormat("{0}.ProductId = Guid\'{1}\'", entities.Products.Name, productIds.Dequeue());
while(productIds.Count > 0)
{
sb.AppendFormat(" OR {0}.ProductId = Guid\'{1}\'",
entities.Products.Name, productIds.Dequeue());
}
}
Working with GUIDs in this context: As you can see above, there is always the word "GUID" before the GUID ifself in the query string fragments. If you don't add this, ObjectQuery<T>.Where
throws the following exception:
The argument types 'Edm.Guid' and 'Edm.String' are incompatible for this operation., near equals expression, line 6, column 14.
Found this in MSDN Forums, might be helpful to have in mind.
Matthias
... looking forward for the next version of .NET and Entity Framework, when everything get's better. :)
If you must use a 2d array:
int numOfPairs = 10; String[][] array = new String[numOfPairs][2]; for(int i = 0; i < array.length; i++){ for(int j = 0; j < array[i].length; j++){ array[i] = new String[2]; array[i][0] = "original word"; array[i][1] = "rearranged word"; } }
Does this give you a hint?
First change the array to a string by using implode() function. E.g $number=array(1,2,3,4,5,...);
$stringofnumber=implode("|",$number);
then pass the string to a session. e.g $_SESSION['string']=$stringofnumber;
so when you go to the page where you want to use the array, just explode your string. e.g
$number=explode("|", $_SESSION['string']);
finally number is your array but remember to start array on the of each page.
copy NUL EmptyFile.txt
DOS has a few special files (devices, actually) that exist in every directory, NUL
being the equivalent of UNIX's /dev/null
: it's a magic file that's always empty and throws away anything you write to it. Here's a list of some others; CON
is occasionally useful as well.
To avoid having any output at all, you can use
copy /y NUL EmptyFile.txt >NUL
/y
prevents copy
from asking a question you can't see when output goes to NUL
.
string filepath = "C:\\Program Files\\example.txt";
FileVersionInfo myFileVersionInfo = FileVersionInfo.GetVersionInfo(filepath);
FileInfo fi = new FileInfo(filepath);
Console.WriteLine(fi.Name);
//input to the "fi" is a full path to the file from "filepath"
//This code will return the fileName from the given path
//output
//example.txt
You can get a handle to the DOM element via ElementRef
by injecting it into your component's constructor:
constructor(private myElement: ElementRef) { ... }
Docs: https://angular.io/docs/ts/latest/api/core/index/ElementRef-class.html
Yes, with reflection - assuming each property type implements Equals
appropriately. An alternative would be to use ReflectiveEquals
recursively for all but some known types, but that gets tricky.
public bool ReflectiveEquals(object first, object second)
{
if (first == null && second == null)
{
return true;
}
if (first == null || second == null)
{
return false;
}
Type firstType = first.GetType();
if (second.GetType() != firstType)
{
return false; // Or throw an exception
}
// This will only use public properties. Is that enough?
foreach (PropertyInfo propertyInfo in firstType.GetProperties())
{
if (propertyInfo.CanRead)
{
object firstValue = propertyInfo.GetValue(first, null);
object secondValue = propertyInfo.GetValue(second, null);
if (!object.Equals(firstValue, secondValue))
{
return false;
}
}
}
return true;
}
Note that, for PIPE
being any command or sequence of commands, then:
if PIPE ; then
# do one thing if PIPE returned with zero status ($?=0)
else
# do another thing if PIPE returned with non-zero status ($?!=0), e.g. error
fi
For the record, [ expr ]
is a shell builtin† shorthand for test expr
.
Since grep
returns with status 0 in case of a match, and non-zero status in case of no matches, you can use:
if grep -lq '^MYSQL_ROLE=master' ; then
# do one thing
else
# do another thing
fi
Note the use of -l
which only cares about the file having at least one match (so that grep
returns as soon as it finds one match, without needlessly continuing to parse the input file.)
†on some platforms [ expr ]
is not a builtin, but an actual executable /bin/[
(whose last argument will be ]
), which is why [ expr ]
should contain blanks around the square brackets, and why it must be followed by one of the command list separators (;
, &&
, ||
, |
, &
, newline)
We should ensure that there are no goto statements in the function itself .. taken care by function call being the last thing in the callee function.
Large scale recursions can use this for optimizations, but in small scale, the instruction overhead for making the function call a tail call reduces the actual purpose.
TCO might cause a forever running function:
void eternity()
{
eternity();
}
I've developed a dotnet library that might come in useful. I have fixed the problem of never getting all of the data if it exceeds the buffer, which many posts have discounted. Still some problems with the solution but works descently well https://github.com/NicholasLKSharp/DotNet-TCP-Communication
You can use native javascript function
var obj = {a:1,b:2};
Object.keys(obj).forEach(function(key){
console.log(key, obj[el])
})
or create an object prototype foreach, but it usually causes issues with other frameworks
if (!Object.prototype.forEach) {
Object.defineProperty(Object.prototype, 'forEach', {
value: function (callback, thisArg) {
if (this == null) {
throw new TypeError('Not an object');
}
thisArg = thisArg || window;
for (var key in this) {
if (this.hasOwnProperty(key)) {
callback.call(thisArg, this[key], key, this);
}
}
}
});
}
var obj = {a:1,b:2};
obj.forEach(function(key, value){
console.log(key, value)
})
I was able to resolve it by updating sdk version and tools in gradle
compileSdkVersion 26
buildToolsVersion "26.0.1"
and support library 26.0.1
https://developer.android.com/topic/libraries/support-library/revisions.html#26-0-1
Set the [Console]::OuputEncoding
as encoding whatever you want, and print out with [Console]::WriteLine
.
If powershell ouput method has a problem, then don't use it. It feels bit bad, but works like a charm :)
If your business class is directly used by your UI is preferrable to use IDataErrorInfo because it put logic closer to their owner.
If your business class is a stub class created by a reference to an WCF/XmlWeb service then you can not/must not use IDataErrorInfo nor throw Exception for use with ExceptionValidationRule. Instead you can:
The function declaration int writeFile () ; seems to be missing in the code. Add int writeFile () ; before the function main()
Didn't work with ODBC-Bridge for me too. I got the way around to initialize ODBC connection using ODBC driver.
import java.sql.*;
public class UserLogin
{
public static void main(String[] args)
{
try
{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
// C:\\databaseFileName.accdb" - location of your database
String url = "jdbc:odbc:Driver={Microsoft Access Driver (*.mdb, *.accdb)};DBQ=" + "C:\\emp.accdb";
// specify url, username, pasword - make sure these are valid
Connection conn = DriverManager.getConnection(url, "username", "password");
System.out.println("Connection Succesfull");
}
catch (Exception e)
{
System.err.println("Got an exception! ");
System.err.println(e.getMessage());
}
}
}
Here is your dataframe:
import pandas as pd
df = pd.DataFrame({
'A': ['a.1', 'a.2', 'a.3'],
'B': ['b.1', 'b.2', 'b.3'],
'C': ['c.1', 'c.2', 'c.3']})
Your answer is in the paragraph "Setting with enlargement" in the section on "Indexing and selecting data" in the documentation on Pandas.
It says:
A DataFrame can be enlarged on either axis via .loc.
So what you need to do is simply one of these two:
df.loc[:, 'D'] = df.loc[:, 'B']
df.loc[:, 'D'] = df['B']
I solved these kinds of problems using the webdrive manager.
You can automatically use the correct chromedriver by using the webdrive-manager. Install the webdrive-manager:
pip install webdriver-manager
Then use the driver in python as follows
from selenium import webdriver
from webdriver_manager.chrome import ChromeDriverManager
driver = webdriver.Chrome(ChromeDriverManager().install())
This answer is taken from https://stackoverflow.com/a/52878725/10741023
My guess is that you're trying to squeeze a number greater than 99999.99 into your decimal fields. Changing it to (8,3) isn't going to do anything if it's greater than 99999.999 - you need to increase the number of digits before the decimal. You can do this by increasing the precision (which is the total number of digits before and after the decimal). You can leave the scale the same unless you need to alter how many decimal places to store. Try decimal(9,2)
or decimal(10,2)
or whatever.
You can test this by commenting out the insert #temp
and see what numbers the select statement is giving you and see if they are bigger than your column can handle.
You can use onlinefontconverter.com site. It works fine and have plenty of output formats (afm bin cff dfont eot pfa pfb pfm ps pt3 suit svg t42 tfm ttc ttf woff). One of the advantages I saw, is that it export all the fonts contained inside the ttc at once (which is very convenient).
I came to this page specifically looking for a way to format an error string. So if someone needs help with the same, you want to use the fmt.Errorf()
function.
The method signature is func Errorf(format string, a ...interface{}) error
.
It returns the formatted string as a value that satisfies the error
interface.
You can look up more details in the documentation - https://golang.org/pkg/fmt/#Errorf.
Try with: $('.onediv').eq(0)
From the demo: Other examples of selectors and methods targeting the first LI
unside an UL
:
.eq()
Method:$('li').eq(0)
:eq()
selector:$('li:eq(0)')
.first()
Method$('li').first()
:first
selector:$('li:first')
:first-child
selector:$('li:first-child')
:lt()
selector:$('li:lt(1)')
:nth-child()
selector:$('li:nth-child(1)')
jQ + JS:
you can also use [i]
to get the JS HTMLelement
index out of the jQuery el. (array) collection like eg:
$('li')[0]
now that you have the JS element representation you have to use JS native methods eg:
$('li')[0].className = 'active'; // Adds class "active" to the first LI in the DOM
or you can (don't - it's bad design) wrap it back into a jQuery object
$( $('li')[0] ).addClass('active'); // Don't. Use .eq() instead
Heres a nicer way using closures
usort($your_data, function($a, $b)
{
return strcmp($a->name, $b->name);
});
Please note this is not in PHP's documentation but if you using 5.3+ closures are supported where callable arguments can be provided.
Lets call your ck
variable payload
instead, like in the python-requests docs:
payload = {'inUserName': 'USERNAME/EMAIL', 'inUserPass': 'PASSWORD'}
url = 'http://www.locationary.com/home/index2.jsp'
requests.post(url, data=payload)
See https://stackoverflow.com/a/17633072/111362 below.
Use AdapterDataObserver in custom RecyclerView
Kotlin:
RecyclerViewEnum.kt
enum class RecyclerViewEnum {
LOADING,
NORMAL,
EMPTY_STATE
}
RecyclerViewEmptyLoadingSupport.kt
class RecyclerViewEmptyLoadingSupport : RecyclerView {
var stateView: RecyclerViewEnum? = RecyclerViewEnum.LOADING
set(value) {
field = value
setState()
}
var emptyStateView: View? = null
var loadingStateView: View? = null
constructor(context: Context) : super(context) {}
constructor(context: Context, attrs: AttributeSet) : super(context, attrs) {}
constructor(context: Context, attrs: AttributeSet, defStyle: Int) : super(context, attrs, defStyle) {}
private val dataObserver = object : AdapterDataObserver() {
override fun onChanged() {
onChangeState()
}
override fun onItemRangeRemoved(positionStart: Int, itemCount: Int) {
super.onItemRangeRemoved(positionStart, itemCount)
onChangeState()
}
override fun onItemRangeInserted(positionStart: Int, itemCount: Int) {
super.onItemRangeInserted(positionStart, itemCount)
onChangeState()
}
}
override fun setAdapter(adapter: RecyclerView.Adapter<*>?) {
super.setAdapter(adapter)
adapter?.registerAdapterDataObserver(dataObserver)
dataObserver.onChanged()
}
fun onChangeState() {
if (adapter?.itemCount == 0) {
emptyStateView?.visibility = View.VISIBLE
loadingStateView?.visibility = View.GONE
[email protected] = View.GONE
} else {
emptyStateView?.visibility = View.GONE
loadingStateView?.visibility = View.GONE
[email protected] = View.VISIBLE
}
}
private fun setState() {
when (this.stateView) {
RecyclerViewEnum.LOADING -> {
loadingStateView?.visibility = View.VISIBLE
[email protected] = View.GONE
emptyStateView?.visibility = View.GONE
}
RecyclerViewEnum.NORMAL -> {
loadingStateView?.visibility = View.GONE
[email protected] = View.VISIBLE
emptyStateView?.visibility = View.GONE
}
RecyclerViewEnum.EMPTY_STATE -> {
loadingStateView?.visibility = View.GONE
[email protected] = View.GONE
emptyStateView?.visibility = View.VISIBLE
}
}
}
}
layout.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<LinearLayout
android:id="@+id/emptyView"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@color/white"
android:gravity="center"
android:orientation="vertical">
<TextView
android:id="@+id/emptyLabelTv"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="empty" />
</LinearLayout>
<LinearLayout
android:id="@+id/loadingView"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@color/white"
android:gravity="center"
android:orientation="vertical">
<ProgressBar
android:id="@+id/progressBar"
android:layout_width="45dp"
android:layout_height="45dp"
android:layout_gravity="center"
android:indeterminate="true"
android:theme="@style/progressBarBlue" />
</LinearLayout>
<com.peeyade.components.recyclerView.RecyclerViewEmptyLoadingSupport
android:id="@+id/recyclerView"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</LinearLayout>
in activity use this way:
recyclerView?.apply {
layoutManager = GridLayoutManager(context, 2)
emptyStateView = emptyView
loadingStateView = loadingView
adapter = adapterGrid
}
// you can set LoadingView or emptyView manual
recyclerView.stateView = RecyclerViewEnum.EMPTY_STATE
recyclerView.stateView = RecyclerViewEnum.LOADING
Solution to allow Apache 2 to host websites outside of htdocs:
Underneath the "DocumentRoot" directive in httpd.conf, you should see a directory block. Replace this directory block with:
<Directory />
Options FollowSymLinks
AllowOverride All
Allow from all
</Directory>
REMEMBER NOT TO USE THIS CONFIGURATION IN A REAL ENVIRONMENT
bmleite has the correct answer about including the module.
If that is correct in your situation, you should also ensure that you are not redefining the modules in multiple files.
Remember:
angular.module('ModuleName', []) // creates a module.
angular.module('ModuleName') // gets you a pre-existing module.
So if you are extending a existing module, remember not to overwrite when trying to fetch it.
You can use scriptlets, however, this is not the way to go. Nowdays inline scriplets or JAVA code in your JSP files is considered a bad habit.
You should read up on JSTL a bit more. If the ansokanInfo object is in your request or session scope, printing the object (toString() method) like this: ${ansokanInfo} can give you some base information. ${ansokanInfo.pSystem} should call the object getter method. If this all works, you can use this:
<c:if test="${ ansokanInfo.pSystem == 'NAT'}"> tataa </c:if>
In android gradle 0.4.0 you can just do:
println System.env.HOME
classpath com.android.tools.build:gradle-experimental:0.4.0
@Liem Vo's answer is correct if you are using android.widget.Button without any overriding. If you are overriding your theme using MaterialComponents, this will not solve the issue.
So if you are
Use app:icon parameter.
<Button
android:id="@+id/bSearch"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:padding="16dp"
android:text="Search"
android:textSize="24sp"
app:icon="@android:drawable/ic_menu_search" />
May do simple for loop with checking types:
with open("jsondontdoit.json", 'w') as fp:
for key in bests.keys():
if type(bests[key]) == np.ndarray:
bests[key] = bests[key].tolist()
continue
for idx in bests[key]:
if type(bests[key][idx]) == np.ndarray:
bests[key][idx] = bests[key][idx].tolist()
json.dump(bests, fp)
fp.close()
Call the script from a batch file (*.bat) or CMD
pwsh.exe -NoLogo -ExecutionPolicy Bypass -Command "./Script.ps1 -Param1 Hello -Param2 World"
pwsh.exe -NoLogo -ExecutionPolicy Bypass -Command "path-to-script/Script.ps1 -Param1 Hello -Param2 World"
pwsh.exe -NoLogo -ExecutionPolicy Bypass -Command "./Script.ps1 Hello -Param2 World"
pwsh.exe -NoLogo -ExecutionPolicy Bypass -Command "./Script.ps1 Hello World"
pwsh.exe -NoLogo -ExecutionPolicy Bypass -Command "./Script.ps1 -Param2 World Hello"
PowerShell
powershell.exe -NoLogo -ExecutionPolicy Bypass -Command "./Script.ps1 -Param1 Hello -Param2 World"
powershell.exe -NoLogo -ExecutionPolicy Bypass -Command "path-to-script/Script.ps1 -Param1 Hello -Param2 World"
powershell.exe -NoLogo -ExecutionPolicy Bypass -Command "./Script.ps1 Hello -Param2 World"
powershell.exe -NoLogo -ExecutionPolicy Bypass -Command "./Script.ps1 Hello World"
powershell.exe -NoLogo -ExecutionPolicy Bypass -Command "./Script.ps1 -Param2 World Hello"
Call from PowerShell
PowerShell Core or Windows PowerShell
& path-to-script/Script.ps1 -Param1 Hello -Param2 World
& ./Script.ps1 -Param1 Hello -Param2 World
Script.ps1 - Script Code
param(
[Parameter(Mandatory=$True, Position=0, ValueFromPipeline=$false)]
[System.String]
$Param1,
[Parameter(Mandatory=$True, Position=1, ValueFromPipeline=$false)]
[System.String]
$Param2
)
Write-Host $Param1
Write-Host $Param2
1) DI is Child->obj depends on parent-obj. The verb depends is important. 2) IOC is Child->obj perform under a platform. where platform could be school, college, dance class. Here perform is an activity with different implication under any platform provider.
practical example: `
//DI
child.getSchool();
//IOC
child.perform()// is a stub implemented by dance-school
child.flourish()// is a stub implemented by dance-school/school/
`
-AB
You can encapsulate this quite nicely in a func similar to what is below.
package main
import (
"bufio"
"fmt"
"os"
)
func main() {
fmt.Println(prompt())
}
func prompt(params ...string) string {
prompt := ": "
if len(params) > 0 {
prompt = params[0]
}
reader := bufio.NewReader(os.Stdin)
fmt.Print(prompt)
text, _ := reader.ReadString('\n')
return text
}
In this example, the prompt by default has a colon and a space in front of it . . .
:
. . . however you can override that by supplying a parameter to the prompt function.
prompt("Input here -> ")
This will result in a prompt like below.
Input here ->
In my case, I just close all instance and copy my root application folder and paste it in different location then open solution in VS it works....
I had the same problem. I was using Python 2, Windows 10 and Git Bash. Turns out in Git Bash you need to use:
source venv/Scripts/activate
In 2008 we cant use Skip().Take()
The way is:
var MinPageRank = (PageNumber - 1) * NumInPage + 1
var MaxPageRank = PageNumber * NumInPage
var visit = Visita.FromSql($"SELECT * FROM (SELECT [RANK] = ROW_NUMBER() OVER (ORDER BY Hora DESC),* FROM Visita WHERE ) A WHERE A.[RANK] BETWEEN {MinPageRank} AND {MaxPageRank}").ToList();
Your OCD is to blame :)
You do not have to put anything about copyright on your page - copyright automatically applies until you explicitly license it otherwise. Copyright also applies for a preset number of years as determined by international treaties. I do not know what the exact number of years is, but it is a lot, so there is absolutely no point in updating the year in your copyright notice.
C++20 will add constexpr
strings and vectors
The following proposal has been accepted apparently: http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2018/p0980r0.pdf and it adds constructors such as:
// 20.3.2.2, construct/copy/destroy
constexpr
basic_string() noexcept(noexcept(Allocator())) : basic_string(Allocator()) { }
constexpr
explicit basic_string(const Allocator& a) noexcept;
constexpr
basic_string(const basic_string& str);
constexpr
basic_string(basic_string&& str) noexcept;
in addition to constexpr versions of all / most methods.
There is no support as of GCC 9.1.0, the following fails to compile:
#include <string>
int main() {
constexpr std::string s("abc");
}
with:
g++-9 -std=c++2a main.cpp
with error:
error: the type ‘const string’ {aka ‘const std::__cxx11::basic_string<char>’} of ‘constexpr’ variable ‘s’ is not literal
std::vector
discussed at: Cannot create constexpr std::vector
Tested in Ubuntu 19.04.
If you're comfortable with numba it allows to create a fast short-circuit (stops as soon as a NaN is found) function:
import numba as nb
import math
@nb.njit
def anynan(array):
array = array.ravel()
for i in range(array.size):
if math.isnan(array[i]):
return True
return False
If there is no NaN
the function might actually be slower than np.min
, I think that's because np.min
uses multiprocessing for large arrays:
import numpy as np
array = np.random.random(2000000)
%timeit anynan(array) # 100 loops, best of 3: 2.21 ms per loop
%timeit np.isnan(array.sum()) # 100 loops, best of 3: 4.45 ms per loop
%timeit np.isnan(array.min()) # 1000 loops, best of 3: 1.64 ms per loop
But in case there is a NaN in the array, especially if it's position is at low indices, then it's much faster:
array = np.random.random(2000000)
array[100] = np.nan
%timeit anynan(array) # 1000000 loops, best of 3: 1.93 µs per loop
%timeit np.isnan(array.sum()) # 100 loops, best of 3: 4.57 ms per loop
%timeit np.isnan(array.min()) # 1000 loops, best of 3: 1.65 ms per loop
Similar results may be achieved with Cython or a C extension, these are a bit more complicated (or easily avaiable as bottleneck.anynan
) but ultimatly do the same as my anynan
function.
I know StackOverflow is not the place for opinion based answers, but I actually have a good opinion on when to shelve changes with a stash.
When you make changes in your workspace/working tree, if you need to perform any branch based operations like a merge, push, fetch or pull, you must be at a clean commit point. So if you have workspace changes you need to commit them. But what if you don't want to commit them? What if they are experimental? Something you don't want part of your commit history? Something you don't want others to see when you push to GitHub?
In that case, you can do a hard reset. But if you do a hard reset you will lose all of your local working tree changes because everything gets overwritten to where it was at the time of the last commit and you'll lose all of your changes.
So, as for the answer of 'when should you stash', the answer is when you need to get back to a clean commit point with a synchronized working tree/index/commit, but you don't want to lose your local changes in the process. Just shelve your changes in a stash and you're good.
And once you've done your stash and then merged or pulled or pushed, you can just stash pop or apply and you're back to where you started from.
GitHub is constantly adding new features, but as of right now, there is now way to save a stash there. Again, the idea of a stash is that it's local and private. Nobody else can peek into your stash without physical access to your workstation. Kinda the same way git reflog is private with the git log is public. It probably wouldn't be private if it was pushed up to GitHub.
One trick might be to do a diff of your workspace, check the diff into your git repository, commit and then push. Then you can do a pull from home, get the diff and then unwind it. But that's a pretty messy way to achieve those results.
git diff > git-dif-file.diff
The only way to do explicit scaling in CSS is to use tricks such as found here.
IE6 only, you could also use filters (check out PNGFix). But applying them automatically to the page will need javascript, though that javascript could be embedded in the CSS file.
If you are going to require javascript, then you might want to just have javascript fill in the missing value for the height by inspecting the image once the content has loaded. (Sorry I do not have a reference for this technique).
Finally, and pardon me for this soapbox, you might want to eschew IE6 support in this matter. You could add _width: auto
after your width: 75px
rule, so that IE6 at least renders the image reasonably, even if it is the wrong size.
I recommend the last solution simply because IE6 is on the way out: 20% and going down almost a percent a month. Also, I note that your site is recreational and in the UK. Both of these help the demographic lean to be away from IE6: IE6 usage drops nearly 40% during weekends (no citation sorry), and UK has a much lower IE6 demographic (again no citation, sorry).
Good luck!
If you want to remove all whitespace:
$str = preg_replace('/\s+/', '', $str);
See the 5th example on the preg_replace documentation. (Note I originally copied that here.)
Edit: commenters pointed out, and are correct, that str_replace
is better than preg_replace
if you really just want to remove the space character. The reason to use preg_replace
would be to remove all whitespace (including tabs, etc.).
I have downloaded Intellij Idea. When I try to install Intellij, a pop-up appeared that my Mac is missing with Java RE, do you want to download it? After I downloaded missing package using Intellij, I could open Android Studio.
malloc does not allocate on specific boundaries, so it must be assumed that it allocates on a byte boundary.
The returned pointer can then not be used if converted to any other type, since accessing that pointer will probably produce a memory access violation by the CPU, and the application will be immediately shut down.
As others have pointed out, there are many web frameworks for Python.
But, seeing as you are just getting started with Python, a simple CGI script might be more appropriate:
Rename your script to index.cgi
. You also need to execute chmod +x index.cgi
to give it execution privileges.
Add these 2 lines in the beginning of the file:
#!/usr/bin/python print('Content-type: text/html\r\n\r')
After this the Python code should run just like in terminal, except the output goes to the browser. When you get that working, you can use the cgi module to get data back from the browser.
Note: this assumes that your webserver is running Linux. For Windows, #!/Python26/python
might work instead.
The following seems to work:
awk -F',[[:blank:]]*' '{$2=$2}1' OFS="," input.txt
I was getting this error while posting a FormData object because I was not setting up the ajax call correctly. Setup below fixed my issue.
var myformData = new FormData();
myformData.append('leadid', $("#leadid").val());
myformData.append('date', $(this).val());
myformData.append('time', $(e.target).prev().val());
$.ajax({
method: 'post',
processData: false,
contentType: false,
cache: false,
data: myformData,
enctype: 'multipart/form-data',
url: 'include/ajax.php',
success: function (response) {
$("#subform").html(response).delay(4000).hide(1);
}
});
You'll have to construct the query-string.
<?php
$ids = array(1, 2, 3, 7, 8, 9);
$inQuery = implode(',', array_fill(0, count($ids), '?'));
$db = new PDO(...);
$stmt = $db->prepare(
'SELECT *
FROM table
WHERE id IN(' . $inQuery . ')'
);
// bindvalue is 1-indexed, so $k+1
foreach ($ids as $k => $id)
$stmt->bindValue(($k+1), $id);
$stmt->execute();
?>
Both chris (comments) and somebodyisintrouble suggested that the foreach-loop ...
(...)
// bindvalue is 1-indexed, so $k+1
foreach ($ids as $k => $id)
$stmt->bindValue(($k+1), $id);
$stmt->execute();
... might be redundant, so the foreach
loop and the $stmt->execute
could be replaced by just ...
<?php
(...)
$stmt->execute($ids);
Encountered similar error. resetting chrome://net-internals/#hsts did not work for me. The issue was that my vm's clock was skewed by days. resetting the time did work out to resolve this issue. https://support.google.com/chrome/answer/4454607?hl=en
Here are instructions assuming you want to install Cygwin on a computer with no Internet connection. I assume that you have access to another computer with an Internet connection. Start on the connected computer:
Get the Cygwin install program ("setup.exe"). Direct download URL: x86 or x86_64.
When the setup asks "Choose a download source", choose Download Without Installing
Go through the rest of the setup (choose download directory, mirrors, software packages you want, etc)
Now you have a Cygwin repository right there on your hard disk. Copy this directory, along with the "setup.exe" program, over to your target computer (it does not need to be on a network).
On the target computer, run "setup.exe"
When the setup asks "Choose a download source", choose Install From Local Directory
Complete setup as usual. No Internet access is required.
-- Delete index if exists
IF EXISTS(SELECT TOP 1 1 FROM sys.indexes indexes INNER JOIN sys.objects
objects ON indexes.object_id = objects.object_id WHERE indexes.name
='Your_Index_Name' AND objects.name = 'Your_Table_Name')
BEGIN
PRINT 'DROP INDEX [Your_Index_Name] ON [dbo].[Your_Table_Name]'
DROP INDEX [our_Index_Name] ON [dbo].[Your_Table_Name]
END
GO
The first push should be a:
git push -u origin branchname
That would make sure:
origin
',simple
'Any future git push will, with that default policy, only push the current branch, and only if that branch has an upstream branch with the same name.
that avoid pushing all matching branches (previous default policy), where tons of test branches were pushed even though they aren't ready to be visible on the upstream repo.
If the deletion has not been committed, the command below will restore the deleted file in the working tree.
$ git checkout -- <file>
You can get a list of all the deleted files in the working tree using the command below.
$ git ls-files --deleted
If the deletion has been committed, find the commit where it happened, then recover the file from this commit.
$ git rev-list -n 1 HEAD -- <file>
$ git checkout <commit>^ -- <file>
In case you are looking for the path of the file to recover, the following command will display a summary of all deleted files.
$ git log --diff-filter=D --summary
Wouldn't it be significantly more readable to do a positive match and reject those strings - rather than match the negative to find strings to accept?
/^my/
As several people have already said, this is due to autoboxing.
You could create a utility method to check whether the object's class is Integer
, Double
, etc. But there is no way to know whether an object was created by autoboxing a primitive; once it's boxed, it looks just like an object created explicitly.
So unless you know for sure that your array will never contain a wrapper class without autoboxing, there is no real solution.
My solution is:
import threading, time
def a():
t = threading.currentThread()
while getattr(t, "do_run", True):
print('Do something')
time.sleep(1)
def getThreadByName(name):
threads = threading.enumerate() #Threads list
for thread in threads:
if thread.name == name:
return thread
threading.Thread(target=a, name='228').start() #Init thread
t = getThreadByName('228') #Get thread by name
time.sleep(5)
t.do_run = False #Signal to stop thread
t.join()
AngularJS's module.constant
does not define a constant in the standard sense.
While it stands on its own as a provider registration mechanism, it is best understood in the context of the related module.value
($provide.value
) function. The official documentation states the use case clearly:
Register a value service with the $injector, such as a string, a number, an array, an object or a function. This is short for registering a service where its provider's $get property is a factory function that takes no arguments and returns the value service. That also means it is not possible to inject other services into a value service.
Compare this to the documentation for module.constant
($provide.constant
) which also clearly states the use case (emphasis mine):
Register a constant service with the $injector, such as a string, a number, an array, an object or a function. Like the value, it is not possible to inject other services into a constant. But unlike value, a constant can be injected into a module configuration function (see angular.Module) and it cannot be overridden by an AngularJS decorator.
Therefore, the AngularJS constant
function does not provide a constant in the commonly understood meaning of the term in the field.
That said the restrictions placed on the provided object, together with its earlier availability via the $injector, clearly suggests that the name is used by analogy.
If you wanted an actual constant in an AngularJS application, you would "provide" one the same way you would in any JavaScript program which is
export const p = 3.14159265;
In Angular 2, the same technique is applicable.
Angular 2 applications do not have a configuration phase in the same sense as AngularJS applications. Furthermore, there is no service decorator mechanism (AngularJS Decorator) but this is not particularly surprising given how different they are from each other.
The example of
angular
.module('mainApp.config', [])
.constant('API_ENDPOINT', 'http://127.0.0.1:6666/api/');
is vaguely arbitrary and slightly off-putting because $provide.constant
is being used to specify an object that is incidentally also a constant. You might as well have written
export const apiEndpoint = 'http://127.0.0.1:6666/api/';
for all either can change.
Now the argument for testability, mocking the constant, is diminished because it literally does not change.
One does not mock p.
Of course your application specific semantics might be that your endpoint could change, or your API might have a non-transparent failover mechanism, so it would be reasonable for the API endpoint to change under certain circumstances.
But in that case, providing it as a string literal representation of a single URL to the constant
function would not have worked.
A better argument, and likely one more aligned with the reason for the existence of the AngularJS $provide.constant
function is that, when AngularJS was introduced, JavaScript had no standard module concept. In that case, globals would be used to share values, mutable or immutable, and using globals is problematic.
That said, providing something like this through a framework increases coupling to that framework. It also mixes Angular specific logic with logic that would work in any other system.
This is not to say it is a wrong or harmful approach, but personally, if I want a constant in an Angular 2 application, I will write
export const p = 3.14159265;
just as I would have were I using AngularJS.
The more things change...
I was having a lot of problems to get this working, every single solution I found didn't seem to work.
I realized that I had to set the div display to flex, so basically this is my CSS:
div{
display: flex;
}
div img{
max-height: 100%;
max-width: 100%;
}
There are two main ways you can draw a line, by using a Canvas
or by using a View
.
From the documentation we see that we need to use the following method:
drawLine (float startX, float startY, float stopX, float stopY, Paint paint)
Here is a picture:
The Paint
object just tells Canvas
what color to paint the line, how wide it should be, and so on.
Here is some sample code:
private Paint paint = new Paint();
....
private void init() {
paint.setColor(Color.BLACK);
paint.setStrokeWidth(1f);
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
startX = 20;
startY = 100;
stopX = 140;
stopY = 30;
canvas.drawLine(startX, startY, stopX, stopY, paint);
}
If you only need a straight horizontal or vertical line, then the easiest way may be to just use a View
in your xml layout file. You would do something like this:
<View
android:layout_width="match_parent"
android:layout_height="1dp"
android:background="@android:color/black" />
Here is a picture with two lines (one horizontal and one vertical) to show what it would look like:
And here is the complete xml layout for that:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="10dp"
android:text="TextView1 in vertical linear layout" />
<View
android:layout_width="match_parent"
android:layout_height="1dp"
android:background="@android:color/black" />
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="10dp"
android:text="TextView2 in vertical linear layout" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content" >
<TextView
android:layout_width="100dp"
android:layout_height="100dp"
android:padding="10dp"
android:text="TextView3 in horizontal linear layout" />
<View
android:layout_width="1dp"
android:layout_height="match_parent"
android:background="@android:color/black" />
<TextView
android:layout_width="100dp"
android:layout_height="100dp"
android:padding="10dp"
android:text="TextView4 in horizontal linear layout" />
</LinearLayout>
</LinearLayout>
POJO: If the class can be executed with underlying JDK,without any other external third party libraries support then its called POJO
JavaBean: If class only contains attributes with accessors(setters and getters) those are called javabeans.Java beans generally will not contain any bussiness logic rather those are used for holding some data in it.
All Javabeans are POJOs but all POJO are not Javabeans
To solve the problem there's other option. in file resources/android/xml/network_security_config.xml. insert:
<network-security-config>
<base-config cleartextTrafficPermitted="true">
<trust-anchors>
<certificates src="system" />
</trust-anchors>
</base-config>
<domain-config cleartextTrafficPermitted="true">
<domain>localhost</domain>
<domain includeSubdomains="true">192.168.7.213:8733</domain>
</domain-config>
</network-security-config>
Im my case I´m using IP address then base-config is necessary, but if you have a domain. just add the domain.
I am doing like this in MSSQL
Getting Monthly Data:
SELECT YEAR(DATE_CREATED) [Year], MONTH(DATE_CREATED) [Month],
DATENAME(MONTH,DATE_CREATED) [Month Name], SUM(Num_of_Pictures) [Pictures Count]
FROM pictures_table
GROUP BY YEAR(DATE_CREATED), MONTH(DATE_CREATED),
DATENAME(MONTH, DATE_CREATED)
ORDER BY 1,2
Getting Monthly Data using PIVOT:
SELECT *
FROM (SELECT YEAR(DATE_CREATED) [Year],
DATENAME(MONTH, DATE_CREATED) [Month],
SUM(Num_of_Pictures) [Pictures Count]
FROM pictures_table
GROUP BY YEAR(DATE_CREATED),
DATENAME(MONTH, DATE_CREATED)) AS MontlySalesData
PIVOT( SUM([Pictures Count])
FOR Month IN ([January],[February],[March],[April],[May],
[June],[July],[August],[September],[October],[November],
[December])) AS MNamePivot
Add to top of the code,
#!/usr/bin/python
Then, run the following command on the terminal,
chmod +x yourScriptFile
Mint 18.2 (Cinnamon)
Menu > Keyboard Preferences > Layouts > Options > Switching to another layout:
if (string.IsNullOrWhiteSpace(fileName)) return Content("filename not present");
var path = Path.Combine(your path, your filename);
var stream = new FileStream(path, FileMode.Open);
return File(stream, System.Net.Mime.MediaTypeNames.Application.Octet, fileName);
You could create a user form:
%~dp0 expands to current directory path of the running batch file.
To get clear understanding, let's create a batch file in a directory.
C:\script\test.bat
with contents:
@echo off
echo %~dp0
When you run it from command prompt, you will see this result:
C:\script\
Another java 8 lambda option :
String[] array2 = Arrays.stream(array).map(String::trim).toArray(String[]::new);
And the ugly but optimized version without new array creation
Arrays.stream(array).map(String::trim).toArray(unused -> array);
Original "array" is modified.
Go to enterprise manager, design table, click on your field.
Make a decimal column
In the properties at the bottom there is a precision property
If you're running Charles and trying to build a docker container then you'll most likely get this error.
Make sure to disable Charles (macos) proxy under proxy -> macOS proxy
Charles is an
HTTP proxy / HTTP monitor / Reverse Proxy that enables a developer to view all of the HTTP and SSL / HTTPS traffic between their machine and the Internet.
So anything similar may cause the same issue.
with open('x.py') as f: s = f.read()
***grins***
nan
means "not a number", a float value that you get if you perform a calculation whose result can't be expressed as a number. Any calculations you perform with NaN
will also result in NaN
.
inf
means infinity.
For example:
>>> 2*float("inf")
inf
>>> -2*float("inf")
-inf
>>> float("inf")-float("inf")
nan
I didn't understand it until I played around with it myself, so I figured there would be others who were confused as well. Say you are working on the user whose id == 6
and whose no_of_logins == 30
when you start.
# 1 (bad)
user.no_of_logins += 1
# result: UPDATE user SET no_of_logins = 31 WHERE user.id = 6
# 2 (bad)
user.no_of_logins = user.no_of_logins + 1
# result: UPDATE user SET no_of_logins = 31 WHERE user.id = 6
# 3 (bad)
setattr(user, 'no_of_logins', user.no_of_logins + 1)
# result: UPDATE user SET no_of_logins = 31 WHERE user.id = 6
# 4 (ok)
user.no_of_logins = User.no_of_logins + 1
# result: UPDATE user SET no_of_logins = no_of_logins + 1 WHERE user.id = 6
# 5 (ok)
setattr(user, 'no_of_logins', User.no_of_logins + 1)
# result: UPDATE user SET no_of_logins = no_of_logins + 1 WHERE user.id = 6
By referencing the class instead of the instance, you can get SQLAlchemy to be smarter about incrementing, getting it to happen on the database side instead of the Python side. Doing it within the database is better since it's less vulnerable to data corruption (e.g. two clients attempt to increment at the same time with a net result of only one increment instead of two). I assume it's possible to do the incrementing in Python if you set locks or bump up the isolation level, but why bother if you don't have to?
If you are going to increment twice via code that produces SQL like SET no_of_logins = no_of_logins + 1
, then you will need to commit or at least flush in between increments, or else you will only get one increment in total:
# 6 (bad)
user.no_of_logins = User.no_of_logins + 1
user.no_of_logins = User.no_of_logins + 1
session.commit()
# result: UPDATE user SET no_of_logins = no_of_logins + 1 WHERE user.id = 6
# 7 (ok)
user.no_of_logins = User.no_of_logins + 1
session.flush()
# result: UPDATE user SET no_of_logins = no_of_logins + 1 WHERE user.id = 6
user.no_of_logins = User.no_of_logins + 1
session.commit()
# result: UPDATE user SET no_of_logins = no_of_logins + 1 WHERE user.id = 6
An unwind segue (sometimes called exit segue) can be used to navigate back through push, modal or popover segues (as if you popped the navigation item from the navigation bar, closed the popover or dismissed the modally presented view controller). On top of that you can actually unwind through not only one but a series of push/modal/popover segues, e.g. "go back" multiple steps in your navigation hierarchy with a single unwind action.
When you perform an unwind segue, you need to specify an action, which is an action method of the view controller you want to unwind to.
Objective-C:
- (IBAction)unwindToThisViewController:(UIStoryboardSegue *)unwindSegue
{
}
Swift:
@IBAction func unwindToThisViewController(segue: UIStoryboardSegue) {
}
The name of this action method is used when you create the unwind segue in the storyboard. Furthermore, this method is called just before the unwind segue is performed. You can get the source view controller from the passed UIStoryboardSegue
parameter to interact with the view controller that initiated the segue (e.g. to get the property values of a modal view controller). In this respect, the method has a similar function as the prepareForSegue:
method of UIViewController
.
iOS 8 update: Unwind segues also work with iOS 8's adaptive segues, such as Show and Show Detail.
Let us have a storyboard with a navigation controller and three child view controllers:
From Green View Controller you can unwind (navigate back) to Red View Controller. From Blue you can unwind to Green or to Red via Green. To enable unwinding you must add the special action methods to Red and Green, e.g. here is the action method in Red:
Objective-C:
@implementation RedViewController
- (IBAction)unwindToRed:(UIStoryboardSegue *)unwindSegue
{
}
@end
Swift:
@IBAction func unwindToRed(segue: UIStoryboardSegue) {
}
After the action method has been added, you can define the unwind segue in the storyboard by control-dragging to the Exit icon. Here we want to unwind to Red from Green when the button is pressed:
You must select the action which is defined in the view controller you want to unwind to:
You can also unwind to Red from Blue (which is "two steps away" in the navigation stack). The key is selecting the correct unwind action.
Before the the unwind segue is performed, the action method is called. In the example I defined an unwind segue to Red from both Green and Blue. We can access the source of the unwind in the action method via the UIStoryboardSegue parameter:
Objective-C:
- (IBAction)unwindToRed:(UIStoryboardSegue *)unwindSegue
{
UIViewController* sourceViewController = unwindSegue.sourceViewController;
if ([sourceViewController isKindOfClass:[BlueViewController class]])
{
NSLog(@"Coming from BLUE!");
}
else if ([sourceViewController isKindOfClass:[GreenViewController class]])
{
NSLog(@"Coming from GREEN!");
}
}
Swift:
@IBAction func unwindToRed(unwindSegue: UIStoryboardSegue) {
if let blueViewController = unwindSegue.sourceViewController as? BlueViewController {
println("Coming from BLUE")
}
else if let redViewController = unwindSegue.sourceViewController as? RedViewController {
println("Coming from RED")
}
}
Unwinding also works through a combination of push/modal segues. E.g. if I added another Yellow view controller with a modal segue, we could unwind from Yellow all the way back to Red in a single step:
When you define an unwind segue by control-dragging something to the Exit symbol of a view controller, a new segue appears in the Document Outline:
Selecting the segue and going to the Attributes Inspector reveals the "Identifier" property. Use this to give a unique identifier to your segue:
After this, the unwind segue can be performed from code just like any other segue:
Objective-C:
[self performSegueWithIdentifier:@"UnwindToRedSegueID" sender:self];
Swift:
performSegueWithIdentifier("UnwindToRedSegueID", sender: self)
In my case, same code worked fine on Firefox, but not on Google Chrome. Google Chrome's JavaScript console said:
XMLHttpRequest cannot load http://www.xyz.com/getZipInfo.php?zip=11234.
Origin http://xyz.com is not allowed by Access-Control-Allow-Origin.
Refused to get unsafe header "X-JSON"
I had to drop the www part of the Ajax URL for it to match correctly with the origin URL and it worked fine then.
The easiest way to compute the correct mouse click or mouse move position on a canvas event is to use this little equation:
canvas.addEventListener('click', event =>
{
let bound = canvas.getBoundingClientRect();
let x = event.clientX - bound.left - canvas.clientLeft;
let y = event.clientY - bound.top - canvas.clientTop;
context.fillRect(x, y, 16, 16);
});
If the canvas has padding-left or padding-top, subtract x and y via:
x -= parseFloat(style['padding-left'].replace('px'));
y -= parseFloat(style['padding-top'].replace('px'));
If your start and end datetimes are on different days use TIMEDIFF.
SELECT TIMEDIFF(datetime1,datetime2)
if datetime1 > datetime2 then
SELECT TIMEDIFF("2019-02-20 23:46:00","2019-02-19 23:45:00")
gives: 24:01:00
and datetime1 < datetime2
SELECT TIMEDIFF("2019-02-19 23:45:00","2019-02-20 23:46:00")
gives: -24:01:00
Step 1 : Create two view inside a linear layout
Step 2 : First view must set to android:layout_weight="1"
Step 3 : Second view will automatically putted downwards
<LinearLayout
android:id="@+id/botton_header"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical" >
<View
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1" />
<Button
android:id="@+id/btn_health_advice"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
</LinearLayout>
Cmd.exe
)When the Docker CLI is used from the Windows Cmd.exe
, use %cd%
to mount the current directory:
echo test > test.txt
docker run --rm -v %cd%:/data busybox ls -ls /data/test.txt
When the Docker CLI is used from the Git Bash (MinGW), mounting the current directory may fail due to a POSIX path conversion: Docker mounted volume adds ;C to end of windows path when translating from linux style path.
/
To skip the path conversion, POSIX paths have to be prefixed with the slash (/
) to have leading double slash (//
), including /$(pwd)
touch test.txt
docker run --rm -v /$(pwd):/data busybox ls -la //data/test.txt
Disable the POSIX path conversion in Git Bash (MinGW) by setting MSYS_NO_PATHCONV=1
environment variable at the command level
touch test.txt
MSYS_NO_PATHCONV=1 docker run --rm -v $(pwd):/data busybox ls -la /data/test.txt
or shell (system) level
export MSYS_NO_PATHCONV=1
touch test.txt
docker run --rm -v $(pwd):/data busybox ls -la /data/test.txt
A Primary key is a special kind of index in that:
there can be only one;
it cannot be nullable
it must be unique.
Candidate keys are selected from the set of super keys, the only thing we take care while selecting the candidate key is: It should not have any redundant attribute.
Example of an Employee table: Employee ( Employee ID, FullName, SSN, DeptID )
Candidate Key: are individual columns in a table that qualifies for the uniqueness of all the rows. Here in Employee table EmployeeID & SSN are Candidate keys.
Primary Key: are the columns you choose to maintain uniqueness in a table. Here in Employee table, you can choose either EmployeeID or SSN columns, EmployeeID is a preferable choice, as SSN is a secure value.
Alternate Key: Candidate column other the Primary column, like if EmployeeID is PK then SSN would be the Alternate key.
Super Key: If you add any other column/attribute to a Primary Key then it becomes a super key, like EmployeeID + FullName, is a Super Key.
Composite Key: If a table does not have a single column that qualifies for a Candidate key, then you have to select 2 or more columns to make a row unique. Like if there is no EmployeeID or SSN columns, then you can make FullName + DateOfBirth as Composite primary Key. But still, there can be a narrow chance of duplicate row.
When I had this, problem, the cause was the ordering of the libraries. To fix it, I put libboost_system
last:
g++ mingw/timer1.o -o mingw/timer1.exe -L/usr/local/boost_1_61_0/stage/lib \
-lboost_timer-mgw53-mt-1_61 \
-lboost_chrono-mgw53-mt-1_61 \
-lboost_system-mgw53-mt-1_61
This was on mingw with gcc 5.3 and boost 1.61.0 with a simple timer example.
*::after {
content: none !important;
}
*::before {
content: none !important;
}
_x000D_
getline is storing the entire line at once, which is not what you want. A simple fix is to have three variables and use cin to get them all. C++ will parse automatically at the spaces.
#include <iostream>
using namespace std;
int main() {
string a, b, c;
cin >> a >> b >> c;
//now you have your three words
return 0;
}
I don't know what particular "operation" you're talking about, so I can't help you there, but if it's changing characters, read up on string and indices. The C++ documentation is great. As for using namespace std; versus std:: and other libraries, there's already been a lot said. Try these questions on StackOverflow to start.
The following may help (study the impacts of disable-verity
first):
adb root
adb disable-verity
adb reboot
You can access the first element adding the following code to the highlight
function
$(this).find(".selected td:first").html()
Working Code:JSFIDDLE
Where on earth did you find this syntax? Java Enums are very simple, you just specify the values.
public enum Gender {
MALE,
FEMALE
}
If you want them to be more complex, you can add values to them like this.
public enum Gender {
MALE("Male", 0),
FEMALE("Female", 1);
private String stringValue;
private int intValue;
private Gender(String toString, int value) {
stringValue = toString;
intValue = value;
}
@Override
public String toString() {
return stringValue;
}
}
Then to use the enum, you would do something like this:
Gender me = Gender.MALE
Keeping in mind the points made in @John Woo's comment/link above, this is how I typically would handle it:
SELECT t1.ID, t1.Name
FROM Table1 t1
WHERE NOT EXISTS (
SELECT TOP 1 NULL
FROM Table2 t2
WHERE t1.ID = t2.ID
)
INIT_CWD
property on process.env
. This is what I'm currently working with in my project.const {INIT_CWD} = process.env; // process.env.INIT_CWD
const paths = require(`${INIT_CWD}/config/paths`);
Good Luck...
Yes. In Ruby the not equal to operator is:
!=
You can get a full list of ruby operators here: https://www.tutorialspoint.com/ruby/ruby_operators.htm.
start chrome https://www.google.com/
or start firefox https://www.google.com/
Can JAX-RS do Asynchronous Request like JAX-WS?
Yes, it can surely do use @Async
Can JAX-RS access a web service that is not running on the Java platform, and vice versa?
Yes, it can Do
What does it mean by "REST is particularly useful for limited-profile devices, such as PDAs and mobile phones"?
It is mainly use for public apis it depends on which approach you want to use.
What does it mean by "JAX-RS do not require XML messages or WSDL service–API definitions?
It has its own standards WADL(Web application Development Language) it has http request by which you can access resources they are altogether created by different mindset,In case in Jax-Rs you have to think of exposing resources
How does spring know which polymorphic type to use.
As long as there is only a single implementation of the interface and that implementation is annotated with @Component
with Spring's component scan enabled, Spring framework can find out the (interface, implementation) pair. If component scan is not enabled, then you have to define the bean explicitly in your application-config.xml (or equivalent spring configuration file).
Do I need @Qualifier or @Resource?
Once you have more than one implementation, then you need to qualify each of them and during auto-wiring, you would need to use the @Qualifier
annotation to inject the right implementation, along with @Autowired
annotation. If you are using @Resource (J2EE semantics), then you should specify the bean name using the name
attribute of this annotation.
Why do we autowire the interface and not the implemented class?
Firstly, it is always a good practice to code to interfaces in general. Secondly, in case of spring, you can inject any implementation at runtime. A typical use case is to inject mock implementation during testing stage.
interface IA
{
public void someFunction();
}
class B implements IA
{
public void someFunction()
{
//busy code block
}
public void someBfunc()
{
//doing b things
}
}
class C implements IA
{
public void someFunction()
{
//busy code block
}
public void someCfunc()
{
//doing C things
}
}
class MyRunner
{
@Autowire
@Qualifier("b")
IA worker;
....
worker.someFunction();
}
Your bean configuration should look like this:
<bean id="b" class="B" />
<bean id="c" class="C" />
<bean id="runner" class="MyRunner" />
Alternatively, if you enabled component scan on the package where these are present, then you should qualify each class with @Component
as follows:
interface IA
{
public void someFunction();
}
@Component(value="b")
class B implements IA
{
public void someFunction()
{
//busy code block
}
public void someBfunc()
{
//doing b things
}
}
@Component(value="c")
class C implements IA
{
public void someFunction()
{
//busy code block
}
public void someCfunc()
{
//doing C things
}
}
@Component
class MyRunner
{
@Autowire
@Qualifier("b")
IA worker;
....
worker.someFunction();
}
Then worker
in MyRunner
will be injected with an instance of type B
.
Build.Version is the place go to for this data. Here is a code snippet for how to format it.
public String getAndroidVersion() {
String release = Build.VERSION.RELEASE;
int sdkVersion = Build.VERSION.SDK_INT;
return "Android SDK: " + sdkVersion + " (" + release +")";
}
Looks like this "Android SDK: 19 (4.4.4)"
Much simpler solution:
Get-PSDrive C | Select-Object Used,Free
and for remote computers (needs Powershell Remoting
)
Invoke-Command -ComputerName SRV2 {Get-PSDrive C} | Select-Object PSComputerName,Used,Free
I also ran into this problem. My situation was a little different. I was using 'working sets' to group my projects inside of eclipse. What I had done was attempt to delete a project and received errors while deleting. Ignoring the errors I removed the project from my working set and thus didn't see that I even had the project anymore. When I received my error I didn't think to look through my package explorer with 'projects', opposed to working sets, as my top view. After switching to a top level view of projects I found the project that was half deleted and was able to delete its contents from both my workspace and the hard drive.
I haven't had the error since.
Make the DropDownStyle to DropDownList
stateComboBox.DropDownStyle = ComboBoxStyle.DropDownList;
You can do this:
Update myTable
SET spares = (SELECT CASE WHEN spares IS NULL THEN '' ELSE spares END AS spares WHERE id = 1) + 'some text'
WHERE id = 1
field = field + value does not work when field is null.
Include stdlib.h
in your header, and then call abort();
in any place you want to exit your program. Like this:
switch(varName)
{
case 1:
blah blah;
case 2:
blah blah;
case 3:
abort();
}
When the user enters the switch accepts this and give it to the case 3 where you call the abort
function. It will exit your screen immediately after hitting enter key.
If you'd rather transform your array, then the iterator
parameter of underscore's map
function is also passed the index as a second argument. So:
_.map([1, 4, 2, 66, 444, 9], function(value, index){ return index + ':' + value; });
... returns:
["0:1", "1:4", "2:2", "3:66", "4:444", "5:9"]
if(allPlayers.empty() == false) {
for(int i = allPlayers.size() - 1; i >= 0; i--)
{
if(allPlayers.at(i).getpMoney() <= 0)
allPlayers.erase(allPlayers.at(i));
}
}
This works for me. And Don't need to think about indexes have already erased.
Just for reference, the equivalent statement for MySQL is: IFNull(Column,0).
This statement evaluates as the column value if not null, otherwise it is evaluated as 0.
The default timeout is 900 second. You can specify different timeout.
-T seconds
--timeout=seconds
The default is to retry 20 times. You can specify different tries.
-t number
--tries=number
link: wget man document
There are two ways:
Without LINQ: yourList.Sort();
With LINQ: yourList.OrderBy(x => x).ToList()
You will find more information in: https://www.dotnetperls.com/sort
I recently had to do this to create half decent looking emails for an email client that did not support the CSS necessary. For an HTML only solution I use a wrapping table to provide the padding.
<table border="1" cellspacing="0" cellpadding="0">_x000D_
<tr><td height="5" colspan="3"></td></tr>_x000D_
<tr>_x000D_
<td width="5"></td>_x000D_
<td>_x000D_
This cells padding matches what you want._x000D_
<ul>_x000D_
<li>5px Left, Top, Bottom padding</li>_x000D_
<li>10px on the right</li>_x000D_
</ul> _x000D_
You can then put your table inside this_x000D_
cell with no spacing or padding set. _x000D_
</td>_x000D_
<td width="10"></td>_x000D_
</tr>_x000D_
<tr><td height="5" colspan="3"></td></tr>_x000D_
</table>
_x000D_
As of 2017 you would only do this for old email client support, it's pretty overkill.
You can use XmlDocument. Also some XPath can be useful.
Just a simple example
XmlDocument doc = new XmlDocument();
doc.Load("sample.xml");
XmlElement root = doc.DocumentElement;
XmlNodeList nodes = root.SelectNodes("some_node"); // You can also use XPath here
foreach (XmlNode node in nodes)
{
// use node variable here for your beeds
}
phpinfo()
, press ctrl+f, and type thread
to check the value.php
.php
folder to something else.php
) folder in xampp directory.php.ini
file from default/old php
folder (That you renamed) and paste it into the new php
folder.[if lt IE 8]
means "if lower than IE8" - and thats why it isn't working in IE8.
wahat you want is [if lte IE 8]
which means "if lower than or equal IE8".
I don't think that the accepted answer actually fully solves the problem. You wanted to have a vertical-align: middle
on the table-cells content. But when you add a div inside the table-cell and give it a height the content of that inner DIV will be at the top.
Check this jsfiddle. The overflow:hidden; works fine, but if you shorten the content so that it's only one line, this line won't be centered vertically
The solution is not to add a DIV inside the table-cell but rather outside. Here's the Code:
/* some wrapper */_x000D_
div.d0 {_x000D_
background: grey;_x000D_
width:200px;_x000D_
height: 200px;_x000D_
}_x000D_
_x000D_
div.table {_x000D_
margin: 0 auto; /* just cosmetics */_x000D_
width: 150px;_x000D_
height: 150px;_x000D_
background: #eee;_x000D_
display: table;_x000D_
}_x000D_
_x000D_
div.tablecell {_x000D_
display: table-cell;_x000D_
vertical-align: middle;_x000D_
text-align:center;_x000D_
height: 100%;_x000D_
width: 100%;_x000D_
background: #aaa;_x000D_
}_x000D_
_x000D_
div.outer-div {_x000D_
height: 150px;_x000D_
overflow: hidden;_x000D_
}
_x000D_
<div class="d0">_x000D_
<div class="outer-div">_x000D_
<div class="table">_x000D_
<div class="tablecell">_x000D_
Lorem ipsum _x000D_
<!--dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren,-->_x000D_
</div>_x000D_
</div>_x000D_
</div>_x000D_
</div>
_x000D_
It helps me:
pg_hba.conf
sudo nano /etc/postgresql/9.x/main/pg_hba.conf
and change this line:
Database administrative login by Unix domain socket
local all postgres md5
to
Database administrative login by Unix domain socket
local all postgres trust
Restart the server
sudo service postgresql restart
Login into psql and set password
psql -U postgres
ALTER USER postgres with password 'new password';
pg_hba.conf
and change this line: Database administrative login by Unix domain socket local all postgres trust
to
Database administrative login by Unix domain socket local all postgres md5
sudo service postgresql restart
MySQLi stands for MySQL improved. It's an object-oriented interface to the MySQL bindings which makes things easier to use. It also offers support for prepared statements (which are very useful). If you're on PHP 5 use MySQLi.
You can use colors for text as others mentioned in their answers.
But you can use emojis instead! for example, you can use??
for warning messages and for error messages.
Or simply use these notebooks as a color:
: error message
: warning message
: ok status message
: action message
: canceled status message
: Or anything you like and want to recognize immediately by color
This method also helps you to quickly scan and find logs directly in the source code.
But Linux default emoji font is not colorful by default and you may want to make them colorful, first.
nodeValue is also a standard DOM property you can use:
function showPanel(fieldName) {
var fieldNameElement = document.getElementById(field_name);
if(fieldNameElement.firstChild)
fieldNameElement.firstChild.nodeValue = "New Text";
}
i solve it by using dataType='jsonp' at the place of dataType='json'
I was also getting the same problem, but i uninstalled all updates of java and now it is working very fine....
As others have said, you can use the dependency:analyze goal to find which dependencies are used and declared, used and undeclared, or unused and declared. You may also find dependency:analyze-dep-mgt useful to look for mismatches in your dependencyManagement section.
You can simply remove unwanted direct dependencies from your POM, but if they are introduced by third-party jars, you can use the <exclusions>
tags in a dependency to exclude the third-party jars (see the section titled Dependency Exclusions for details and some discussion). Here is an example excluding commons-logging from the Spring dependency:
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring</artifactId>
<version>2.5.5</version>
<exclusions>
<exclusion>
<groupId>commons-logging</groupId>
<artifactId>commons-logging</artifactId>
</exclusion>
</exclusions>
</dependency>
For a progress bar kind of thing, in Swift 4
I follow these steps:
@IBOutlet var progressBar: UIView!
var progressBarWidth: Int = your value
progressBar.frame.size.width = CGFloat(progressBarWidth)
progressBarWidth += your value
for auto increase the width every time user touches a button. In linux environment:
ip="$(ifconfig eth0 | grep "inet addr:" | awk '{print $2}' | cut -d ':' -f 2)"
or
ip="$(ifconfig eth0 | grep "inet addr:" | awk '{print $2}' | cut -d ':' -f 2)" | echo $ip
example in FreeBSD:
ifconfig re0 | grep -v "inet6" | grep -i "inet" | awk '{print $2}'
If you have more than one IP address configured, you will have more than one IP address in stdout.
I think I found the proper way to do it...
// Create a DOM Text node:
var text_node = document.createTextNode(unescaped_text);
// Get the HTML element where you want to insert the text into:
var elem = document.getElementById('msg_span');
// Optional: clear its old contents
//elem.innerHTML = '';
// Append the text node into it:
elem.appendChild(text_node);
It's really just a coding style. The compiler generates the exact same for both variants.
See also here for the performance question:
Although recently its use is undefined, a common and useful use for the form feed is to separate sections of code vertically, like so: (from http://ergoemacs.org/emacs/emacs_form_feed_section_paging.html)
I use Goto
For x= 1 to 20
If something then goto continue
skip this code
Continue:
Next x
You need to use : "$@"
(WITH the quotes) or "${@}"
(same, but also telling the shell where the variable name starts and ends).
(and do NOT use : $@
, or "$*"
, or $*
).
ex:
#testscript1:
echo "TestScript1 Arguments:"
for an_arg in "$@" ; do
echo "${an_arg}"
done
echo "nb of args: $#"
./testscript2 "$@" #invokes testscript2 with the same arguments we received
I'm not sure I understood your other requirement ( you want to invoke './testscript2' in single quotes?) so here are 2 wild guesses (changing the last line above) :
'./testscript2' "$@" #only makes sense if "/path/to/testscript2" containes spaces?
./testscript2 '"some thing" "another"' "$var" "$var2" #3 args to testscript2
Please give me the exact thing you are trying to do
edit: after his comment saying he attempts tesscript1 "$1" "$2" "$3" "$4" "$5" "$6" to run : salt 'remote host' cmd.run './testscript2 $1 $2 $3 $4 $5 $6'
You have many levels of intermediate: testscript1 on host 1, needs to run "salt", and give it a string launching "testscrit2" with arguments in quotes...
You could maybe "simplify" by having:
#testscript1
#we receive args, we generate a custom script simulating 'testscript2 "$@"'
theargs="'$1'"
shift
for i in "$@" ; do
theargs="${theargs} '$i'"
done
salt 'remote host' cmd.run "./testscript2 ${theargs}"
if THAt doesn't work, then instead of running "testscript2 ${theargs}", replace THE LAST LINE above by
echo "./testscript2 ${theargs}" >/tmp/runtestscript2.$$ #generate custom script locally ($$ is current pid in bash/sh/...)
scp /tmp/runtestscript2.$$ user@remotehost:/tmp/runtestscript2.$$ #copy it to remotehost
salt 'remotehost' cmd.run "./runtestscript2.$$" #the args are inside the custom script!
ssh user@remotehost "rm /tmp/runtestscript2.$$" #delete the remote one
rm /tmp/runtestscript2.$$ #and the local one
DECLARE @test nvarchar(100)
SET @test = 'Foreign Tax Credit - 1997'
SELECT @test, left(@test, charindex('-', @test) - 2) AS LeftString,
right(@test, len(@test) - charindex('-', @test) - 1) AS RightString
You can use LINQ-to-DataSet
with Enumerable.Any
:
String author = "John Grisham";
bool contains = tbl.AsEnumerable().Any(row => author == row.Field<String>("Author"));
Another approach is to use DataTable.Select
:
DataRow[] foundAuthors = tbl.Select("Author = '" + searchAuthor + "'");
if(foundAuthors.Length != 0)
{
// do something...
}
Q: what if we do not know the columns Headers and we want to find if any cell value
PEPSI
exist in any rows'c columns? I can loop it all to find out but is there a better way? –
Yes, you can use this query:
DataColumn[] columns = tbl.Columns.Cast<DataColumn>().ToArray();
bool anyFieldContainsPepsi = tbl.AsEnumerable()
.Any(row => columns.Any(col => row[col].ToString() == "PEPSI"));
As many answers have already pointed out, JSON does not natively have comments. Of course sometimes you want them anyway. For Python, two ways to do that are with commentjson
(#
and //
for Python 2 only) or json_tricks
(#
or //
for Python 2 and Python 3), which has several other features. Disclaimer: I made json_tricks
.
Here is a method. This will not only provide scrollbar container, but will also show the scrollbar even if content isnt enough (as per your requirement). Would also work on Iphone, and android devices as well..
<style>
.scrollholder {
position: relative;
width: 310px; height: 350px;
overflow: auto;
z-index: 1;
}
</style>
<script>
function isTouchDevice() {
try {
document.createEvent("TouchEvent");
return true;
} catch (e) {
return false;
}
}
function touchScroll(id) {
if (isTouchDevice()) { //if touch events exist...
var el = document.getElementById(id);
var scrollStartPos = 0;
document.getElementById(id).addEventListener("touchstart", function (event) {
scrollStartPos = this.scrollTop + event.touches[0].pageY;
event.preventDefault();
}, false);
document.getElementById(id).addEventListener("touchmove", function (event) {
this.scrollTop = scrollStartPos - event.touches[0].pageY;
event.preventDefault();
}, false);
}
}
</script>
<body onload="touchScroll('scrollMe')">
<!-- title -->
<!-- <div class="title" onselectstart="return false">Alarms</div> -->
<div class="scrollholder" id="scrollMe">
</div>
</body>
IE 8 will support the window.navigator.onLine property.
But of course that doesn't help with other browsers or operating systems. I predict other browser vendors will decide to provide that property as well given the importance of knowing online/offline status in Ajax applications.
Until that happens, either XHR or an Image()
or <img>
request can provide something close to the functionality you want.
Update (2014/11/16)
Major browsers now support this property, but your results will vary.
Quote from Mozilla Documentation:
In Chrome and Safari, if the browser is not able to connect to a local area network (LAN) or a router, it is offline; all other conditions return
true
. So while you can assume that the browser is offline when it returns afalse
value, you cannot assume that a true value necessarily means that the browser can access the internet. You could be getting false positives, such as in cases where the computer is running a virtualization software that has virtual ethernet adapters that are always "connected." Therefore, if you really want to determine the online status of the browser, you should develop additional means for checking.In Firefox and Internet Explorer, switching the browser to offline mode sends a
false
value. All other conditions return atrue
value.
Finally found this method:
basename($_SERVER['REQUEST_URI']);
This will return all URLs with page name. (e.g.: index.php?id=1&name=rr&class=10
).
Firstly make sure your API Key is valid and add this into your manifest <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
Here's my maps activity.. there might be some redundant information in it since it's from a larger project I created.
import android.content.Intent;
import android.content.IntentSender;
import android.location.Location;
import android.support.v4.app.FragmentActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.location.LocationListener;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationServices;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;
public class MapsActivity extends FragmentActivity implements
GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener,
LocationListener {
//These variable are initalized here as they need to be used in more than one methid
private double currentLatitude; //lat of user
private double currentLongitude; //long of user
private double latitudeVillageApartmets= 53.385952001750184;
private double longitudeVillageApartments= -6.599087119102478;
public static final String TAG = MapsActivity.class.getSimpleName();
private final static int CONNECTION_FAILURE_RESOLUTION_REQUEST = 9000;
private GoogleMap mMap; // Might be null if Google Play services APK is not available.
private GoogleApiClient mGoogleApiClient;
private LocationRequest mLocationRequest;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
setUpMapIfNeeded();
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
// Create the LocationRequest object
mLocationRequest = LocationRequest.create()
.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY)
.setInterval(10 * 1000) // 10 seconds, in milliseconds
.setFastestInterval(1 * 1000); // 1 second, in milliseconds
}
/*These methods all have to do with the map and wht happens if the activity is paused etc*/
//contains lat and lon of another marker
private void setUpMap() {
MarkerOptions marker = new MarkerOptions().position(new LatLng(latitudeVillageApartmets, longitudeVillageApartments)).title("1"); //create marker
mMap.addMarker(marker); // adding marker
}
//contains your lat and lon
private void handleNewLocation(Location location) {
Log.d(TAG, location.toString());
currentLatitude = location.getLatitude();
currentLongitude = location.getLongitude();
LatLng latLng = new LatLng(currentLatitude, currentLongitude);
MarkerOptions options = new MarkerOptions()
.position(latLng)
.title("You are here");
mMap.addMarker(options);
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom((latLng), 11.0F));
}
@Override
protected void onResume() {
super.onResume();
setUpMapIfNeeded();
mGoogleApiClient.connect();
}
@Override
protected void onPause() {
super.onPause();
if (mGoogleApiClient.isConnected()) {
LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this);
mGoogleApiClient.disconnect();
}
}
private void setUpMapIfNeeded() {
// Do a null check to confirm that we have not already instantiated the map.
if (mMap == null) {
// Try to obtain the map from the SupportMapFragment.
mMap = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map))
.getMap();
// Check if we were successful in obtaining the map.
if (mMap != null) {
setUpMap();
}
}
}
@Override
public void onConnected(Bundle bundle) {
Location location = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
if (location == null) {
LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
}
else {
handleNewLocation(location);
}
}
@Override
public void onConnectionSuspended(int i) {
}
@Override
public void onConnectionFailed(ConnectionResult connectionResult) {
if (connectionResult.hasResolution()) {
try {
// Start an Activity that tries to resolve the error
connectionResult.startResolutionForResult(this, CONNECTION_FAILURE_RESOLUTION_REQUEST);
/*
* Thrown if Google Play services canceled the original
* PendingIntent
*/
} catch (IntentSender.SendIntentException e) {
// Log the error
e.printStackTrace();
}
} else {
/*
* If no resolution is available, display a dialog to the
* user with the error.
*/
Log.i(TAG, "Location services connection failed with code " + connectionResult.getErrorCode());
}
}
@Override
public void onLocationChanged(Location location) {
handleNewLocation(location);
}
}
There's a lot of methods here that are hard to understand but basically all update the map when it's paused etc. There are also connection timeouts etc. Sorry for just posting this, I tried to fix your code but I couldn't figure out what was wrong.
The core problem is what you define line and whether end-on-line character sequence is part of the line or not. UNIX-based editors (such as VIM) or tools (such as Git) use EOL character sequence as line terminator, therefore it's a part of the line. It's similar to use of semicolon (;) in C and Pascal. In C semicolon terminates statements, in Pascal it separates them.
Here's an example of one with dynamic columns and rows with angularJS: http://plnkr.co/edit/0fsRUp?p=preview
An easy solution that works for me with Ubuntu 14.04.
react-native run-android
The emulator (already launched) will return: Unable to download JS Bundle; start again the JS server:
react-native start
Hit Reload JS on the emulator. It worked for me. Hope it will help
If your web application is configured to impersonate a client, then using a trusted connection will potentially have a negative performance impact. This is because each client must use a different connection pool (with the client's credentials).
Most web applications don't use impersonation / delegation, and hence don't have this problem.
See this MSDN article for more information.
Many answers use tens of lines of code, or require adding a new library to the project, but if you use recursion, this is just 4 lines of code.
function merge(current, updates) {_x000D_
for (key of Object.keys(updates)) {_x000D_
if (!current.hasOwnProperty(key) || typeof updates[key] !== 'object') current[key] = updates[key];_x000D_
else merge(current[key], updates[key]);_x000D_
}_x000D_
return current;_x000D_
}_x000D_
console.log(merge({ a: { a: 1 } }, { a: { b: 1 } }));
_x000D_
Arrays handling: The above version overwrites old array values with new ones. If you want it to keep the old array values and add the new ones, just add a else if (current[key] instanceof Array && updates[key] instanceof Array) current[key] = current[key].concat(updates[key])
block above the else
statament and you're all set.
SELECT * FROM (
SELECT * FROM table_name ORDER BY sortable_column DESC
) WHERE ROWNUM = 1;
Let's presume your code also had an #else
statement which defined a null stub function, addressing one of Jon Skeet's points. There's a second important distinction between the two.
Suppose the #if DEBUG
or Conditional
function exists in a DLL which is referenced by your main project executable. Using the #if
, the evaluation of the conditional will be performed with regard to the library's compilation settings. Using the Conditional
attribute, the evaluation of the conditional will be performed with regard to the compilation settings of the invoker.
Got the same problem but didn't found a good solution yet for detecting it automatically . Now im using PsPad (www.pspad.com) for that ;) Works fine
this is my alternative solution, instead of a List of Map, i'm using a Map of List. Tested on tables of 5000 elements, on a remote db, times are around 350ms for eiter method.
private Map<String, List<Object>> resultSetToArrayList(ResultSet rs) throws SQLException {
ResultSetMetaData md = rs.getMetaData();
int columns = md.getColumnCount();
Map<String, List<Object>> map = new HashMap<>(columns);
for (int i = 1; i <= columns; ++i) {
map.put(md.getColumnName(i), new ArrayList<>());
}
while (rs.next()) {
for (int i = 1; i <= columns; ++i) {
map.get(md.getColumnName(i)).add(rs.getObject(i));
}
}
return map;
}
To expand on the accepted answer, I just wanted to provide another reason why real
? user
+ sys
.
Keep in mind that real
represents actual elapsed time, while user
and sys
values represent CPU execution time. As a result, on a multicore system, the user
and/or sys
time (as well as their sum) can actually exceed the real time. For example, on a Java app I'm running for class I get this set of values:
real 1m47.363s
user 2m41.318s
sys 0m4.013s
You can try using jQuery with the Attribute Contains Prefix Selector.
$('[id|=q1_]')
Haven't tested it though.
hope it will work
@Html.DropDownList("accountid", (IEnumerable<SelectListItem>)ViewBag.Accounts, String.Empty, new { @class ="extra-class" })
Here String.Empty
will be the empty as a default selector.
Visual Studio's UserVoice gives a link to generic OrderedDictionary implementation by dotmore.
But if you only need to get key/value pairs by index and don't need to get values by keys, you may use one simple trick. Declare some generic class (I called it ListArray) as follows:
class ListArray<T> : List<T[]> { }
You may also declare it with constructors:
class ListArray<T> : List<T[]>
{
public ListArray() : base() { }
public ListArray(int capacity) : base(capacity) { }
}
For example, you read some key/value pairs from a file and just want to store them in the order they were read so to get them later by index:
ListArray<string> settingsRead = new ListArray<string>();
using (var sr = new StreamReader(myFile))
{
string line;
while ((line = sr.ReadLine()) != null)
{
string[] keyValueStrings = line.Split(separator);
for (int i = 0; i < keyValueStrings.Length; i++)
keyValueStrings[i] = keyValueStrings[i].Trim();
settingsRead.Add(keyValueStrings);
}
}
// Later you get your key/value strings simply by index
string[] myKeyValueStrings = settingsRead[index];
As you may have noticed, you can have not necessarily just pairs of key/value in your ListArray. The item arrays may be of any length, like in jagged array.
Andrey Tarasevich provides the following explanation:
[Minor changes to formatting made. Parenthetical annotations added in square brackets []
].
The whole idea of using 'do/while' version is to make a macro which will expand into a regular statement, not into a compound statement. This is done in order to make the use of function-style macros uniform with the use of ordinary functions in all contexts.
Consider the following code sketch:
if (<condition>) foo(a); else bar(a);
where
foo
andbar
are ordinary functions. Now imagine that you'd like to replace functionfoo
with a macro of the above nature [namedCALL_FUNCS
]:if (<condition>) CALL_FUNCS(a); else bar(a);
Now, if your macro is defined in accordance with the second approach (just
{
and}
) the code will no longer compile, because the 'true' branch ofif
is now represented by a compound statement. And when you put a;
after this compound statement, you finished the wholeif
statement, thus orphaning theelse
branch (hence the compilation error).One way to correct this problem is to remember not to put
;
after macro "invocations":if (<condition>) CALL_FUNCS(a) else bar(a);
This will compile and work as expected, but this is not uniform. The more elegant solution is to make sure that macro expand into a regular statement, not into a compound one. One way to achieve that is to define the macro as follows:
#define CALL_FUNCS(x) \ do { \ func1(x); \ func2(x); \ func3(x); \ } while (0)
Now this code:
if (<condition>) CALL_FUNCS(a); else bar(a);
will compile without any problems.
However, note the small but important difference between my definition of
CALL_FUNCS
and the first version in your message. I didn't put a;
after} while (0)
. Putting a;
at the end of that definition would immediately defeat the entire point of using 'do/while' and make that macro pretty much equivalent to the compound-statement version.I don't know why the author of the code you quoted in your original message put this
;
afterwhile (0)
. In this form both variants are equivalent. The whole idea behind using 'do/while' version is not to include this final;
into the macro (for the reasons that I explained above).
As a complement to other answers note that you can also put the lang
attribute on various HTML tags inside a page.
For example to give a hint to the spellchecker that the input text should be in english:
<input ... spellcheck="true" lang="en"> ...
See: https://developer.mozilla.org/en-US/docs/Web/HTML/Global_attributes/lang
Here is a more modern way of doing this:
name1 : str = input("What's your name? ")
age1 : int = int(input ("how old are you? "))
twentyone : int = 21 - age1
print('Hi, {}, you will be 21 in: {} years'.format(name1, twentyone))
What about npm i -g npm
? Did you try to run this as well?
As you know JBoss is a purely filesystem based installation. To install you simply unzip a file and thats it. Once you install a certain folder structure is created by default and as you run the JBoss instance for the first time, it creates additional folders for runtime operation. For comparison here is the structure of JBoss AS 7 before and after you start for the first time
Before
jboss-as-7
|
|---> standalone
| |----> lib
| |----> configuration
| |----> deployments
|
|---> domain
|....
After
jboss-as-7
|
|---> standalone
| |----> lib
| |----> configuration
| |----> deployments
| |----> tmp
| |----> data
| |----> log
|
|---> domain
|....
As you can see 3 new folders are created (log, data & tmp). These folders can all be deleted without effecting the application deployed in deployments folder unless your application generated Data that's stored in those folders. In development, its ok to delete all these 3 new folders assuming you don't have any need for the logs and data stored in "data" directory.
For production, ITS NOT RECOMMENDED to delete these folders as there maybe application generated data that stores certain state of the application. For ex, in the data folder, the appserver can save critical Tx rollback logs. So contact your JBoss Administrator if you need to delete those folders for any reason in production.
Good luck!
Actually, this too works great.
input[type=submit]{
width: 15px;
position: absolute;
right: 20px;
bottom: 20px;
background: #09c;
color: #fff;
font-family: tahoma,geneva,algerian;
height: 30px;
-webkit-border-radius: 15px;
-moz-border-radius: 15px;
border-radius: 15px;
border: 1px solid #999;
}
The above answers unfortunately don't quite work. In particular, the compile stage does not have access to scope, so you can't customize the field based on dynamic attributes. Using the linking stage seems to offer the most flexibility (in terms of asynchronously creating dom, etc.) The below approach addresses that:
<!-- Usage: -->
<form>
<form-field ng-model="formModel[field.attr]" field="field" ng-repeat="field in fields">
</form>
// directive
angular.module('app')
.directive('formField', function($compile, $parse) {
return {
restrict: 'E',
compile: function(element, attrs) {
var fieldGetter = $parse(attrs.field);
return function (scope, element, attrs) {
var template, field, id;
field = fieldGetter(scope);
template = '..your dom structure here...'
element.replaceWith($compile(template)(scope));
}
}
}
})
I've created a gist with more complete code and a writeup of the approach.
As mentioned by others: git doesn't track folders, only files.
You can ensure a folder exists with these commands (or equivalent logic):
echo "*" > keepthisfolder/.gitignore
git add --force keepthisfolder/.gitignore
git commit -m "adding git ignore file to keepthisfolder"
The existence of the file will mean anyone checking out the repository will have the folder.
The contents of the gitignore file will mean anything in it are ignored
You do not need to not-ignore the .gitignore file itself. It is a rule which would serve no purpose at all once committed.
OR
if you prefer to keep all your ignore definitions in the same place, you can create .gitignore in the root of your project with contents like so:
*.tmp # example, ignore all .tmp files in any folder
path/to/keepthisfolder
path/to/keepthatfolder
and to ensure the folders exist
touch path/to/keepthisfolder/anything
git add --force path/to/keepthisfolder/anything
git commit -m "ensure keepthisfolder exists when checked out"
"anything" can literally be anything. Common used names are .gitignore, .gitkeep, empty.
Want to add an answer here for the sake of completeness.
<a href="tel:1234567">Call 123-4567</a>
Works just fine on most devices. However, on desktops this will appear as a link which does nothing when you click on it so you should consider using CSS to make it conditionally visible only on mobile devices.
Also, you should know that Skype (which is fairly popular) uses a different syntax by default (but can be parametered to use tel:).
<a href="callto:1234567">Call 123-4567</a>
However, I think in latest mobile browsers (I know for sure on Android) now the tel
syntax should offer a popup of available applications that can be used to complete the calling action.
Use This as the solution
This worked for me perfectly..
<div align="center">
<img src="">
</div>
I would add to the accepted answer that you would also want to add the Accept
header to the httpClient
:
httpClient.DefaultRequestHeaders.Accept.Clear();
httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
#include <algorithm>
#include <iostream>
template <typename T>
inline const T&
max_of(const T& a, const T& b) {
return std::max(a, b);
}
template <typename T, typename ...Args>
inline const T&
max_of(const T& a, const T& b, const Args& ...args) {
return max_of(std::max(a, b), args...);
}
int main() {
std::cout << max_of(1, 2, 3, 4, 5) << std::endl;
// Or just use the std library:
std::cout << std::max({1, 2, 3, 4, 5}) << std::endl;
return 0;
}
Another way to make the parser raise the same exception is the following incorrect clause.
SELECT r.name
FROM roles r
WHERE id IN ( SELECT role_id ,
system_user_id
FROM role_members m
WHERE r.id = m.role_id
AND m.system_user_id = intIdSystemUser
)
The nested SELECT
statement in the IN
clause returns two columns, which the parser sees as operands, which is technically correct, since the id column matches values from but one column (role_id) in the result returned by the nested select statement, which is expected to return a list.
For sake of completeness, the correct syntax is as follows.
SELECT r.name
FROM roles r
WHERE id IN ( SELECT role_id
FROM role_members m
WHERE r.id = m.role_id
AND m.system_user_id = intIdSystemUser
)
The stored procedure of which this query is a portion not only parsed, but returned the expected result.
If you would like to check in PHP , then you should do something like :
$query_s =mysql_query("SELECT YOURROWNAME from `YOURTABLENAME` where name = $name");
$ertom=mysql_fetch_array($query_s);
if ('' !== $ertom['YOURROWNAME']) {
//do your action
echo "It was filled";
} else {
echo "it was empty!";
}
The answer that Pablo Santa Cruz gave is correct; however, in case anybody stumbled on this page and wants more clarification, here is a detailed breakdown.
Suppose we have the following tables:
-- t1
id name
1 Tim
2 Marta
-- t2
id name
1 Tim
3 Katarina
An inner join, like this:
SELECT *
FROM `t1`
INNER JOIN `t2` ON `t1`.`id` = `t2`.`id`;
Would get us only records that appear in both tables, like this:
1 Tim 1 Tim
Inner joins don't have a direction (like left or right) because they are explicitly bidirectional - we require a match on both sides.
Outer joins, on the other hand, are for finding records that may not have a match in the other table. As such, you have to specify which side of the join is allowed to have a missing record.
LEFT JOIN
and RIGHT JOIN
are shorthand for LEFT OUTER JOIN
and RIGHT OUTER JOIN
; I will use their full names below to reinforce the concept of outer joins vs inner joins.
A left outer join, like this:
SELECT *
FROM `t1`
LEFT OUTER JOIN `t2` ON `t1`.`id` = `t2`.`id`;
...would get us all the records from the left table regardless of whether or not they have a match in the right table, like this:
1 Tim 1 Tim
2 Marta NULL NULL
A right outer join, like this:
SELECT *
FROM `t1`
RIGHT OUTER JOIN `t2` ON `t1`.`id` = `t2`.`id`;
...would get us all the records from the right table regardless of whether or not they have a match in the left table, like this:
1 Tim 1 Tim
NULL NULL 3 Katarina
A full outer join would give us all records from both tables, whether or not they have a match in the other table, with NULLs on both sides where there is no match. The result would look like this:
1 Tim 1 Tim
2 Marta NULL NULL
NULL NULL 3 Katarina
However, as Pablo Santa Cruz pointed out, MySQL doesn't support this. We can emulate it by doing a UNION of a left join and a right join, like this:
SELECT *
FROM `t1`
LEFT OUTER JOIN `t2` ON `t1`.`id` = `t2`.`id`
UNION
SELECT *
FROM `t1`
RIGHT OUTER JOIN `t2` ON `t1`.`id` = `t2`.`id`;
You can think of a UNION
as meaning "run both of these queries, then stack the results on top of each other"; some of the rows will come from the first query and some from the second.
It should be noted that a UNION
in MySQL will eliminate exact duplicates: Tim would appear in both of the queries here, but the result of the UNION
only lists him once. My database guru colleague feels that this behavior should not be relied upon. So to be more explicit about it, we could add a WHERE
clause to the second query:
SELECT *
FROM `t1`
LEFT OUTER JOIN `t2` ON `t1`.`id` = `t2`.`id`
UNION
SELECT *
FROM `t1`
RIGHT OUTER JOIN `t2` ON `t1`.`id` = `t2`.`id`
WHERE `t1`.`id` IS NULL;
On the other hand, if you wanted to see duplicates for some reason, you could use UNION ALL
.
From JDK 14+ which includes JEP 305 we can do Pattern Matching for instanceof
Patterns basically test that a value has a certain type, and can extract information from the value when it has the matching type.
Before Java 14
if (obj instanceof String) {
String str = (String) obj; // need to declare and cast again the object
.. str.contains(..) ..
}else{
str = ....
}
Java 14 enhancements
if (!(obj instanceof String str)) {
.. str.contains(..) .. // no need to declare str object again with casting
} else {
.. str....
}
We can also combine the type check and other conditions together
if (obj instanceof String str && str.length() > 4) {.. str.contains(..) ..}
The use of pattern matching in instanceof
should reduce the overall number of explicit casts in Java programs.
PS: instanceOf
will only match when the object is not null, then only it can be assigned to str
.
Best way to make drop down list:
grid.Column("PriceType",canSort:true,header: "PriceType",format: @<span>
<span id="[email protected]">@item.PriceTypeDescription</span>
@Html.DropDownList("PriceType"+(int)item.ShoppingCartID,new SelectList(MvcApplication1.Services.ExigoApiContext.CreateODataContext().PriceTypes.Select(s => new { s.PriceTypeID, s.PriceTypeDescription }).AsEnumerable(),"PriceTypeID", "PriceTypeDescription",Convert.ToInt32(item.PriceTypeId)), new { @class = "PriceType",@style="width:120px;display:none",@selectedvalue="selected"})
</span>),
As mentioned in several places, I'm also not able to get the req.session.destroy() function to work correctly.
This is my work around .. seems to do the trick, and still allows req.flash to be used
req.session = {};
If you delete or set req.session = null; , seems then you can't use req.flash
ES6 introduces the new Math.trunc
method. This allows to fix @MarkElliot's answer to make it work for negative numbers too:
var div = Math.trunc(y/x);
var rem = y % x;
Note that Math
methods have the advantage over bitwise operators that they work with numbers over 231.
import os
path = "C:/Documents and Settings/flow_model/"
os.chdir(path)
os.system("flow.exe")
We can sort the list in one of two ways:
1. Using Comparator : When required to use the sort logic in multiple places If you want to use the sorting logic in a single place, then you can write an anonymous inner class as follows, or else extract the comparator and use it in multiple places
Collections.sort(arrayList, new Comparator<ActiveAlarm>() {
public int compare(ActiveAlarm o1, ActiveAlarm o2) {
//Sorts by 'TimeStarted' property
return o1.getTimeStarted()<o2.getTimeStarted()?-1:o1.getTimeStarted()>o2.getTimeStarted()?1:doSecodaryOrderSort(o1,o2);
}
//If 'TimeStarted' property is equal sorts by 'TimeEnded' property
public int doSecodaryOrderSort(ActiveAlarm o1,ActiveAlarm o2) {
return o1.getTimeEnded()<o2.getTimeEnded()?-1:o1.getTimeEnded()>o2.getTimeEnded()?1:0;
}
});
We can have null check for the properties, if we could have used 'Long' instead of 'long'.
2. Using Comparable(natural ordering): If sort algorithm always stick to one property: write a class that implements 'Comparable' and override 'compareTo' method as defined below
class ActiveAlarm implements Comparable<ActiveAlarm>{
public long timeStarted;
public long timeEnded;
private String name = "";
private String description = "";
private String event;
private boolean live = false;
public ActiveAlarm(long timeStarted,long timeEnded) {
this.timeStarted=timeStarted;
this.timeEnded=timeEnded;
}
public long getTimeStarted() {
return timeStarted;
}
public long getTimeEnded() {
return timeEnded;
}
public int compareTo(ActiveAlarm o) {
return timeStarted<o.getTimeStarted()?-1:timeStarted>o.getTimeStarted()?1:doSecodaryOrderSort(o);
}
public int doSecodaryOrderSort(ActiveAlarm o) {
return timeEnded<o.getTimeEnded()?-1:timeEnded>o.getTimeEnded()?1:0;
}
}
call sort method to sort based on natural ordering
Collections.sort(list);
String withoutQuotes_line1 = line1.replace("\"", "");
have a look here
Fairly simple process I am using SCSS obviously but you don't have to as it's just CSS in the end!
<span class="menu">Menu</span>
.menu {
position: relative;
text-decoration: none;
font-weight: 400;
color: blue;
transition: all .35s ease;
&::before {
content: "";
position: absolute;
width: 100%;
height: 2px;
bottom: 0;
left: 0;
background-color: yellow;
visibility: hidden;
-webkit-transform: scaleX(0);
transform: scaleX(0);
-webkit-transition: all 0.3s ease-in-out 0s;
transition: all 0.3s ease-in-out 0s;
}
&:hover {
color: yellow;
&::before {
visibility: visible;
-webkit-transform: scaleX(1);
transform: scaleX(1);
}
}
}
Try GACView if you have a fear of command prompts.
You have not set the PATH properly in DOS.You need to point the path to where the gacutil resides to use it in DOS.
You receive this error because in C language you are not allowed to use initializers with variable length arrays. The error message you are getting basically says it all.
6.7.8 Initialization
...
3 The type of the entity to be initialized shall be an array of unknown size or an object type that is not a variable length array type.
You can't add a Button to an empty list without creating a new instance of that Button. You are missing the
Button newButton = new Button();
in your code plus get rid of the .Capacity
Testing time is probably more closely correlated to feature scope than development time. I'd also argue (perhaps controversially) that testing time is correlated to the skill of your development team.
For a 6-to-9 month development effort, I demand a absolute minimum of 2 weeks testing time, performed by actual testers (not the development team) who are well-versed in the software they will be testing (i.e., 2 weeks does not include ramp-up time). This is for a project that has ~5 developers.
The loop in your code is only an over-simplified example, right?
It would be better to create the PreparedStatement
only once, and re-use it over and over again in the loop.
In situations where that is not possible (because it complicated the program flow too much), it is still beneficial to use a PreparedStatement
, even if you use it only once, because the server-side of the work (parsing the SQL and caching the execution plan), will still be reduced.
To address the situation that you want to re-use the Java-side PreparedStatement
, some JDBC drivers (such as Oracle) have a caching feature: If you create a PreparedStatement
for the same SQL on the same connection, it will give you the same (cached) instance.
About multi-threading: I do not think JDBC connections can be shared across multiple threads (i.e. used concurrently by multiple threads) anyway. Every thread should get his own connection from the pool, use it, and return it to the pool again.
The solution above does not work in all InputBox-Cancel cases. Most notably, it does not work if you have to InputBox a Range.
For example, try the following InputBox for defining a custom range ('sRange', type:=8, requires Set + Application.InputBox) and you will get an error upon pressing Cancel:
Sub Cancel_Handler_WRONG()
Set sRange = Application.InputBox("Input custom range", _
"Cancel-press test", Selection.Address, Type:=8)
If StrPtr(sRange) = 0 Then 'I also tried with sRange.address and vbNullString
MsgBox ("Cancel pressed!")
Exit Sub
End If
MsgBox ("Your custom range is " & sRange.Address)
End Sub
The only thing that works, in this case, is an "On Error GoTo ErrorHandler" statement before the InputBox + ErrorHandler at the end:
Sub Cancel_Handler_OK()
On Error GoTo ErrorHandler
Set sRange = Application.InputBox("Input custom range", _
"Cancel-press test", Selection.Address, Type:=8)
MsgBox ("Your custom range is " & sRange.Address)
Exit Sub
ErrorHandler:
MsgBox ("Cancel pressed")
End Sub
So, the question is how to detect either an error or StrPtr()=0 with an If statement?
For me everything else was almost ok, but somehow my project settings changed & iisExpress was getting used instead of IISLocal. When I changed & pointed to the virtual directory (in IISLocal), it stared working perfectly again.
Source code, Assembly code, Machine code, Object code, Byte code, Executable file and Library file.
All these terms are often very confusing for most people for the fact that they think they are mutually exclusive. See the diagram to understand their relations. The description of each term is given below.
Instructions in human readable (programming) language
Instructions written in a high level (programming) language
e.g., C, C++ and Java programs
Instructions written in an assembly language (kind of low-level programming language).
As the first step of the compilation process, high-level code is converted into this form. It is the assembly code which is then being converted into actual machine code. On most systems, these two steps are performed automatically as a part of the compilation process.
e.g., program.asm
The product of a compilation process. It may be in the form of machine code or byte code.
e.g., file.o
Instructions in machine language.
e.g., a.out
Instruction in an intermediate form which can be executed by an interpreter such as JVM.
e.g., Java class file
The product of linking proccess. They are machine code which can be directly executed by the CPU.
e.g., an .exe file.
Note that in some contexts a file containing byte-code or scripting language instructions may also be considered executable.
Some code is compiled into this form for different reasons such as re-usability and later used by executable files.
You should be able to use Windows "UNC" paths with robocopy. For example:
robocopy \\myServer\myFolder\myFile.txt \\myOtherServer\myOtherFolder
Robocopy has the ability to recover from certain types of network hiccups automatically.
Try the following function implemented in Swift 3.0 and above
func delayWithSeconds(_ seconds: Double, completion: @escaping () -> ()) {
DispatchQueue.main.asyncAfter(deadline: .now() + seconds) {
completion()
}
}
Usage
delayWithSeconds(1) {
//Do something
}
var window = new MyWindow();
for center of the screen use:
window.WindowStartupLocation = System.Windows.WindowStartupLocation.CenterScreen;
for center of the parent window use:
window.WindowStartupLocation = System.Windows.WindowStartupLocation.CenterOwner;
You can do this in a try and catch block:
try:
if val is None:
print("null")
except NameError:
# throw an exception or do something else
Use set or select
SET @counter := 100;
SELECT @variable_name := value;
example :
SELECT @price := MAX(product.price)
FROM product
You're mixing the parts together instead of separating them cleanly.
printf '\e[1;34m%-6s\e[m' "This is text"
Basically, put the fixed stuff in the format and the variable stuff in the parameters.
This depends on what content do you have. You need to initialize your requestMessage.Content
property with new HttpContent. For example:
...
// Add request body
if (isPostRequest)
{
requestMessage.Content = new ByteArrayContent(content);
}
...
where content
is your encoded content. You also should include correct Content-type header.
Oh, it can be even nicer (from this answer):
requestMessage.Content = new StringContent("{\"name\":\"John Doe\",\"age\":33}", Encoding.UTF8, "application/json");
There's a nodejs tool which supports json schema v4 at https://github.com/krg7880/json-schema-generator
It works either as a command line tool, or as a nodejs library:
var jsonSchemaGenerator = require('json-schema-generator'),
obj = { some: { object: true } },
schemaObj;
schemaObj = jsonSchemaGenerator(json);
Based on Ahmed's answer, after some cleaning up and generalization, including the other "Find" parameters, so we can use this function in any situation:
'Uses Range.Find to get a range of all find results within a worksheet
' Same as Find All from search dialog box
'
Function FindAll(rng As Range, What As Variant, Optional LookIn As XlFindLookIn = xlValues, Optional LookAt As XlLookAt = xlWhole, Optional SearchOrder As XlSearchOrder = xlByColumns, Optional SearchDirection As XlSearchDirection = xlNext, Optional MatchCase As Boolean = False, Optional MatchByte As Boolean = False, Optional SearchFormat As Boolean = False) As Range
Dim SearchResult As Range
Dim firstMatch As String
With rng
Set SearchResult = .Find(What, , LookIn, LookAt, SearchOrder, SearchDirection, MatchCase, MatchByte, SearchFormat)
If Not SearchResult Is Nothing Then
firstMatch = SearchResult.Address
Do
If FindAll Is Nothing Then
Set FindAll = SearchResult
Else
Set FindAll = Union(FindAll, SearchResult)
End If
Set SearchResult = .FindNext(SearchResult)
Loop While Not SearchResult Is Nothing And SearchResult.Address <> firstMatch
End If
End With
End Function
To do a cross server query, check out the system stored procedure: sp_addlinkedserver in the help files.
Once the server is linked you can run a query against it.
So let me see, we want to show adam and eve there's some forbidden fruit in a tree, adn we 'd like a way to prevent them from eating...
How about having an angel with a flaming sword?
Might sound naive, and I dunno what your application does actually, but what about the extensive use of includes?
For the legitimate user, is all the software that should be visible or only parts of it? Because you could obfuscate and give a copy of source code to legitimate
You could wrap the php in a container like Phalanger (.NET)
Perhaps your concerned with external theft, meaning your code freely visible over the web as customers uses it. This could be worth investing in a cheap web site hosting, for $50 a year, registering your legit customers with a serial in their code and have your app posting info to your web site regularly. At least, you'd detect when code has been compromised. You could push it with a self destruct after n days, giving you enough time to contact your customer and change the serial. This could be the only obfuscated include() of the whole code
No. C++ and Java both disallow overloading on a functions's return type. The reason is that overloading on return-type can be confusing (it can be hard for developers to predict which overload will be called). In fact, there are those who argue that any overloading can be confusing in this respect and recommend against it, but even those who favor overloading seem to agree that this particular form is too confusing.
The actual server permissions will not matter at this point; all looks ok.
SQL Server itself needs folder permissions.
depending on your version, you can add SERVERNAME$MSSQLSERVER permissions to touch your folder. Othewise, it has to be in the default BACKUP directory (either where you installed it or default to c:\programfiles(x)\MSSQL\BACKUP.
ADO Recordset has .State
property, you can check if its value is adStateClosed
or adStateOpen
If Not (rs Is Nothing) Then
If (rs.State And adStateOpen) = adStateOpen Then rs.Close
Set rs = Nothing
End If
Edit;
The reason not to check .State
against 1 or 0 is because even if it works 99.99% of the time, it is still possible to have other flags set which will cause the If statement fail the adStateOpen
check.
Edit2:
For Late binding without the ActiveX Data Objects referenced, you have few options. Use the value of adStateOpen constant from ObjectStateEnum
If Not (rs Is Nothing) Then
If (rs.State And 1) = 1 Then rs.Close
Set rs = Nothing
End If
Or you can define the constant yourself to make your code more readable (defining them all for a good example.)
Const adStateClosed As Long = 0 'Indicates that the object is closed.
Const adStateOpen As Long = 1 'Indicates that the object is open.
Const adStateConnecting As Long = 2 'Indicates that the object is connecting.
Const adStateExecuting As Long = 4 'Indicates that the object is executing a command.
Const adStateFetching As Long = 8 'Indicates that the rows of the object are being retrieved.
[...]
If Not (rs Is Nothing) Then
' ex. If (0001 And 0001) = 0001 (only open flag) -> true
' ex. If (1001 And 0001) = 0001 (open and retrieve) -> true
' This second example means it is open, but its value is not 1
' and If rs.State = 1 -> false, even though it is open
If (rs.State And adStateOpen) = adStateOpen Then
rs.Close
End If
Set rs = Nothing
End If
You just need to perform a selector with a delay - (0 seconds works).
override func viewDidLoad() {
super.viewDidLoad()
perform(#selector(presentExampleController), with: nil, afterDelay: 0)
}
@objc private func presentExampleController() {
let exampleStoryboard = UIStoryboard(named: "example", bundle: nil)
let exampleVC = storyboard.instantiateViewController(withIdentifier: "ExampleVC") as! ExampleVC
present(exampleVC, animated: true)
}
The double space generally works well. However, sometimes the lacking newline in the PDF still occurs to me when using four pound sign sub titles #### in Jupyter Notebook, as the next paragraph is put into the subtitle as a single paragraph. No amount of double spaces and returns fixed this, until I created a notebook copy 'v. PDF' and started using a single backslash '\' which also indents the next paragraph nicely:
#### 1.1 My Subtitle \
1.1 My Subtitle
Next paragraph text.
An alternative to this, is to upgrade the level of your four # titles to three # titles, etc. up the title chain, which will remove the next paragraph indent and format the indent of the title itself (#### My Subtitle ---> ### My Subtitle).
### My Subtitle
1.1 My Subtitle
Next paragraph text.
TL;DR
You should use FLUSH PRIVILEGES;
only if you modify the grant tables directly using statements such as INSERT
, UPDATE
, or DELETE
.