On Xiaomi Mi5s with MIUI8.3 (Android 6) Xiaomi.EU Rom:
Settings/ Other Settings / Developer Options / Switch on: Allow USB Debug, Allow USB install and Allow USB Debug (Security options)
{Sorry for the translation, my device has spanish}
Faced similar issue, and here is the solution
Example :
In elasticsearch.yml add the below properties
cluster.name: production
node.name: node1
network.bind_host: 10.0.1.22
network.host: 0.0.0.0
transport.tcp.port: 9300
Add the following in Java Elastic API for Bulk Push (just a code snippet). For IP Address add public IP address of elastic search machine
Client client;
BulkRequestBuilder requestBuilder;
try {
client = TransportClient.builder().settings(Settings.builder().put("cluster.name", "production").put("node.name","node1")).build().addTransportAddress(
new InetSocketTransportAddress(InetAddress.getByName(""), 9300));
requestBuilder = (client).prepareBulk();
}
catch (Exception e) {
}
Open the Firewall ports for 9200,9300
You can simply type:
string filePath = Sysem.Configuration.ConfigurationManager.AppSettings[key.ToString()];
because key
is an object and AppSettings
takes a string
Perhaps you should look at adding a Settings File. (e.g. App.Settings) Creating this file will allow you to do the following:
string mysetting = App.Default.MySetting;
App.Default.MySetting = "my new setting";
This means you can edit and then change items, where the items are strongly typed, and best of all... you don't have to touch any xml before you deploy!
The result is a Application or User contextual setting.
Have a look in the "add new item" menu for the setting file.
Expanding on Adis H's example to include the null case (got bit on this one)
Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
if (config.AppSettings.Settings["HostName"] != null)
config.AppSettings.Settings["HostName"].Value = hostName;
else
config.AppSettings.Settings.Add("HostName", hostName);
config.Save(ConfigurationSaveMode.Modified);
ConfigurationManager.RefreshSection("appSettings");
If your settings file is in a web app, they will be in teh web.config file (right below your project. If they are in any other type of project, they will be in the app.config file (also below your project).
Edit
As is pointed out in the comments: your design time application settings are in an app.config file for applications other than web applications. When you build, the app.config file is copied to the output directory, and will be named yourexename.exe.config. At runtime, only the file named yourexename.exe.config will be read.
sorry for late answer but may be my code may help u.
I placed 3 buttons on the winform surface. button1 & 2 will set different value and button3 will retrieve current value. so when run my code first add the reference System.configuration
and click on first button and then click on 3rd button to see what value has been set. next time again click on second & 3rd button to see again what value has been set after change.
so here is the code.
using System.Configuration;
private void button1_Click(object sender, EventArgs e)
{
Configuration config = ConfigurationManager.OpenExeConfiguration(Application.ExecutablePath);
config.AppSettings.Settings.Remove("DBServerName");
config.AppSettings.Settings.Add("DBServerName", "FirstAddedValue1");
config.Save(ConfigurationSaveMode.Modified);
}
private void button2_Click(object sender, EventArgs e)
{
Configuration config = ConfigurationManager.OpenExeConfiguration(Application.ExecutablePath);
config.AppSettings.Settings.Remove("DBServerName");
config.AppSettings.Settings.Add("DBServerName", "SecondAddedValue1");
config.Save(ConfigurationSaveMode.Modified);
}
private void button3_Click(object sender, EventArgs e)
{
Configuration config = ConfigurationManager.OpenExeConfiguration(Application.ExecutablePath);
MessageBox.Show(config.AppSettings.Settings["DBServerName"].Value);
}
The following can be used to test for the existence of a file, and then to delete it.
Dim aFile As String
aFile = "c:\file_to_delete.txt"
If Len(Dir$(aFile)) > 0 Then
Kill aFile
End If
try
block should be around open. Not around prompt.
while True:
prompt = input("\n Hello to Sudoku valitator,"
"\n \n Please type in the path to your file and press 'Enter': ")
try:
sudoku = open(prompt, 'r').readlines()
except FileNotFoundError:
print("Wrong file or file path")
else:
break
Try this too in addition to MahmoudS comments. Change the maven compiler source and target in your pom.xml to the java version which you are using. Say 1.7 for jdk7
<maven.compiler.source>1.7</maven.compiler.source>
<maven.compiler.target>1.7</maven.compiler.target>
This is a nice tutorial:
http://android-developers.blogspot.de/2009/05/painless-threading.html
Or this for the UI thread:
http://developer.android.com/guide/faq/commontasks.html#threading
Or here a very practical one:
http://www.androidacademy.com/1-tutorials/43-hands-on/115-threading-with-android-part1
and another one about procceses and threads
http://developer.android.com/guide/components/processes-and-threads.html
I found a solution for my problem while writing my question !
Going into my remote session i tried two key combinations, and it solved the problem on my Desktop : Alt+Enter and Ctrl+Enter (i don't know which one solved the problem though)
I tried to reproduce the problem, but i couldn't... but i'm almost sure it's one of the key combinations described in the question above (since i experienced this problem several times)
So it seems the problem comes from the use of RDP (windows7 and 8)
Update 2017: Problem occurs on Windows 10 aswell.
Also since Java 7, one line with java.nio.file.Files:
Files.write(new File(filePath).toPath(), data);
Where data is your byte[] and filePath is a String. You can also add multiple file open options with the StandardOpenOptions class. Add throws or surround with try/catch.
To extend further this topic. In case you want to add Font Awesome 5 icons you need to add some extra CSS.
Icons by default have classes svg-inline--fa
and fa-w-*
.
There are also modifier classes like fa-lg
, fa-rotate-*
and other. You need to check svg-with-js.css
file and find proper CSS for that.
You need to add your own color to css icon otherwise it will be black by default, for example fill='%23f00'
where %23
is encoded #
.
h1::before{_x000D_
_x000D_
/* svg-inline--fa */_x000D_
display:inline-block;_x000D_
font-size:inherit;_x000D_
height:1em;_x000D_
overflow:visible;_x000D_
vertical-align:-.125em;_x000D_
_x000D_
/* fa-w-14 */_x000D_
width:.875em;_x000D_
_x000D_
/* Icon */_x000D_
content:url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 448 512'%3E%3Cpath fill='%23f00' d='M400 256H152V152.9c0-39.6 31.7-72.5 71.3-72.9 40-.4 72.7 32.1 72.7 72v16c0 13.3 10.7 24 24 24h32c13.3 0 24-10.7 24-24v-16C376 68 307.5-.3 223.5 0 139.5.3 72 69.5 72 153.5V256H48c-26.5 0-48 21.5-48 48v160c0 26.5 21.5 48 48 48h352c26.5 0 48-21.5 48-48V304c0-26.5-21.5-48-48-48zM264 408c0 22.1-17.9 40-40 40s-40-17.9-40-40v-48c0-22.1 17.9-40 40-40s40 17.9 40 40v48z'%3E%3C/path%3E%3C/svg%3E");_x000D_
_x000D_
/* Margin */_x000D_
margin-right:.75rem;_x000D_
}
_x000D_
<h1>Lorem Ipsum</h1>
_x000D_
What gives? It works. Just ignore it:
@SuppressWarnings("unchecked")
No, you cannot parameterize it. I'd however rather use a List<Map<K, V>>
instead.
List<Map<String, String>> listOfMaps = new ArrayList<Map<String, String>>();
To learn more about collections and maps, have a look at this tutorial.
You can try something like this
var access_token = driver.findElement(webdriver.By.name("AccToken"))
var access_token_getTextFunction = function() {
access_token.getText().then(function(value) {
console.log(value);
return value;
});
}
Than you can call this function where you want to get the value..
As a newbie, I faced the same 'problem'.
In newbie terms :
when you call plot()
, the graph window gets the focus and you cannot enter further commands into R. That is when you conclude that you must close the graph window to return to R.
However, some commands, like identify()
, act on open/active graph windows.
When identify()
cannot find an open/active graph window, it gives this error message.
However, you can simply click on the R window without closing the graph window. Then you can type more commands at the R prompt, like identify()
etc.
You just need to add 'table-layout: fixed;'
.table {
display: table;
height: 100px;
width: 100%;
table-layout: fixed;
}
Yahoo is very easy to use and provides customized data. Use the following page to learn more.
finance.yahoo.com/d/quotes.csv?s=AAPL+GOOG+MSFT=pder=.csv
WARNING - there are a few tutorials out there on the web that show you how to do this, but the region where you put in the stock symbols causes an error if you use it as posted. You will get a "MISSING FORMAT VALUE". The tutorials I found omits the commentary around GOOG.
Example URL for GOOG: http://download.finance.yahoo.com/d/quotes.csv?s=%40%5EDJI,GOOG&f=nsl1op&e=.csv
CASE - 1
Using array.filter()
We can get an array of objects which will match with our condition.
see the working example.
var questions = [
{id: 1, question: "Do you feel a connection to a higher source and have a sense of comfort knowing that you are part of something greater than yourself?", category: "Spiritual", subs: []},
{id: 2, question: "Do you feel you are free of unhealthy behavior that impacts your overall well-being?", category: "Habits", subs: []},
{id: 3, question: "1 Do you feel you have healthy and fulfilling relationships?", category: "Relationships", subs: []},
{id: 3, question: "2 Do you feel you have healthy and fulfilling relationships?", category: "Relationships", subs: []},
{id: 3, question: "3 Do you feel you have healthy and fulfilling relationships?", category: "Relationships", subs: []},
{id: 4, question: "Do you feel you have a sense of purpose and that you have a positive outlook about yourself and life?", category: "Emotional Well-being", subs: []},
{id: 5, question: "Do you feel you have a healthy diet and that you are fueling your body for optimal health? ", category: "Eating Habits ", subs: []},
{id: 6, question: "Do you feel that you get enough rest and that your stress level is healthy?", category: "Relaxation ", subs: []},
{id: 7, question: "Do you feel you get enough physical activity for optimal health?", category: "Exercise ", subs: []},
{id: 8, question: "Do you feel you practice self-care and go to the doctor regularly?", category: "Medical Maintenance", subs: []},
{id: 9, question: "Do you feel satisfied with your income and economic stability?", category: "Financial", subs: []},
{id: 10, question: "1 Do you feel you do fun things and laugh enough in your life?", category: "Play", subs: []},
{id: 10, question: "2 Do you feel you do fun things and laugh enough in your life?", category: "Play", subs: []},
{id: 11, question: "Do you feel you have a healthy sense of balance in this area of your life?", category: "Work-life Balance", subs: []},
{id: 12, question: "Do you feel a sense of peace and contentment in your home? ", category: "Home Environment", subs: []},
{id: 13, question: "Do you feel that you are challenged and growing as a person?", category: "Intellectual Wellbeing", subs: []},
{id: 14, question: "Do you feel content with what you see when you look in the mirror?", category: "Self-image", subs: []},
{id: 15, question: "Do you feel engaged at work and a sense of fulfillment with your job?", category: "Work Satisfaction", subs: []}
];
function filter(){
console.clear();
var filter_id = document.getElementById("filter").value;
var filter_array = questions.filter(x => x.id == filter_id);
console.log(filter_array);
}
_x000D_
button {
background: #0095ff;
color: white;
border: none;
border-radius: 3px;
padding: 8px;
cursor: pointer;
}
input {
padding: 8px;
}
_x000D_
<div>
<label for="filter"></label>
<input id="filter" type="number" name="filter" placeholder="Enter id which you want to filter">
<button onclick="filter()">Filter</button>
</div>
_x000D_
CASE - 2
Using array.find()
we can get first matched item and break the iteration.
var questions = [
{id: 1, question: "Do you feel a connection to a higher source and have a sense of comfort knowing that you are part of something greater than yourself?", category: "Spiritual", subs: []},
{id: 2, question: "Do you feel you are free of unhealthy behavior that impacts your overall well-being?", category: "Habits", subs: []},
{id: 3, question: "1 Do you feel you have healthy and fulfilling relationships?", category: "Relationships", subs: []},
{id: 3, question: "2 Do you feel you have healthy and fulfilling relationships?", category: "Relationships", subs: []},
{id: 3, question: "3 Do you feel you have healthy and fulfilling relationships?", category: "Relationships", subs: []},
{id: 4, question: "Do you feel you have a sense of purpose and that you have a positive outlook about yourself and life?", category: "Emotional Well-being", subs: []},
{id: 5, question: "Do you feel you have a healthy diet and that you are fueling your body for optimal health? ", category: "Eating Habits ", subs: []},
{id: 6, question: "Do you feel that you get enough rest and that your stress level is healthy?", category: "Relaxation ", subs: []},
{id: 7, question: "Do you feel you get enough physical activity for optimal health?", category: "Exercise ", subs: []},
{id: 8, question: "Do you feel you practice self-care and go to the doctor regularly?", category: "Medical Maintenance", subs: []},
{id: 9, question: "Do you feel satisfied with your income and economic stability?", category: "Financial", subs: []},
{id: 10, question: "1 Do you feel you do fun things and laugh enough in your life?", category: "Play", subs: []},
{id: 10, question: "2 Do you feel you do fun things and laugh enough in your life?", category: "Play", subs: []},
{id: 11, question: "Do you feel you have a healthy sense of balance in this area of your life?", category: "Work-life Balance", subs: []},
{id: 12, question: "Do you feel a sense of peace and contentment in your home? ", category: "Home Environment", subs: []},
{id: 13, question: "Do you feel that you are challenged and growing as a person?", category: "Intellectual Wellbeing", subs: []},
{id: 14, question: "Do you feel content with what you see when you look in the mirror?", category: "Self-image", subs: []},
{id: 15, question: "Do you feel engaged at work and a sense of fulfillment with your job?", category: "Work Satisfaction", subs: []}
];
function find(){
console.clear();
var find_id = document.getElementById("find").value;
var find_object = questions.find(x => x.id == find_id);
console.log(find_object);
}
_x000D_
button {
background: #0095ff;
color: white;
border: none;
border-radius: 3px;
padding: 8px;
cursor: pointer;
}
input {
padding: 8px;
width: 200px;
}
_x000D_
<div>
<label for="find"></label>
<input id="find" type="number" name="find" placeholder="Enter id which you want to find">
<button onclick="find()">Find</button>
</div>
_x000D_
Compilating answers here and there, here's a complete set of arr tools to get the work done:
Function getArraySize(arr As Variant)
' returns array size for a n dimention array
' usage result(k) = size of the k-th dimension
Dim ndims As Long
Dim arrsize() As Variant
ndims = getDimensions(arr)
ReDim arrsize(ndims - 1)
For i = 1 To ndims
arrsize(i - 1) = getDimSize(arr, i)
Next i
getArraySize = arrsize
End Function
Function getDimSize(arr As Variant, dimension As Integer)
' returns size for the given dimension number
getDimSize = UBound(arr, dimension) - LBound(arr, dimension) + 1
End Function
Function getDimensions(arr As Variant) As Long
' returns number of dimension in an array (ex. sheet range = 2 dimensions)
On Error GoTo Err
Dim i As Long
Dim tmp As Long
i = 0
Do While True
i = i + 1
tmp = UBound(arr, i)
Loop
Err:
getDimensions = i - 1
End Function
Aspect-oriented programming lets you trap assignments or fetches and attach intercepting logic to them, which I propose is the right way to solve the problem. (The issue of whether they should be public or protected or package-protected is orthogonal.)
Thus you start out with unintercepted fields with the right access qualifier. As your program requirements grow you attach logic to perhaps validate, make a copy of the object being returned, etc.
The getter/setter philosophy imposes costs on a large number of simple cases where they are not needed.
Whether aspect-style is cleaner or not is somewhat qualitative. I would find it easy to see just the variables in a class and view the logic separately. In fact, the raison d'etre for Apect-oriented programming is that many concerns are cross-cutting and compartmentalizing them in the class body itself is not ideal (logging being an example -- if you want to log all gets Java wants you to write a whole bunch of getters and keeping them in sync but AspectJ allows you a one-liner).
The issue of IDE is a red-herring. It is not so much the typing as it is the reading and visual pollution that arises from get/sets.
Annotations seem similar to aspect-oriented programming at first sight however they require you to exhaustively enumerate pointcuts by attaching annotations, as opposed to a concise wild-card-like pointcut specification in AspectJ.
I hope awareness of AspectJ prevents people from prematurely settling on dynamic languages.
in google colabs if this is your first time,
from google.colab import drive
drive.mount('/content/drive')
run these codes and go through the outputlink then past the pass-prase to the box
when you copy you can copy as follows, go to file right click and copy the path ***don't forget to remove " /content "
f = open("drive/My Drive/RES/dimeric_force_field/Test/python_read/cropped.pdb", "r")
For those of you who figured out that many/most of the ios::fmtflags
don't work with std::stringstream
yet like the template idea that Kornel posted way back when, the following works and is relatively clean:
#include <iomanip>
#include <sstream>
template< typename T >
std::string hexify(T i)
{
std::stringbuf buf;
std::ostream os(&buf);
os << "0x" << std::setfill('0') << std::setw(sizeof(T) * 2)
<< std::hex << i;
return buf.str().c_str();
}
int someNumber = 314159265;
std::string hexified = hexify< int >(someNumber);
For python, try clicking on the "Python X.X" button on the left side of the bottom status bar and changing it to different values.
This is the only thing that worked for me.
Explanation from the Preshing on Programming blog:
It’s handy when you have two related operations which you’d like to execute as a pair, with a block of code in between. The classic example is opening a file, manipulating the file, then closing it:
with open('output.txt', 'w') as f: f.write('Hi there!')
The above with statement will automatically close the file after the nested block of code. (Continue reading to see exactly how the close occurs.) The advantage of using a with statement is that it is guaranteed to close the file no matter how the nested block exits. If an exception occurs before the end of the block, it will close the file before the exception is caught by an outer exception handler. If the nested block were to contain a return statement, or a continue or break statement, the with statement would automatically close the file in those cases, too.
For me it helped to install libxml2-dev
and libxslt1-dev
.
sudo apt-get install libxml2-dev
Some reading to get you started on character encodings: Joel on Software: The Absolute Minimum Every Software Developer Absolutely, Positively Must Know About Unicode and Character Sets (No Excuses!)
By the way - ASP.NET has nothing to do with it. Encodings are universal.
All you have to do is to remove the table row (<tr>
) tag from your table. For example here is the code to remove the last row from the table:
$('#myTable tr:last').remove();
*Code above was taken from this jQuery Howto post.
You can't use @android:style/TextAppearance
as the parent for the whole app's theme; that's why koopaking3's solution seems quite broken.
To change default text colour everywhere in your app using a custom theme, try something like this. Works at least on Android 4.0+ (API level 14+).
res/values/themes.xml
:
<resources>
<style name="MyAppTheme" parent="android:Theme.Holo.Light">
<!-- Change default text colour from dark grey to black -->
<item name="android:textColor">@android:color/black</item>
</style>
</resources>
Manifest:
<application
...
android:theme="@style/MyAppTheme">
A shortcoming with the above is that also disabled Action Bar overflow menu items use the default colour, instead of being greyed out. (Of course, if you don't use disabled menu items anywhere in your app, this may not matter.)
As I learned by asking this question, a better way is to define the colour using a drawable:
<item name="android:textColor">@drawable/default_text_color</item>
...with res/drawable/default_text_color.xml
specifying separate state_enabled="false"
colour:
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_enabled="false" android:color="@android:color/darker_gray"/>
<item android:color="@android:color/black"/>
</selector>
Ran into this issue today (Excel crashes on adding rows using .ListRows.Add
).
After reading this post and checking my table, I realized the calculations of the formula's in some of the cells in the row depend on a value in other cells.
In my case of cells in a higher column AND even cells with a formula!
The solution was to fill the new added row from back to front, so calculations would not go wrong.
Excel normally can deal with formula's in different cells, but it seems adding a row in a table kicks of a recalculation in order of the columns (A,B,C,etc..).
Hope this helps clearing issues with .ListRows.Add
Create a separate ul.nav
for just that list item and float that ul
right.
Try running the following code:
List<String> listOfString = Arrays.asList("Hello", "World");
ArrayList<String> arrayListOfString = new ArrayList(listOfString);
System.out.println(listOfString.getClass());
System.out.println(arrayListOfString.getClass());
You'll get the following result:
class java.util.Arrays$ArrayList
class java.util.ArrayList
So, that means they're 2 different classes that aren't extending each other. java.util.Arrays$ArrayList signifies the private class named ArrayList (inner class of Arrays class) and java.util.ArrayList signifies the public class named ArrayList. Thus, casting from java.util.Arrays$ArrayList to java.util.ArrayList and vice versa are irrelevant/not available.
Lightweight command line argument defaults
Although argparse
is great and is the right answer for fully documented command line switches and advanced features, you can use function argument defaults to handles straightforward positional arguments very simply.
import sys
def get_args(name='default', first='a', second=2):
return first, int(second)
first, second = get_args(*sys.argv)
print first, second
The 'name' argument captures the script name and is not used. Test output looks like this:
> ./test.py
a 2
> ./test.py A
A 2
> ./test.py A 20
A 20
For simple scripts where I just want some default values, I find this quite sufficient. You might also want to include some type coercion in the return values or command line values will all be strings.
I always add this style to my Bootstrap LESS / SASS:
.row-no-padding {
[class*="col-"] {
padding-left: 0 !important;
padding-right: 0 !important;
}
}
Then in the HTML you can write:
<div class="row row-no-padding">
I wrote my own library to achieve the intended behaviour in ios Maps app. It is a protocol oriented solution. So you don't need to inherit any base class instead create a sheet controller and configure as you wish. It also supports inner navigation/presentation with or without UINavigationController.
See below link for more details.
If you own the HTML code then it might be wise to assign an id to this href. Then your code would look like this:
<a id="sign_up" class="sign_new">Sign up</a>
And jQuery:
$(document).ready(function(){
$('#sign_up').click(function(){
alert('Sign new href executed.');
});
});
If you do not own the HTML then you'd need to change $('#sign_up') to $('a.sign_new'). You might also fire event.stopPropagation() if you have a href in anchor and do not want it handled (AFAIR return false might work as well).
$(document).ready(function(){
$('#sign_up').click(function(event){
alert('Sign new href executed.');
event.stopPropagation();
});
});
Rather than going into the AndroidManifest, you could just do this:
screenOrientation = getResources().getConfiguration().orientation;
getActivity().setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LOCKED);
... AsyncTask
screenOrientation = getResources().getConfiguration().orientation;
@Override
protected void onPostExecute(String things) {
context.setRequestedOrientation(PlayListFragment.screenOrientation);
or
context.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_FULL_SENSOR);
}
The only drawback here is that it requires API level 18 or higher. So basically this is the tip of the spear.
While the above answers are probably best for this situation, if you just want to do a one-off and don't want to bother with modifying other files, you can in-line the CSS.
<p style="margin-bottom:3cm;">This is the first question?</p>
You can use ViewModelBase as base class for all models , this class will take care of pulling data from session
class ViewModelBase
{
public User CurrentUser
{
get { return System.Web.HttpContext.Current.Session["user"] as User };
set
{
System.Web.HttpContext.Current.Session["user"]=value;
}
}
}
You can write a extention method on HttpContextBase to deal with session data
T FromSession<T>(this HttpContextBase context ,string key,Action<T> getFromSource=null)
{
if(context.Session[key]!=null)
{
return (T) context.Session[key];
}
else if(getFromSource!=null)
{
var value = getFromSource();
context.Session[key]=value;
return value;
}
else
return null;
}
Use this like below in controller
User userData = HttpContext.FromSession<User>("userdata",()=> { return user object from service/db });
The second argument is optional it will be used fill session data for that key when value is not present in session.
Use 51Degrees.com device detection solution to detect browser name, vendor and version.
First, follow the 4-step guide to incorporate device detector in to your project. When I say incorporate I mean download archive with PHP code and database file, extract them and include 2 files. That's all there is to do to incorporate.
Once that's done you can use the following properties to get browser information:
$_51d['BrowserName'] - Gives you the name of the browser (Safari, Molto, Motorola, MStarBrowser etc).
$_51d['BrowserVendor'] - Gives you the company who created browser.
$_51d['BrowserVersion'] - Version number of the browser
In your example propertyInfo.GetValue(this, null)
should work. Consider altering GetNamesAndTypesAndValues()
as follows:
public void GetNamesAndTypesAndValues()
{
foreach (PropertyInfo propertyInfo in allClassProperties)
{
Console.WriteLine("{0} [type = {1}] [value = {2}]",
propertyInfo.Name,
propertyInfo.PropertyType,
propertyInfo.GetValue(this, null));
}
}
The top answer is good but it doesn't mention expression trees which explain "how" the two interfaces differ. Basically, there are two identical sets of LINQ extensions. Where()
, Sum()
, Count()
, FirstOrDefault()
, etc all have two versions: one that accepts functions and one that accepts expressions.
The IEnumerable
version signature is: Where(Func<Customer, bool> predicate)
The IQueryable
version signature is: Where(Expression<Func<Customer, bool>> predicate)
You've probably been using both of those without realizing it because both are called using identical syntax:
e.g. Where(x => x.City == "<City>")
works on both IEnumerable
and IQueryable
When using Where()
on an IEnumerable
collection, the compiler passes a compiled function to Where()
When using Where()
on an IQueryable
collection, the compiler passes an expression tree to Where()
. An expression tree is like the reflection system but for code. The compiler converts your code into a data structure that describes what your code does in a format that's easily digestible.
Why bother with this expression tree thing? I just want Where()
to filter my data.
The main reason is that both the EF and Linq2SQL ORMs can convert expression trees directly into SQL where your code will execute much faster.
Oh, that sounds like a free performance boost, should I use AsQueryable()
all over the place in that case?
No, IQueryable
is only useful if the underlying data provider can do something with it. Converting something like a regular List
to IQueryable
will not give you any benefit.
here is a solution that will function for both characters and substrings:
select (length('a') - nvl(length(replace('a','b')),0)) / length('b')
from dual
where a is the string in which you search the occurrence of b
have a nice day!
In computer programming, particularly in the C, C++, and C# programming languages, a variable or object declared with the volatile
keyword usually has special properties related to optimization and/or threading. Generally speaking, the volatile
keyword is intended to prevent the (pseudo)compiler from applying any optimizations on the code that assume values of variables cannot change "on their own." (c) Wikipedia
Mistake in original post is acquire() call set inside the try loop. Here is a correct approach to use "binary" semaphore (Mutex):
semaphore.acquire();
try {
//do stuff
} catch (Exception e) {
//exception stuff
} finally {
semaphore.release();
}
I would use VARCHAR
for variable length data, but not with fixed length data. Because a SHA-1 value is always 160 bit long, the VARCHAR
would just waste an additional byte for the length of the fixed-length field.
And I also wouldn’t store the value the SHA1
is returning. Because it uses just 4 bit per character and thus would need 160/4 = 40 characters. But if you use 8 bit per character, you would only need a 160/8 = 20 character long field.
So I recommend you to use BINARY(20)
and the UNHEX
function to convert the SHA1
value to binary.
I compared storage requirements for BINARY(20)
and CHAR(40)
.
CREATE TABLE `binary` (
`id` int unsigned auto_increment primary key,
`password` binary(20) not null
);
CREATE TABLE `char` (
`id` int unsigned auto_increment primary key,
`password` char(40) not null
);
With million of records binary(20)
takes 44.56M, while char(40)
takes 64.57M.
InnoDB
engine.
Although you cannot use different sized slides in one PowerPoint file, for the actual presentation you can link several different files together to create a presentation that has different slide sizes.
The process to do so is as follows:
Reference to Office Support Page where this solution was first posted. https://support.office.com/en-us/article/can-i-use-portrait-and-landscape-slide-orientation-in-the-same-presentation-d8c21781-1fb6-4406-bcd6-25cfac37b5d6?ocmsassetID=HA010099556&CorrelationId=1ac4e97f-bfe6-47b1-bab6-5783e78d126d&ui=en-US&rs=en-US&ad=US
See full query from SHOW PROCESSLIST :
SHOW FULL PROCESSLIST;
Or
SELECT * FROM INFORMATION_SCHEMA.PROCESSLIST;
Try another *fastcgi_param* something like
fastcgi_param SCRIPT_FILENAME /usr/share/nginx/html$fastcgi_script_name;
They are not the same thing.
Consider these queries:
SELECT *
FROM Orders
LEFT JOIN OrderLines ON OrderLines.OrderID=Orders.ID
WHERE Orders.ID = 12345
and
SELECT *
FROM Orders
LEFT JOIN OrderLines ON OrderLines.OrderID=Orders.ID
AND Orders.ID = 12345
The first will return an order and its lines, if any, for order number 12345
. The second will return all orders, but only order 12345
will have any lines associated with it.
With an INNER JOIN
, the clauses are effectively equivalent. However, just because they are functionally the same, in that they produce the same results, does not mean the two kinds of clauses have the same semantic meaning.
This Perl code removes commas at the end of the line:
perl -pe 's/,$//' file > file.nocomma
This variation still works if there is whitespace after the comma:
perl -lpe 's/,\s*$//' file > file.nocomma
This variation edits the file in-place:
perl -i -lpe 's/,\s*$//' file
This variation edits the file in-place, and makes a backup file.bak
:
perl -i.bak -lpe 's/,\s*$//' file
The best solution I've come up with at on the spot (though most likely crude) would be:
String.prototype.getBytes = function() {
var bytes = [];
for (var i = 0; i < this.length; i++) {
var charCode = this.charCodeAt(i);
var cLen = Math.ceil(Math.log(charCode)/Math.log(256));
for (var j = 0; j < cLen; j++) {
bytes.push((charCode << (j*8)) & 0xFF);
}
}
return bytes;
}
Though I notice this question has been here for over a year.
Use the LEN
function:
Returns the number of characters of the specified string expression, excluding trailing blanks.
In a new PHP7 there is a finally a support for a cryptographically secure pseudo-random integers.
int random_int ( int $min , int $max )
random_int — Generates cryptographically secure pseudo-random integers
which basically makes previous answers obsolete.
As Jean mentioned, using a StringBuilder
instead of +=
would be better. But if you're looking for something simpler, Guava, IOUtils, and Jsoup are all good options.
Example with Guava:
String content = Files.asCharSource(new File("/path/to/mypage.html"), StandardCharsets.UTF_8).read();
Example with IOUtils:
InputStream in = new URL("/path/to/mypage.html").openStream();
String content;
try {
content = IOUtils.toString(in, StandardCharsets.UTF_8);
} finally {
IOUtils.closeQuietly(in);
}
Example with Jsoup:
String content = Jsoup.parse(new File("/path/to/mypage.html"), "UTF-8").toString();
or
String content = Jsoup.parse(new File("/path/to/mypage.html"), "UTF-8").outerHtml();
NOTES:
Files.readLines()
andFiles.toString()
These are now deprecated as of Guava release version 22.0 (May 22, 2017).
Files.asCharSource()
should be used instead as seen in the example above. (version 22.0 release diffs)
IOUtils.toString(InputStream)
andCharsets.UTF_8
Deprecated as of Apache Commons-IO version 2.5 (May 6, 2016). IOUtils.toString
should now be passed the InputStream
and the Charset
as seen in the example above. Java 7's StandardCharsets
should be used instead of Charsets
as seen in the example above. (deprecated Charsets.UTF_8)
If you are using the IN operator, the SQL engine will scan all records fetched from the inner query. On the other hand if we are using EXISTS, the SQL engine will stop the scanning process as soon as it found a match.
If it does not work, you may try one of these tools that convert the image to an HTML table (beware the size of your image though):
With VS 2010, use the Database project.
Makes a perfect DB versioning solution, and makes syncing DB's a breeze.
Your missing a ' after night. right here getElementById('Night
You have to seed it. Seeding it with the time is a good idea:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main ()
{
srand ( time(NULL) );
printf ("Random Number: %d\n", rand() %100);
return 0;
}
You get the same sequence because rand()
is automatically seeded with the a value of 1 if you do not call srand()
.
Due to comments
rand()
will return a number between 0 and RAND_MAX
(defined in the standard library). Using the modulo operator (%
) gives the remainder of the division rand() / 100
. This will force the random number to be within the range 0-99. For example, to get a random number in the range of 0-999 we would apply rand() % 1000
.
For an excellent resource on how bash invocation works, what dotfiles do what, and how you should use/configure them, read this:
Check out my highly simplified Echo example: It is designed to use basic HTTP communication, but it can easily be modified to use named pipes by editing the app.config files for the client and server. Make the following changes:
Edit the server's app.config file, removing or commenting out the http baseAddress entry and adding a new baseAddress entry for the named pipe (called net.pipe). Also, if you don't intend on using HTTP for a communication protocol, make sure the serviceMetadata and serviceDebug is either commented out or deleted:
<configuration>
<system.serviceModel>
<services>
<service name="com.aschneider.examples.wcf.services.EchoService">
<host>
<baseAddresses>
<add baseAddress="net.pipe://localhost/EchoService"/>
</baseAddresses>
</host>
</service>
</services>
<behaviors>
<serviceBehaviors></serviceBehaviors>
</behaviors>
</system.serviceModel>
</configuration>
Edit the client's app.config file so that the basicHttpBinding is either commented out or deleted and a netNamedPipeBinding entry is added. You will also need to change the endpoint entry to use the pipe:
<configuration>
<system.serviceModel>
<bindings>
<netNamedPipeBinding>
<binding name="NetNamedPipeBinding_IEchoService"/>
</netNamedPipeBinding>
</bindings>
<client>
<endpoint address = "net.pipe://localhost/EchoService"
binding = "netNamedPipeBinding"
bindingConfiguration = "NetNamedPipeBinding_IEchoService"
contract = "EchoServiceReference.IEchoService"
name = "NetNamedPipeBinding_IEchoService"/>
</client>
</system.serviceModel>
</configuration>
The above example will only run with named pipes, but nothing is stopping you from using multiple protocols to run your service. AFAIK, you should be able to have a server run a service using both named pipes and HTTP (as well as other protocols).
Also, the binding in the client's app.config file is highly simplified. There are many different parameters you can adjust, aside from just specifying the baseAddress...
String file = "";
try {
InputStream is = new FileInputStream(filename);
String UTF8 = "utf8";
int BUFFER_SIZE = 8192;
BufferedReader br = new BufferedReader(new InputStreamReader(is,
UTF8), BUFFER_SIZE);
String str;
while ((str = br.readLine()) != null) {
file += str;
}
} catch (Exception e) {
}
Try this,.. :-)
$('html, body').animate(...)
does not for me on iphone, android chrome safari browser.
I had to target root content element of the page.
$('#cotnent').animate(...)
Here is what I have ended up with
if (navigator.userAgent.match(/(iPod|iPhone|iPad|Android)/)) {
$('#content').animate({
scrollTop: $("#elementtoScrollToID").offset().top
}, 'slow');
}
else{
$('html, body').animate({
scrollTop: $("#elementtoScrollToID").offset().top
}, 'slow');
}
All body content wired up with a #content div
<html>
....
<body>
<div id="content">
....
</div>
</body>
</html>
Use MoreLINQ, which has a DistinctBy
method :)
IEnumerable<Car> distinctCars = cars.DistinctBy(car => car.CarCode);
(This is only for LINQ to Objects, mind you.)
var mouseX;
var mouseY;
$(document).mousemove( function(e) {
mouseX = e.pageX;
mouseY = e.pageY;
});
$(".classForHoverEffect").mouseover(function(){
$('#DivToShow').css({'top':mouseY,'left':mouseX}).fadeIn('slow');
});
the function above will make the DIV appear over the link wherever that may be on the page. It will fade in slowly when the link is hovered. You could also use .hover() instead. From there the DIV will stay, so if you would like the DIV to disappear when the mouse moves away, then,
$(".classForHoverEffect").mouseout(function(){
$('#DivToShow').fadeOut('slow');
});
If you DIV is already positioned, you can simply use
$('.classForHoverEffect').hover(function(){
$('#DivToShow').fadeIn('slow');
});
Also, keep in mind, your DIV style needs to be set to display:none;
in order for it to fadeIn or show.
See http://wiki.apache.org/httpd/DistrosDefaultLayout for discussion of where you might find Apache httpd configuration files on various platforms, since this can vary from release to release and platform to platform. The most common answer, however, is either /etc/apache/conf or /etc/httpd/conf
Generically, you can determine the answer by running the command:
httpd -V
(That's a capital V). Or, on systems where httpd is renamed, perhaps apache2ctl -V
This will return various details about how httpd is built and configured, including the default location of the main configuration file.
One of the lines of output should look like:
-D SERVER_CONFIG_FILE="conf/httpd.conf"
which, combined with the line:
-D HTTPD_ROOT="/etc/httpd"
will give you a full path to the default location of the configuration file
Try Shift + Delete. Did 24.000 files in 2 minutes for me.
Just encountered the same issue. The problem is because of django-registration
incompatible with django 1.7 user model.
A simple fix is to change these lines of code, at your installed django-registration
module::
try:
from django.contrib.auth import get_user_model
User = get_user_model()
except ImportError:
from django.contrib.auth.models import User
to::
from django.conf import settings
try:
from django.contrib.auth import get_user_model
User = settings.AUTH_USER_MODEL
except ImportError:
from django.contrib.auth.models import User
Mine is at .venv/local/lib/python2.7/site-packages/registration/models.py
(virtualenv)
As stated in other posts, you can use the break keyword. One thing that was hinted at but not explained is that the keyword can take a numeric value to tell PHP how many levels to break from.
For example, if you have three foreach loops nested in each other trying to find a piece of information, you could do 'break 3' to get out of all three nested loops. This will work for the 'for', 'foreach', 'while', 'do-while', or 'switch' structures.
$person = "Rasmus Lerdorf";
$found = false;
foreach($organization as $oKey=>$department)
{
foreach($department as $dKey=>$group)
{
foreach($group as $gKey=>$employee)
{
if ($employee['fullname'] == $person)
{
$found = true;
break 3;
}
} // group
} // department
} // organization
I get this post is old but there have been changes to how select2 works now and the answer to this question is extremely simple.
To set the values in a multi select2 is as follows
$('#Books_Illustrations').val([1,2,3]).change();
There is no need to specify .select2
in jquery anymore, simply .val
Also there will be times you will not want to fire the change
event because you might have some other code that will execute which is what will happen if you use the method above so to get around that you can change the value without firing the change
event like so
$('#Books_Illustrations').select2([1,2,3], null, false);
This would work very well -- You can use HTML5 to allow only image files to be uploaded. This is the code for uploader.htm --
<html>
<head>
<script>
function validateForm(){
var image = document.getElementById("image").value;
var name = document.getElementById("name").value;
if (image =='')
{
return false;
}
if(name =='')
{
return false;
}
else
{
return true;
}
return false;
}
</script>
</head>
<body>
<form method="post" action="upload.php" enctype="multipart/form-data">
<input type="text" name="ext" size="30"/>
<input type="text" name="name" id="name" size="30"/>
<input type="file" accept="image/*" name="image" id="image" />
<input type="submit" value='Save' onclick="return validateForm()"/>
</form>
</body>
</html>
Now the code for upload.php --
<?php
$name = $_POST['name'];
$ext = $_POST['ext'];
if (isset($_FILES['image']['name']))
{
$saveto = "$name.$ext";
move_uploaded_file($_FILES['image']['tmp_name'], $saveto);
$typeok = TRUE;
switch($_FILES['image']['type'])
{
case "image/gif": $src = imagecreatefromgif($saveto); break;
case "image/jpeg": // Both regular and progressive jpegs
case "image/pjpeg": $src = imagecreatefromjpeg($saveto); break;
case "image/png": $src = imagecreatefrompng($saveto); break;
default: $typeok = FALSE; break;
}
if ($typeok)
{
list($w, $h) = getimagesize($saveto);
$max = 100;
$tw = $w;
$th = $h;
if ($w > $h && $max < $w)
{
$th = $max / $w * $h;
$tw = $max;
}
elseif ($h > $w && $max < $h)
{
$tw = $max / $h * $w;
$th = $max;
}
elseif ($max < $w)
{
$tw = $th = $max;
}
$tmp = imagecreatetruecolor($tw, $th);
imagecopyresampled($tmp, $src, 0, 0, 0, 0, $tw, $th, $w, $h);
imageconvolution($tmp, array( // Sharpen image
array(-1, -1, -1),
array(-1, 16, -1),
array(-1, -1, -1)
), 8, 0);
imagejpeg($tmp, $saveto);
imagedestroy($tmp);
imagedestroy($src);
}
}
?>
newlist = oldlist[::10]
This picks out every 10th element of the list.
[class*="test"],[class="second"] {
background: #ffff00;
}
Instead of "w"
use "a"
(append) mode with open
function:
with open("games.txt", "a") as text_file:
What's wrong with:
var data = {};
$(".form-selector").serializeArray().map(function(x){data[x.name] = x.value;});
No need to promise with $http, i use it just with two returns :
myApp.service('dataService', function($http) {
this.getData = function() {
return $http({
method: 'GET',
url: 'https://www.example.com/api/v1/page',
params: 'limit=10, sort_by=created:desc',
headers: {'Authorization': 'Token token=xxxxYYYYZzzz'}
}).success(function(data){
return data;
}).error(function(){
alert("error");
return null ;
});
}
});
In controller
myApp.controller('AngularJSCtrl', function($scope, dataService) {
$scope.data = null;
dataService.getData().then(function(response) {
$scope.data = response;
});
});
A cleaner alternative would be to use a Dictionary
to handle parameters. They are key-value pairs after all.
private static readonly HttpClient httpclient;
static MyClassName()
{
// HttpClient is intended to be instantiated once and re-used throughout the life of an application.
// Instantiating an HttpClient class for every request will exhaust the number of sockets available under heavy loads.
// This will result in SocketException errors.
// https://docs.microsoft.com/en-us/dotnet/api/system.net.http.httpclient?view=netframework-4.7.1
httpclient = new HttpClient();
}
var url = "http://myserver/method";
var parameters = new Dictionary<string, string> { { "param1", "1" }, { "param2", "2" } };
var encodedContent = new FormUrlEncodedContent (parameters);
var response = await httpclient.PostAsync (url, encodedContent).ConfigureAwait (false);
if (response.StatusCode == HttpStatusCode.OK) {
// Do something with response. Example get content:
// var responseContent = await response.Content.ReadAsStringAsync ().ConfigureAwait (false);
}
Also dont forget to Dispose()
httpclient, if you dont use the keyword using
As stated in the Remarks section of the HttpClient class in the Microsoft docs, HttpClient should be instantiated once and re-used.
Edit:
You may want to look into response.EnsureSuccessStatusCode();
instead of if (response.StatusCode == HttpStatusCode.OK)
.
You may want to keep your httpclient and dont Dispose()
it. See: Do HttpClient and HttpClientHandler have to be disposed?
Edit:
Do not worry about using .ConfigureAwait(false) in .NET Core. For more details look at https://blog.stephencleary.com/2017/03/aspnetcore-synchronization-context.html
You can use the following library:
https://github.com/pnowy/NativeCriteria
The library is built on the top of the Hibernate "create sql query" so it supports all databases supported by Hibernate (the Hibernate session and JPA providers are supported). The builder patter is available and so on (object mappers, result mappers).
You can find the examples on github page, the library is available at Maven central of course.
NativeCriteria c = new NativeCriteria(new HibernateQueryProvider(hibernateSession), "table_name", "alias");
c.addJoin(NativeExps.innerJoin("table_name_to_join", "alias2", "alias.left_column", "alias2.right_column"));
c.setProjection(NativeExps.projection().addProjection(Lists.newArrayList("alias.table_column","alias2.table_column")));
l <- replicate(10,list(sample(letters, 20)))
a <-lapply(l[1:10],data.frame)
do.call("cbind", a)
First, having the url in href
is best because it allows users to copy links, open in another tab, etc.
In some cases (e.g. sites with frequent HTML changes) it is not practical to bind links every time there is an update.
Normal link:
<a href="https://www.google.com/">Google<a/>
And something like this for JS:
$("a").click(function (e) {
e.preventDefault();
var href = $(this).attr("href");
window.open(href);
return false;
});
The benefits of this method are clean separation of markup and behavior and doesn't have to repeat the function calls in every link.
If you don't want to bind every time, however, you can use onclick and pass in the element and event, e.g.:
<a href="https://www.google.com/" onclick="return Handler(this, event);">Google</a>
And this for JS:
function Handler(self, e) {
e.preventDefault();
var href = $(self).attr("href");
window.open(href);
return false;
}
The benefit to this method is that you can load in new links (e.g. via AJAX) whenever you want without having to worry about binding every time.
Just a note that in Java 9 and above, the naming convention is different. System.getProperty("java.version")
returns "9"
rather than "1.9"
.
Can you provide an example, because put should work fine as well?
Documentation -
The type of request to make ("POST" or "GET"); the default is "GET". Note: Other HTTP request methods, such as PUT and DELETE, can also be used here, but they are not supported by all browsers.
Have the example in fiddle and the form parameters are passed fine (as it is put it will not be appended to url
) -
$.ajax({
url: '/echo/html/',
type: 'PUT',
data: "name=John&location=Boston",
success: function(data) {
alert('Load was performed.');
}
});
Demo tested from jQuery 1.3.2 onwards on Chrome.
In my case, the solution was to remove "" (quotation mark) from commit message. Weird
You could try adding an<hr>
and styling that. Its a minimal markup change but seems to need less css so that might do the trick.
fiddle:
In addition to the locations listed above, the OS X version of Perl also has two more ways:
The /Library/Perl/x.xx/AppendToPath file. Paths listed in this file are appended to @INC at runtime.
The /Library/Perl/x.xx/PrependToPath file. Paths listed in this file are prepended to @INC at runtime.
I just ran into this problem today. It turned out that a bug on the server (null pointer exception) was causing it to fail in creating a response, yet it still generated an HTTP status code of 200. Because of the 200 status code, Chrome expected a valid response. The first thing that Chrome did was to look for the 'Access-Control-Allow-Origin' header, which it did not find. Chrome then cancelled the request, and Angular gave me an error. The bug during processing the POST request is the reason why the OPTIONS would succeed, but the POST would fail.
In short, if you see this error, it may be that your server didn't return any headers at all in response to the POST request.
This is android's way of telling you to upgrade gradle to the most recent version. You can do two things-
This problem occurs when you already had MySQL installed on your machine or in case you have changed the post number of the MySql service which is 3306(Default). In order to solve this, you have to tell the phpMyAdmin to look for another port instead of 3306. To do so go to C:\xampp\phpMyAdmin(default location) and open Config.inc
and add this line $cfg['Servers'][$i]['port'] = '3307';
after $cfg['Servers'][$i]['AllowNoPassword'] = true;
Restart the services and now it should work.
The following works as of April 2014. Delimiting each component of the URL with +
and &
for spaces and addition statements, respectively.
Full HTML:
<iframe src="http://maps.google.com/maps?q=Scottish+Rite+Hamilton+ON&loc:43.25911+-79.879494&z=15&output=embed"></iframe>
Broken down:
http://maps.google.com/maps?q=
where ?q= starts the general search, which I provide a venue, city, province info using +
for spaces.
Scottish+Rite+Hamilton+ON
Next the geo-data. Lat and lng.
&loc:43.25911+-79.879494
Zoom level
&z=15
Required for iframes:
&output=embed
This answer features:
Here's the extracted code:
public async Task SendAsync(string subject, string body, string to)
{
using (var message = new MailMessage(smtpConfig.FromAddress, to)
{
Subject = subject,
Body = body,
IsBodyHtml = true
})
{
using (var client = new SmtpClient()
{
Port = smtpConfig.Port,
DeliveryMethod = SmtpDeliveryMethod.Network,
UseDefaultCredentials = false,
Host = smtpConfig.Host,
Credentials = new NetworkCredential(smtpConfig.User, smtpConfig.Password),
})
{
await client.SendMailAsync(message);
}
}
}
Class SmtpConfig:
public class SmtpConfig
{
public string Host { get; set; }
public string User { get; set; }
public string Password { get; set; }
public int Port { get; set; }
public string FromAddress { get; set; }
}
File > Project Structure > SDK Location > JDK Location >
/usr/lib/jvm/java-8-openjdk-amd64
GL
Cron is good for something that will run periodically, like every Saturday at 4am. There's also anacron, which works around power shutdowns, sleeps, and whatnot. As well as at.
But for a one-off solution, that doesn't require root or anything, you can just use date to compute the seconds-since-epoch of the target time as well as the present time, then use expr to find the difference, and sleep that many seconds.
This is now supported in Chrome by the "Pause on all exceptions" button.
To enable it:
Note that this button has multiple states. Keep clicking the button to switch between
Here is a log4j.properties file that I've used with great success.
logDir=/var/log/myapp
log4j.rootLogger=INFO, stdout
#log4j.rootLogger=DEBUG, stdout
log4j.appender.stdout=org.apache.log4j.DailyRollingFileAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d{MM/dd/yyyy hh:mm:ss a}|%-5p|%-30c{1}| %m%n
log4j.appender.stdout.DatePattern='.'yyyy-MM-dd
log4j.appender.stdout.File=${logDir}/myapp.log
log4j.appender.stdout.append=true
The DailyRollingFileAppender will create new files each day with file names that look like this:
myapp.log.2017-01-27
myapp.log.2017-01-28
myapp.log.2017-01-29
myapp.log <-- today's log
Each entry in the log file will will have this format:
01/30/2017 12:59:47 AM|INFO |Component1 | calling foobar(): userId=123, returning totalSent=1
01/30/2017 12:59:47 AM|INFO |Component2 | count=1 > 0, calling fooBar()
Set the location of the above file by using -Dlog4j.configuration
, as mentioned in this posting:
java -Dlog4j.configuration=file:/home/myapp/config/log4j.properties com.foobar.myapp
In your Java code, be sure to set the name of each software component when you instantiate your logger object. I also like to log to both the log file and standard output, so I wrote this small function.
private static final Logger LOGGER = Logger.getLogger("Component1");
public static void log(org.apache.log4j.Logger logger, String message) {
logger.info(message);
System.out.printf("%s\n", message);
}
public static String stackTraceToString(Exception ex) {
StringWriter sw = new StringWriter();
PrintWriter pw = new PrintWriter(sw);
ex.printStackTrace(pw);
return sw.toString();
}
And then call it like so:
LOGGER.info(String.format("Exception occurred: %s", stackTraceToString(ex)));
<style>
#aspectRatio
{
position:fixed;
left:0px;
top:0px;
width:60vw;
height:40vw;
border:1px solid;
font-size:10vw;
}
</style>
<body>
<div id="aspectRatio">Aspect Ratio?</div>
</body>
The key thing to note here is vw
= viewport width, and vh
= viewport height
You may note that request.json or request.get_json() works only when the "Content-type: application/json" has been added in the header of the request. If you are unable to change the client request configuration, so you can get the body as json like this:
data = json.loads(request.data)
Found the port esp32 was connected to by -
ls /dev/*
You would get a long list and you can find the port you need
Use Test-Path:
if (!(Test-Path $exactadminfile) -and !(Test-Path $userfile)) {
Write-Warning "$userFile absent from both locations"
}
Placing the above code in your ForEach
loop should do what you want
I once ran into this situation and I had the dependencies in classpath. The solution was to include javax.mail and javax.activation libraries in the container's (eg. tomcat) lib folder. Using maven -set them to provided scope and it should work. You will have shared email libs in classpath for all projects.
Useful source: http://haveacafe.wordpress.com/2008/09/26/113/
I had many issues involving C# and SqlServer. I ended up doing the following:
Also make sure that all your machines run on the same timezone.
Regarding the different result sets you get, your first example is "July First" while the second is "4th of July" ...
Also, the second example can be also interpreted as "April 7th", it depends on your server localization configuration (my solution doesn't suffer from this issue).
EDIT: hh was replaced with HH, as it doesn't seem to capture the correct hour on systems with AM/PM as opposed to systems with 24h clock. See the comments below.
I followed around five different answers as well as all the blog posts in the previous answers and still had problems. I was trying to add a listener to some existing code that was tracing using the TraceSource.TraceEvent(TraceEventType, Int32, String)
method where the TraceSource
object was initialised with a string making it a 'named source'.
For me the issue was not creating a valid combination of source and switch elements to target this source. Here is an example that will log to a file called tracelog.txt
. For the following code:
TraceSource source = new TraceSource("sourceName");
source.TraceEvent(TraceEventType.Verbose, 1, "Trace message");
I successfully managed to log with the following diagnostics configuration:
<system.diagnostics>
<sources>
<source name="sourceName" switchName="switchName">
<listeners>
<add
name="textWriterTraceListener"
type="System.Diagnostics.TextWriterTraceListener"
initializeData="tracelog.txt" />
</listeners>
</source>
</sources>
<switches>
<add name="switchName" value="Verbose" />
</switches>
</system.diagnostics>
if you remove the float: left
from the a
and add white-space: nowrap
to the outer div
#myWorkContent{
width:530px;
height:210px;
border: 13px solid #bed5cd;
overflow-x: scroll;
overflow-y: hidden;
white-space: nowrap;
}
#myWorkContent a {
display: inline;
}
this should work for any size or amount of images..
or even:
#myWorkContent a {
display: inline-block;
vertical-align: middle;
}
which would also vertically align images of different heights if required
XmlWriter is the fastest way to write good XML. XDocument, XMLDocument and some others works good aswell, but are not optimized for writing XML. If you want to write the XML as fast as possible, you should definitely use XmlWriter.
Using Bootstrap 3.3.5 and .container-fluid
, this is how I get full width with no gutters or horizontal scrolling on mobile. Note that .container-fluid
was re-introduced in 3.1.
Full width on mobile/tablet, 1/4 screen on desktop
<div class="container-fluid"> <!-- Adds 15px left/right padding -->
<div class="row"> <!-- Adds -15px left/right margins -->
<div class="col-md-4 col-md-offset-4" style="padding-left: 0, padding-right: 0"> <!-- col classes adds 15px padding, so remove the same amount -->
<!-- Full-width for mobile -->
<!-- 1/4 screen width for desktop -->
</div>
</div>
</div>
Full width on all resolutions (mobile, table, desktop)
<div class="container-fluid"> <!-- Adds 15px left/right padding -->
<div class="row"> <!-- Adds -15px left/right margins -->
<div>
<!-- Full-width content -->
</div>
</div>
</div>
In addition to Tim's answer, this issue occurred for me when I was splitting up a refactoring a file, splitting it up into their own files.
VSCode, for some reason, indented parts of my [class] code, which caused this issue. This was hard to notice at first, but after I realised the code was indented, I formatted the code and the issue disappeared.
for example, everything after the first line of the Class definition was auto-indented during the paste.
export class MyClass extends Something<string> {
public blah: string = null;
constructor() { ... }
}
This may sound like the long way around, but you may want to look at using Excel to generate INSERT SQL code that you can past into Query Analyzer to create your table.
Works well if you cant use the wizards because the excel file isn't on the server
This error would occur if any of the following variables were actually strings or null instead of arrays, in which case accessing them with an array syntax $var[$i]
would be like trying to access a specific character in a string:
$catagory
$task
$fullText
$dueDate
$empId
In short, everything in your insert query.
Perhaps the $catagory
variable is misspelled?
function myResizeFunction() {
...
}
$(function() {
$(window).resize(myResizeFunction).trigger('resize');
});
This will cause your resize handler to trigger on window resize and on document ready. Of course, you can attach your resize handler outside of the document ready handler if you want .trigger('resize')
to run on page load instead.
UPDATE: Here's another option if you don't want to make use of any other third-party libraries.
This technique adds a specific class to your target element so you have the advantage of controlling the styling through CSS only (and avoiding inline styling).
It also ensures that the class is only added or removed when the actual threshold point is triggered and not on each and every resize. It will fire at one threshold point only: when the height changes from <= 818 to > 819 or vice versa and not multiple times within each region. It's not concerned with any change in width.
function myResizeFunction() {
var $window = $(this),
height = Math.ceil($window.height()),
previousHeight = $window.data('previousHeight');
if (height !== previousHeight) {
if (height < 819)
previousHeight >= 819 && $('.footer').removeClass('hgte819');
else if (!previousHeight || previousHeight < 819)
$('.footer').addClass('hgte819');
$window.data('previousHeight', height);
}
}
$(function() {
$(window).on('resize.optionalNamespace', myResizeFunction).triggerHandler('resize.optionalNamespace');
});
As an example, you might have the following as some of your CSS rules:
.footer {
bottom: auto;
left: auto;
position: static;
}
.footer.hgte819 {
bottom: 3px;
left: 0;
position: absolute;
}
Unfortunate most of the profilers I tried failed when used with tail calls, most notably ANTS. I just end up writing my own. There is a simple implementation on CodeProject that you can use as a base.
This might be very late answer. But this chart kills it.
All percentage values are mapped to the hexadecimal values.
Instead of doing this:
$(document).ready(function() { });
You should be doing this:
jQuery(document).ready(function($) {
// your code goes here
});
This is because WordPress may use $ for something other than jQuery, in the future, or now, and so you need to load jQuery in a way that the $ can be used only in a jQuery document ready callback.
Use your developer's tool of choice and check if the tr
, td
or img
has any padding or margins.
For me brew postinstall python3
didn't work. I found this solution on the GitHub Homebrew issues page:
$ brew rm python
$ rm -rf /usr/local/opt/python
$ brew cleanup
$ brew install python3
I had the similar problem with printing multiple PDF files in a row and found only workaround by using 2Printer software. Command line example to print PDF files:
2Printer.exe -s "C:\In\*.PDF" -prn "HP LasetJet 1100"
It is free for non-commercial use at http://doc2prn.com/
Run php
in lint mode from the command line to validate syntax without execution:
php -l FILENAME
Higher-level static analyzers include:
Lower-level analyzers include:
Runtime analyzers, which are more useful for some things due to PHP's dynamic nature, include:
The documentation libraries phpdoc and Doxygen perform a kind of code analysis. Doxygen, for example, can be configured to render nice inheritance graphs with Graphviz.
Another option is xhprof, which is similar to Xdebug, but lighter, making it suitable for production servers. The tool includes a PHP-based interface.
I couldn't find an off-the-shelf module that added this function, so I wrote one:
In Access, go to the Database Tools ribbon, in the Macro area click into Visual Basic. In the top left Project area, right click the name of your file and select Insert -> Module. In the module paste this:
Public Function Substring_Index(strWord As String, strDelim As String, intCount As Integer) As String
Substring_Index = delims
start = 0
test = ""
For i = 1 To intCount
oldstart = start + 1
start = InStr(oldstart, strWord, strDelim)
Substring_Index = Mid(strWord, oldstart, start - oldstart)
Next i
End Function
Save the module as module1 (the default). You can now use statements like:
SELECT Substring_Index([fieldname],",",2) FROM table
Basically modulus Operator gives you remainder simple Example in maths what's left over/remainder of 11 divided by 3? answer is 2
for same thing C++ has modulus operator ('%')
Basic code for explanation
#include <iostream>
using namespace std;
int main()
{
int num = 11;
cout << "remainder is " << (num % 3) << endl;
return 0;
}
Which will display
remainder is 2
This is what I have used in the past.
html, body {
height: 100%;
overflow: auto;
}
Also in the iframe
add the following style
border: 0; position:fixed; top:0; left:0; right:0; bottom:0; width:100%; height:100%
You simply call
Blog::all();
//example usage.
$posts = Blog::all();
$posts->each(function($post) // foreach($posts as $post) { }
{
//do something
}
from anywhere in your application.
Reading the documentation will help a lot.
In short, on MariaDB
1) sudo mysql -u root;
2) use mysql;
3) UPDATE mysql.user SET plugin = 'mysql_native_password',
Password = PASSWORD('pass1234') WHERE User = 'root';
4) FLUSH PRIVILEGES;
5) exit;
<select name="CCards" id="ccards">
<option value="0">Select Saved Payment Method:</option>
<option value="1846">test xxxx1234</option>
<option value="1962">test2 xxxx3456</option>
</select>
<script type="text/javascript">
/** Jquery **/
var selectedValue = $('#ccards').val();
//** Regular Javascript **/
var selectedValue2 = document.getElementById('ccards').value;
</script>
A subclass is a class that extends another class.
public class BaseClass{
public String getFoo(){
return "foo";
}
}
public class SubClass extends BaseClass{
}
Then...
System.out.println(new SubClass().getFoo());
Will print:
foo
This works because a subclass inherits the functionality of the class it extends.
Below sample code can read file line by line and write new file in UTF-8 format. Also, i am explicitly specifying Cp1252 encoding.
public static void main(String args[]) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(
new FileInputStream("c:\\filenonUTF.txt"),
"Cp1252"));
String line;
Writer out = new BufferedWriter(
new OutputStreamWriter(new FileOutputStream(
"c:\\fileUTF.txt"), "UTF-8"));
try {
while ((line = br.readLine()) != null) {
out.write(line);
out.write("\n");
}
} finally {
br.close();
out.close();
}
}
I had a similar issue with zsh and nvm on Linux, I fixed it by adding nvm initialization script in ~/.profile
and restart login session like this
export NVM_DIR="$HOME/.nvm"
[ -s "$NVM_DIR/nvm.sh" ] && \. "$NVM_DIR/nvm.sh" # This loads nvm
[ -s "$NVM_DIR/bash_completion" ] && \. "$NVM_DIR/bash_completion"
Using background-size cover worked for me.
#footer {
background-color: #eee;
background-image: url(images/bodybgbottomleft.png);
background-repeat: no-repeat;
background-size: cover;
clear: both;
width: 100%;
margin: 0;
padding: 30px 0 0;
}
Obviously be aware of support issues, check Can I Use: http://caniuse.com/#search=background-size
Just wanted to clarify that the snippet from accepted answer gives the nearest midnight in the past:
var d = new Date();
d.setHours(0,0,0,0); // last midnight
If you want to get the nearest midnight in future, use the following code:
var d = new Date();
d.setHours(24,0,0,0); // next midnight
I don't think you can call
$.attr('checked',true);
because there is no element selector in the first place. $ must be followed by $('selector_name'). GOod luck!
You may consider declaring the variables with moudule level scope. Module-level variable is available to all of the procedures in that module, but it is not available to procedures in other modules
For details on Scope of variables
refer this link
Please copy the below code into any module, save the workbook and then run the code.
Here is what code does
The sample subroutine sets the folder path & later the file path. Kindly set them accordingly before you run the code.
I have added a function IsWorkBookOpen to check if workbook is already then set the workbook variable the workbook name else open the workbook which will be assigned to workbook variable accordingly.
Dim wbA As Workbook
Dim wbB As Workbook
Sub MySubRoutine()
Dim folderPath As String, fileNm1 As String, fileNm2 As String, filePath1 As String, filePath2 As String
folderPath = ThisWorkbook.Path & "\"
fileNm1 = "file1.xlsx"
fileNm2 = "file2.xlsx"
filePath1 = folderPath & fileNm1
filePath2 = folderPath & fileNm2
If IsWorkBookOpen(filePath1) Then
Set wbA = Workbooks(fileNm1)
Else
Set wbA = Workbooks.Open(filePath1)
End If
If IsWorkBookOpen(filePath2) Then
Set wbB = Workbooks.Open(fileNm2)
Else
Set wbB = Workbooks.Open(filePath2)
End If
' your code here
End Sub
Function IsWorkBookOpen(FileName As String)
Dim ff As Long, ErrNo As Long
On Error Resume Next
ff = FreeFile()
Open FileName For Input Lock Read As #ff
Close ff
ErrNo = Err
On Error GoTo 0
Select Case ErrNo
Case 0: IsWorkBookOpen = False
Case 70: IsWorkBookOpen = True
Case Else: Error ErrNo
End Select
End Function
Using Prompt to select the file use below code.
Dim wbA As Workbook
Dim wbB As Workbook
Sub MySubRoutine()
Dim folderPath As String, fileNm1 As String, fileNm2 As String, filePath1 As String, filePath2 As String
Dim filePath As String
cmdBrowse_Click filePath, 1
filePath1 = filePath
'reset the variable
filePath = vbNullString
cmdBrowse_Click filePath, 2
filePath2 = filePath
fileNm1 = GetFileName(filePath1, "\")
fileNm2 = GetFileName(filePath2, "\")
If IsWorkBookOpen(filePath1) Then
Set wbA = Workbooks(fileNm1)
Else
Set wbA = Workbooks.Open(filePath1)
End If
If IsWorkBookOpen(filePath2) Then
Set wbB = Workbooks.Open(fileNm2)
Else
Set wbB = Workbooks.Open(filePath2)
End If
' your code here
End Sub
Function IsWorkBookOpen(FileName As String)
Dim ff As Long, ErrNo As Long
On Error Resume Next
ff = FreeFile()
Open FileName For Input Lock Read As #ff
Close ff
ErrNo = Err
On Error GoTo 0
Select Case ErrNo
Case 0: IsWorkBookOpen = False
Case 70: IsWorkBookOpen = True
Case Else: Error ErrNo
End Select
End Function
Private Sub cmdBrowse_Click(ByRef filePath As String, num As Integer)
Dim fd As FileDialog
Set fd = Application.FileDialog(msoFileDialogFilePicker)
fd.AllowMultiSelect = False
fd.Title = "Select workbook " & num
fd.InitialView = msoFileDialogViewSmallIcons
Dim FileChosen As Integer
FileChosen = fd.Show
fd.Filters.Clear
fd.Filters.Add "Excel macros", "*.xlsx"
fd.FilterIndex = 1
If FileChosen <> -1 Then
MsgBox "You chose cancel"
filePath = ""
Else
filePath = fd.SelectedItems(1)
End If
End Sub
Function GetFileName(fullName As String, pathSeparator As String) As String
Dim i As Integer
Dim iFNLenght As Integer
iFNLenght = Len(fullName)
For i = iFNLenght To 1 Step -1
If Mid(fullName, i, 1) = pathSeparator Then Exit For
Next
GetFileName = Right(fullName, iFNLenght - i)
End Function
With modern browsers, this is easy without jQuery:
document.getElementById('yourParentDiv').querySelectorAll('[id^="q17_"]');
The querySelectorAll takes a selector (as per CSS selectors) and uses it to search children of the 'yourParentDiv' element recursively. The selector uses ^=
which means "starts with".
Note that all browsers released since June 2009 support this.
Try this
test2.removeAll(test1);
Removes from this set all of its elements that are contained in the specified collection (optional operation). If the specified collection is also a set, this operation effectively modifies this set so that its value is the asymmetric set difference of the two sets.
The problem is WHEN the event is added and EXECUTED via triggering
(the document
onload
property modification can be verified by examining the properties list).
When does this execute and modify onload
relative to the onload
event trigger:
document.addEventListener('load', ... );
before, during or after the load and/or render of the page's HTML?
This simple scURIple (cut & paste to URL) "works" w/o alert
ing as naively expected:
data:text/html;charset=utf-8,
<html content editable><head>
<script>
document.addEventListener('load', function(){ alert(42) } );
</script>
</head><body>goodbye universe - hello muiltiverse</body>
</html>
Does loading imply script contents have been executed?
A little out of this world expansion ...
Consider a slight modification:
data:text/html;charset=utf-8,
<html content editable><head>
<script>
if(confirm("expand mind?"))document.addEventListener('load', function(){ alert(42) } );
</script>
</head><body>goodbye universe - hello muiltiverse</body>
</html>
and whether the HTML has been loaded or not.
Rendering is certainly pending since goodbye universe - hello muiltiverse
is not seen on screen but, does not the confirm( ... )
have to be already loaded to be executed? ... and so document.addEventListener('load', ... )
... ?
In other words, can you execute code to check for self-loading when the code itself is not yet loaded?
Or, another way of looking at the situation, if the code is executable and executed then it has ALREADY been loaded as a done deal and to retroactively check when the transition occurred between not yet loaded and loaded is a priori fait accompli.
So which comes first: loading and executing the code or using the code's functionality though not loaded?
onload
as a window
property works because it is subordinate to the object and not self-referential as in the document
case, ie. it's the window
's contents, via document
, that determine the loaded question err situation.
PS.: When do the following fail to alert(...)
? (personally experienced gotcha's):
caveat: unless loading to the same window is really fast ... clobbering is the order of the day
so what is really needed below when using the same named window:
window.open(URIstr1,"w") .
addEventListener('load',
function(){ alert(42);
window.open(URIstr2,"w") .
addEventListener('load',
function(){ alert(43);
window.open(URIstr3,"w") .
addEventListener('load',
function(){ alert(44);
/* ... */
} )
} )
} )
alternatively, proceed each successive window.open
with:
alert("press Ok either after # alert shows pending load is done or inspired via divine intervention" );
data:text/html;charset=utf-8,
<html content editable><head><!-- tagging fluff --><script>
window.open(
"data:text/plain, has no DOM or" ,"Window"
) . addEventListener('load', function(){ alert(42) } )
window.open(
"data:text/plain, has no DOM but" ,"Window"
) . addEventListener('load', function(){ alert(4) } )
window.open(
"data:text/html,<html><body>has DOM and", "Window"
) . addEventListener('load', function(){ alert(2) } )
window.open(
"data:text/html,<html><body>has DOM and", "noWindow"
) . addEventListener('load', function(){ alert(1) } )
/* etc. including where body has onload=... in each appropriate open */
</script><!-- terminating fluff --></head></html>
which emphasize onload
differences as a document
or window
property.
Another caveat concerns preserving XSS, Cross Site Scripting, and SOP, Same Origin Policy rules which may allow loading an HTML URI but not modifying it's content to check for same. If a scURIple is run as a bookmarklet/scriplet from the same origin/site then there maybe success.
ie. From an arbitrary page, this link will do the load but not likely do alert('done')
:
<a href="javascript:window.open('view-source:http://google.ca') .
addEventListener( 'load', function(){ alert('done') } )"> src. vu </a>
but if the link is bookmarked and then clicked when viewing a google.ca
page, it does both.
test environment:
window.navigator.userAgent =
Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.0.4) Gecko/2008102920 Firefox/3.0.4 (Splashtop-v1.2.17.0)
Here you have an example of a Dockerfile that runs nginx. As mentionned by Charles, it uses the daemon off
configuration:
https://github.com/darron/docker-nginx-php5/blob/master/Dockerfile#L17
"success" : function(data){
//do stuff here
fnCallback(data);
}
Use stri_sub
function from stringi
package.
To get substring from the end, use negative numbers.
Look below for the examples:
stri_sub("abcde",1,3)
[1] "abc"
stri_sub("abcde",1,1)
[1] "a"
stri_sub("abcde",-3,-1)
[1] "cde"
You can install this package from github: https://github.com/Rexamine/stringi
It is available on CRAN now, simply type
install.packages("stringi")
to install this package.
NO, it does NOT work in Access 2013, only 2007/2010. There is no way to really convert an MDB to ACCDB in Access 2013.
iText is really easy to use.
If you requiere doc files you can call abiword (free lightweigh multi-os text procesor) from the command line, it has several conversion format convert options.
Here is an example of request execution process in its simplest form:
CloseableHttpClient httpclient = HttpClients.createDefault(); HttpGet httpget = new HttpGet("http://localhost/"); CloseableHttpResponse response = httpclient.execute(httpget); try { //do something } finally { response.close(); }
HttpClient resource deallocation: When an instance CloseableHttpClient is no longer needed and is about to go out of scope the connection manager associated with it must be shut down by calling the CloseableHttpClient#close() method.
CloseableHttpClient httpclient = HttpClients.createDefault(); try { //do something } finally { httpclient.close(); }
see the Reference to learn fundamentals.
@Scadge Since Java 7, Use of try-with-resources statement ensures that each resource is closed at the end of the statement. It can be used both for the client and for each response
try(CloseableHttpClient httpclient = HttpClients.createDefault()){
// e.g. do this many times
try (CloseableHttpResponse response = httpclient.execute(httpget)) {
//do something
}
//do something else with httpclient here
}
use as below:
<div id="getSessionStorage"></div>
For this to append anything use below code for reference:
$(document).ready(function () {
var storageVal = sessionStorage.getItem("UserName");
alert(storageVal);
$("#getSessionStorage").append(storageVal);
});
This will appear as below in html (assuming storageVal="Rishabh")
<div id="getSessionStorage">Rishabh</div>
I suggest to use utf8mb4_unicode_ci
, which is based on the Unicode standard for sorting and comparison, which sorts accurately in a very wide range of languages.
I'm not sure why your current code is failing (what is the Exception you get?), but I would like to point out this approach performs O(N-squared). Consider pre-sorting your input arrays (if they are not defined to be pre-sorted) and merging the sorted arrays:
http://www.algolist.net/Algorithms/Merge/Sorted_arrays
Sorting is generally O(N logN) and the merge is O(m+n).
command install:
conda install python=3.5
conda install python=3.6
download the most recent Anaconda installer:
Anaconda 4.2.0
Anaconda 5.2.0
reference from anaconda doc:
Assuming a
is a string. The Slice notation in python has the syntax -
list[<start>:<stop>:<step>]
So, when you do a[::-1]
, it starts from the end towards the first taking each element. So it reverses a. This is applicable for lists/tuples as well.
Example -
>>> a = '1234'
>>> a[::-1]
'4321'
Then you convert it to int and then back to string (Though not sure why you do that) , that just gives you back the string.
Here's the steps to achieve this:
Download the sendmail.zip through this link
Open sendmail.ini and set the configuration as follows:
smtp_server=smtp.gmail.com
hostname=localhost
Access your email account. Click the Gear Tool > Settings > Forwarding and POP/IMAP > IMAP access. Click "Enable IMAP", then save your changes.
Run your WAMP Server. Enable ssl_module under Apache Module.
Next, enable php_openssl and php_sockets under PHP.
Open php.ini and configure it as the codes below. Basically, you just have to set the sendmail_path.
[mail function] ; For Win32 only. ; http://php.net/smtp ;SMTP = ; http://php.net/smtp-port ;smtp_port = 25 ; For Win32 only. ; http://php.net/sendmail-from ;sendmail_from = [email protected] ; For Unix only. You may supply arguments as well (default: "sendmail -t -i"). ; http://php.net/sendmail-path sendmail_path = "C:\wamp\sendmail\sendmail.exe -t -i"
I hope this will work for you..
If you are not able to upgrade your Python version to 2.7.9, and want to suppress warnings,
you can downgrade your 'requests' version to 2.5.3:
pip install requests==2.5.3
In your code you are assigning a native method to a property of custom object.
When you call support.animationFrame(function () {})
, it is executed in the context of current object (ie support). For the native requestAnimationFrame function to work properly, it must be executed in the context of window
.
So the correct usage here is support.animationFrame.call(window, function() {});
.
The same happens with alert too:
var myObj = {
myAlert : alert //copying native alert to an object
};
myObj.myAlert('this is an alert'); //is illegal
myObj.myAlert.call(window, 'this is an alert'); // executing in context of window
Another option is to use Function.prototype.bind() which is part of ES5 standard and available in all modern browsers.
var _raf = window.requestAnimationFrame ||
window.mozRequestAnimationFrame ||
window.webkitRequestAnimationFrame ||
window.msRequestAnimationFrame ||
window.oRequestAnimationFrame;
var support = {
animationFrame: _raf ? _raf.bind(window) : null
};
An IntentService is an extension of a Service that is made to ease the execution of a task that needs to be executed in background and in a seperated thread.
IntentService starts, create a thread and runs its task in the thread. once done, it cleans everything. Only one instance of a IntentService can run at the same time, several calls are enqueued.
It is very simple to use and very convenient for a lot of uses, for instance downloading stuff. But it has limitations that can make you want to use instead the more basic (not simple) Service.
For example, a service connected to a xmpp server and bound by activities cannot be simply done using an IntentService. You'll end up ignoring or overriding IntentService stuffs.
I tried all answers above and nothing worked. Actually, we need 3 steps from above answers together to make it work:
As suggested by Flavio; add CORS configuration on your bucket:
<CORSConfiguration>
<CORSRule>
<AllowedOrigin>*</AllowedOrigin>
<AllowedMethod>GET</AllowedMethod>
</CORSRule>
</CORSConfiguration>
On the image; mention crossorigin:
<img href="abc.jpg" crossorigin="anonymous">
Are you using a CDN? If everything works fine connecting to origin server but NOT via CDN; it means you need some setting on your CDN like accept CORS headers. Exact setting depends on which CDN you are using.
since you set your itemsource to your collection, your textbox is tied to each individual item in that collection. the selected item property is useful in this scenario if you were trying to do a master-detail form, having 2 listboxes. you would bind the second listbox's itemsource to the child collection of rules. in otherwords the selected item alerts outside controls that your source has changed, internal controls(those inside your datatemplate already are aware of the change.
and to answer your question yes in most circumstances setting the itemsource is the same as setting the datacontext of the control.
When using Windows.Web.Http namespace, for POST instead of FormUrlEncodedContent we write HttpFormUrlEncodedContent. Also the response is type of HttpResponseMessage. The rest is as Evan Mulawski wrote down.
This is the simplest solution working for me.
$('#your_modal_id').clone().prop("id", "new_modal_id").appendTo("target_container");
This has become very easy with Jackson 2.0 and the Joda module.
ObjectMapper mapper = new ObjectMapper();
mapper.registerModule(new JodaModule());
Maven dependency:
<dependency>
<groupId>com.fasterxml.jackson.datatype</groupId>
<artifactId>jackson-datatype-joda</artifactId>
<version>2.1.1</version>
</dependency>
Code and documentation: https://github.com/FasterXML/jackson-datatype-joda
Binaries: http://repo1.maven.org/maven2/com/fasterxml/jackson/datatype/jackson-datatype-joda/
Android complete source code for adding events and reminders with start and end time format.
/** Adds Events and Reminders in Calendar. */
private void addReminderInCalendar() {
Calendar cal = Calendar.getInstance();
Uri EVENTS_URI = Uri.parse(getCalendarUriBase(true) + "events");
ContentResolver cr = getContentResolver();
TimeZone timeZone = TimeZone.getDefault();
/** Inserting an event in calendar. */
ContentValues values = new ContentValues();
values.put(CalendarContract.Events.CALENDAR_ID, 1);
values.put(CalendarContract.Events.TITLE, "Sanjeev Reminder 01");
values.put(CalendarContract.Events.DESCRIPTION, "A test Reminder.");
values.put(CalendarContract.Events.ALL_DAY, 0);
// event starts at 11 minutes from now
values.put(CalendarContract.Events.DTSTART, cal.getTimeInMillis() + 11 * 60 * 1000);
// ends 60 minutes from now
values.put(CalendarContract.Events.DTEND, cal.getTimeInMillis() + 60 * 60 * 1000);
values.put(CalendarContract.Events.EVENT_TIMEZONE, timeZone.getID());
values.put(CalendarContract.Events.HAS_ALARM, 1);
Uri event = cr.insert(EVENTS_URI, values);
// Display event id
Toast.makeText(getApplicationContext(), "Event added :: ID :: " + event.getLastPathSegment(), Toast.LENGTH_SHORT).show();
/** Adding reminder for event added. */
Uri REMINDERS_URI = Uri.parse(getCalendarUriBase(true) + "reminders");
values = new ContentValues();
values.put(CalendarContract.Reminders.EVENT_ID, Long.parseLong(event.getLastPathSegment()));
values.put(CalendarContract.Reminders.METHOD, Reminders.METHOD_ALERT);
values.put(CalendarContract.Reminders.MINUTES, 10);
cr.insert(REMINDERS_URI, values);
}
/** Returns Calendar Base URI, supports both new and old OS. */
private String getCalendarUriBase(boolean eventUri) {
Uri calendarURI = null;
try {
if (android.os.Build.VERSION.SDK_INT <= 7) {
calendarURI = (eventUri) ? Uri.parse("content://calendar/") : Uri.parse("content://calendar/calendars");
} else {
calendarURI = (eventUri) ? Uri.parse("content://com.android.calendar/") : Uri
.parse("content://com.android.calendar/calendars");
}
} catch (Exception e) {
e.printStackTrace();
}
return calendarURI.toString();
}
<uses-permission android:name="android.permission.READ_CALENDAR" />
<uses-permission android:name="android.permission.WRITE_CALENDAR" />
It seems that document.getElementById('overlayBtn');
is returning null
because it executes before the DOM fully loads.
If you put this line of code under
window.onload=function(){
-- put your code here
}
then it will run without issue.
Example:
window.onload=function(){
var mb = document.getElementById("b");
mb.addEventListener("click", handler);
mb.addEventListener("click", handler2);
}
function handler() {
$("p").html("<br>" + $("p").text() + "<br>You clicked me-1!<br>");
}
function handler2() {
$("p").html("<br>" + $("p").text() + "<br>You clicked me-2!<br>");
}
Simply use an image extension like .jpeg
or .png
.
<input type="radio" name="radio" value="upi">upi
<input type="radio" name="radio" value="bankAcc">Bank
<script type="text/javascript">
$(document).ready(function() {
$('input[type=radio][name=radio]').change(function() {
if (this.value == 'upi') {
//write your logic here
}
else if (this.value == 'bankAcc') {
//write your logic here
}
});
</script>
$(this).find('.info').animate({'margin-top': '-50px', opacity: 0.5 }, 1000);
Not MarginTop. It works
This can also happen if you are attempting to connect over HTTPS and the server is not configured to handle SSL connections correctly.
I would check your application servers SSL settings and make sure that the certification is configured correctly.
no. You can use UDF in which you can pass parameters.
I see that you've tagged this question with the google-spreadsheet-api
tag. So by "drop-down" do you mean Google App Script's ListBox? If so, you may toggle a user's ability to select multiple items from the ListBox with a simple true/false value.
Here's an example:
`var lb = app.createListBox(true).setId('myId').setName('myLbName');`
Notice that multiselect is enabled because of the word true.
Heap allocations are possible for static variables if you use the lazy_static macro as seen in the docs
Using this macro, it is possible to have statics that require code to be executed at runtime in order to be initialized. This includes anything requiring heap allocations, like vectors or hash maps, as well as anything that requires function calls to be computed.
// Declares a lazily evaluated constant HashMap. The HashMap will be evaluated once and
// stored behind a global static reference.
use lazy_static::lazy_static;
use std::collections::HashMap;
lazy_static! {
static ref PRIVILEGES: HashMap<&'static str, Vec<&'static str>> = {
let mut map = HashMap::new();
map.insert("James", vec!["user", "admin"]);
map.insert("Jim", vec!["user"]);
map
};
}
fn show_access(name: &str) {
let access = PRIVILEGES.get(name);
println!("{}: {:?}", name, access);
}
fn main() {
let access = PRIVILEGES.get("James");
println!("James: {:?}", access);
show_access("Jim");
}
YES you can!! The solution should be easy, safe, and performant...
I'm new to postgresql, but it seems you can create computed columns by using an expression index, paired with a view (the view is optional, but makes makes life a bit easier).
Suppose my computation is md5(some_string_field)
, then I create the index as:
CREATE INDEX some_string_field_md5_index ON some_table(MD5(some_string_field));
Now, any queries that act on MD5(some_string_field)
will use the index rather than computing it from scratch. For example:
SELECT MAX(some_field) FROM some_table GROUP BY MD5(some_string_field);
You can check this with explain.
However at this point you are relying on users of the table knowing exactly how to construct the column. To make life easier, you can create a VIEW
onto an augmented version of the original table, adding in the computed value as a new column:
CREATE VIEW some_table_augmented AS
SELECT *, MD5(some_string_field) as some_string_field_md5 from some_table;
Now any queries using some_table_augmented
will be able to use some_string_field_md5
without worrying about how it works..they just get good performance. The view doesn't copy any data from the original table, so it is good memory-wise as well as performance-wise. Note however that you can't update/insert into a view, only into the source table, but if you really want, I believe you can redirect inserts and updates to the source table using rules (I could be wrong on that last point as I've never tried it myself).
Edit: it seems if the query involves competing indices, the planner engine may sometimes not use the expression-index at all. The choice seems to be data dependant.
I have used both R and MATLAB to solve problems and construct models related to Environmental Engineering and there is a lot of overlap between the two systems. In my opinion, the advantages of MATLAB lie in specialized domain-specific applications. Some examples are:
Functions such as streamline that aid in fluid dynamics investigations.
Toolboxes such as the image processing toolset. I have not found a R package that provides an equivalent implementation of tools like the watershed algorithm.
In my opinion MATLAB provides far better interactive graphics capabilities. However, I think R produces better static print-quality graphics, depending on the application. MATLAB's symbolic math toolbox is also better integrated and more capable than R equivalents such as Ryacas or rSymPy. The existence of the MATLAB compiler also allows systems based on MATLAB code to be deployed independently of the MATLAB environment-- although it's availability will depend on how much money you have to throw around.
Another thing I should note is that the MATLAB debugger is one of the best I have worked with.
The principle advantage I see with R is the openness of the system and the ease with which it can be extended. This has resulted in an incredible diversity of packages on CRAN. I know Mathworks also maintains a repository of user-contributed toolboxes and I can't make a fair comparison as I have not used it that much.
The openness of R also extends to linking in compiled code. A while back I had a model written in Fortran and I was trying to decide between using R or MATLAB as a front-end to help prepare input and process results. I spent an hour reading about the MEX interface to compiled code. When I found that I would have to write and maintain a separate Fortran routine that did some intricate pointer juggling in order to manage the interface, I shelved MATLAB.
The R interface consists of calling .Fortran( [subroutine name], [argument list]) and is simply quicker and cleaner.
package logicprogram;
import java.io.*;
public class Strinrevers {
public static void main(String args[])throws IOException
{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
System.out.println("enter data");
String data=br.readLine();
System.out.println(data);
String str="";
char cha[]=data.toCharArray();
int l=data.length();
int k=l-1;
System.out.println(l);
for(int i=0;k>=i;k--)
{
str+=cha[k];
}
//String text=String.valueOf(ch);
System.out.println(str);
}
}
That is called a shebang, it tells the shell what program to interpret the script with, when executed.
In your example, the script is to be interpreted and run by the bash shell.
Some other example shebangs are:
(From Wikipedia)
#!/bin/sh — Execute the file using sh, the Bourne shell, or a compatible shell
#!/bin/csh — Execute the file using csh, the C shell, or a compatible shell
#!/usr/bin/perl -T — Execute using Perl with the option for taint checks
#!/usr/bin/php — Execute the file using the PHP command line interpreter
#!/usr/bin/python -O — Execute using Python with optimizations to code
#!/usr/bin/ruby — Execute using Ruby
and a few additional ones I can think off the top of my head, such as:
#!/bin/ksh
#!/bin/awk
#!/bin/expect
In a script with the bash shebang, for example, you would write your code with bash syntax; whereas in a script with expect shebang, you would code it in expect syntax, and so on.
Response to updated portion:
It depends on what /bin/sh
actually points to on your system. Often it is just a symlink to /bin/bash
. Sometimes portable scripts are written with #!/bin/sh
just to signify that it's a shell script, but it uses whichever shell is referred to by /bin/sh
on that particular system (maybe it points to /bin/bash
, /bin/ksh
or /bin/zsh
)
Active Directory does not store the group membership on user objects. It only stores the Member list on the group. The tools show the group membership on user objects by doing queries for it.
How about:
(&(objectClass=group)(member=cn=my,ou=full,dc=domain))
(You forgot the (& ) bit in your example in the question as well).
By "constant reference" I am guessing you really mean "reference to constant data". Pointers on the other hand, can be a constant pointer (the pointer itself is constant, not the data it points to), a pointer to constant data, or both.
I know this is a really old post, but I found it in searching for a solution to the same problem. I don't want a nested if-statement, and Switch is apparently newer than the version of Excel I'm using. I figured out what was going wrong with my code, so I figured I'd share here in case it helps someone else.
I remembered that VLOOKUP requires the source table to be sorted alphabetically/numerically for it to work. I was initially trying to do this...
=LOOKUP(LOWER(LEFT($T$3, 1)), {"s","l","m"}, {-1,1,0})
and it started working when I did this...
=LOOKUP(LOWER(LEFT($T$3, 1)), {"l","m","s"}, {1,0,-1})
I was initially thinking the last value might turn out to be a default, so I wanted the zero at the last place. That doesn't seem to be the behavior anyway, so I just put the possible matches in order, and it worked.
Edit: As a final note, I see that the example in the original post has letters in alphabetical order, but I imagine the real use case might have been different if the error was happening and the letters A, B, and C were just examples.
The statement about CMake being a "build generator" is a common misconception.
It's not technically wrong; it just describes HOW it works, but not WHAT it does.
In the context of the question, they do the same thing: take a bunch of C/C++ files and turn them into a binary.
So, what is the real difference?
CMake is much more high-level. It's tailored to compile C++, for which you write much less build code, but can be also used for general purpose build. make
has some built-in C/C++ rules as well, but they are useless at best.
CMake
does a two-step build: it generates a low-level build script in ninja
or make
or many other generators, and then you run it. All the shell script pieces that are normally piled into Makefile
are only executed at the generation stage. Thus, CMake
build can be orders of magnitude faster.
The grammar of CMake
is much easier to support for external tools than make's.
Once make
builds an artifact, it forgets how it was built. What sources it was built from, what compiler flags? CMake
tracks it, make
leaves it up to you. If one of library sources was removed since the previous version of Makefile
, make
won't rebuild it.
Modern CMake
(starting with version 3.something) works in terms of dependencies between "targets". A target is still a single output file, but it can have transitive ("public"/"interface" in CMake terms) dependencies.
These transitive dependencies can be exposed to or hidden from the dependent packages. CMake
will manage directories for you. With make
, you're stuck on a file-by-file and manage-directories-by-hand level.
You could code up something in make
using intermediate files to cover the last two gaps, but you're on your own. make
does contain a Turing complete language (even two, sometimes three counting Guile); the first two are horrible and the Guile is practically never used.
To be honest, this is what CMake
and make
have in common -- their languages are pretty horrible. Here's what comes to mind:
CMake
has three data types: string, list, and a target with properties. make
has one: string;set_property(TARGET helloworld APPEND PROPERTY INCLUDE_DIRECTORIES "${CMAKE_CURRENT_SOURCE_DIR}")
;We apply StandardScalar()
on a row basis.
So, for each row in a column (I am assuming that you are working with a Pandas DataFrame):
x_new = (x_original - mean_of_distribution) / std_of_distribution
Few points -
It is called Standard Scalar as we are dividing it by the standard deviation of the distribution (distr. of the feature). Similarly, you can guess for MinMaxScalar()
.
The original distribution remains the same after applying StandardScalar()
. It is a common misconception that the distribution gets changed to a Normal Distribution. We are just squashing the range into [0, 1].
The answer here (https://stackoverflow.com/a/22408965/2236315) by @adrianoesch should help (e.g., solves "If you know of a solution that does not require the awkward workaround mentioned in your comment (shift the column names, copy the data), that would be great." and "...requiring that the data be copied" proposed by @Frank).
Note that if you open in some text editor, you should see that the number of header fields less than number of columns below the header row. In my case, the data set had a "," missing at the end of the last header field.
The current accepted answer doesn't work for multiple groupings.
Try this when you need to operate on categories of column row-values.
Suppose I have the following data:
+---------+-----------+
| column1 | column2 |
+---------+-----------+
| cat | Felon |
| cat | Purz |
| dog | Fido |
| dog | Beethoven |
| dog | Buddy |
| bird | Tweety |
+---------+-----------+
And I want this as my output:
+------+----------------------+
| type | names |
+------+----------------------+
| cat | Felon,Purz |
| dog | Fido,Beethoven,Buddy |
| bird | Tweety |
+------+----------------------+
(If you're following along:
create table #column_to_list (column1 varchar(30), column2 varchar(30))
insert into #column_to_list
values
('cat','Felon'),
('cat','Purz'),
('dog','Fido'),
('dog','Beethoven'),
('dog','Buddy'),
('bird','Tweety')
)
Now – I don’t want to go into all the syntax, but as you can see, this does the initial trick for us:
select ',' + cast(column2 as varchar(255)) as [text()]
from #column_to_list sub
where column1 = 'dog'
for xml path('')
--Using "as [text()]" here is specific to the “for XML” line after our where clause and we can’t give a name to our selection, hence the weird column_name
output:
+------------------------------------------+
| XML_F52E2B61-18A1-11d1-B105-00805F49916B |
+------------------------------------------+
| ,Fido,Beethoven,Buddy |
+------------------------------------------+
You can see it’s limited in that it was for just one grouping (where column1 = ‘dog’) and it left a comma in the front, and additionally it’s named weird.
So, first let's handle the leading comma using the 'stuff' function and name our column stuff_list:
select stuff([list],1,1,'') as stuff_list
from (select ',' + cast(column2 as varchar(255)) as [text()]
from #column_to_list sub
where column1 = 'dog'
for xml path('')
) sub_query([list])
--"sub_query([list])" just names our column as '[list]' so we can refer to it in the stuff function.
Output:
+----------------------+
| stuff_list |
+----------------------+
| Fido,Beethoven,Buddy |
+----------------------+
Finally let’s just mush this into a select statement, noting the reference to the top_query alias defining which column1 we want (on the 5th line here):
select top_query.column1,
(select stuff([list],1,1,'') as stuff_list
from (select ',' + cast(column2 as varchar(255)) as [text()]
from #column_to_list sub
where sub.column1 = top_query.column1
for xml path('')
) sub_query([list])
) as pet_list
from #column_to_list top_query
group by column1
order by column1
output:
+---------+----------------------+
| column1 | pet_list |
+---------+----------------------+
| bird | Tweety |
| cat | Felon,Purz |
| dog | Fido,Beethoven,Buddy |
+---------+----------------------+
And we’re done.
You can read more here:
The global Git configuration file is stored at $HOME/.gitconfig
on all platforms.
However, you can simply open a terminal and execute git config
, which will write the appropriate changes to this file. You shouldn't need to manually tweak .gitconfig
, unless you particularly want to.
At long last, we're excited to announce that we FINALLY implemented copy and paste support for Linux/WSL instances in Windows Console via CTRL + SHIFT + [C|V]!
You can enable/disable this feature in case you find a keyboard collision with a command-line app, but this should start working when you install and run any Win10 builds >= 17643.
Thanks for your patience while we re-engineered Console's internals to allow this feature to work :)
Yes it would be bad practice to parse it yourself. Take a look at SimpleDateFormat, it will turn the String into a Date and you can set the Date into a Calendar instance.
Actually, you can, even though accepted answer saying that you can't.
There is a _JAVA_OPTIONS
environment variable, more about it here
You need to enable SSL in your PHP config. Load up php.ini
and find a line with the following:
;extension=php_openssl.dll
Uncomment it. :D
(by removing the semicolon from the statement)
extension=php_openssl.dll
If not using Word2Vec we have other model to find it using BERT for embed. Below are reference link https://github.com/UKPLab/sentence-transformers
pip install -U sentence-transformers
from sentence_transformers import SentenceTransformer
import scipy.spatial
embedder = SentenceTransformer('bert-base-nli-mean-tokens')
# Corpus with example sentences
corpus = ['A man is eating a food.',
'A man is eating a piece of bread.',
'The girl is carrying a baby.',
'A man is riding a horse.',
'A woman is playing violin.',
'Two men pushed carts through the woods.',
'A man is riding a white horse on an enclosed ground.',
'A monkey is playing drums.',
'A cheetah is running behind its prey.'
]
corpus_embeddings = embedder.encode(corpus)
# Query sentences:
queries = ['A man is eating pasta.', 'Someone in a gorilla costume is playing a set of drums.', 'A cheetah chases prey on across a field.']
query_embeddings = embedder.encode(queries)
# Find the closest 5 sentences of the corpus for each query sentence based on cosine similarity
closest_n = 5
for query, query_embedding in zip(queries, query_embeddings):
distances = scipy.spatial.distance.cdist([query_embedding], corpus_embeddings, "cosine")[0]
results = zip(range(len(distances)), distances)
results = sorted(results, key=lambda x: x[1])
print("\n\n======================\n\n")
print("Query:", query)
print("\nTop 5 most similar sentences in corpus:")
for idx, distance in results[0:closest_n]:
print(corpus[idx].strip(), "(Score: %.4f)" % (1-distance))
Other Link to follow https://github.com/hanxiao/bert-as-service
No need to use rectangles ... compare the coordinates of 2 players constantly.
like
if(x1===x&&y1==y)
remember to increase the range of x when ur comparing.
if ur rectangle width is 30 take as if (x1>x&&x2>x+30)
..likewise y
You probably had a typo when you first ran it.
evaluating 0.5 % 0.3
returns '0.2' (A double) as expected.
Mindprod has a good overview of how modulus works in Java.
I have just copied and moved a Magento site to a local area so I could work on it offline and had the same problem.
But in the end I found out Magento was forcing a redirect from http to https and I didn't have a SSL setup. So this solved my problem http://www.magentocommerce.com/wiki/recover/ssl_access_with_phpmyadmin
It pretty much says set web/secure/use_in_adminhtml value from 1 to 0 in the core_config_data to allow non-secure access to the admin area
People don't see the nice cool Stream producers all over the Java libs.
public static double[] list(){
return new Random().ints().asDoubleStream().toArray();
}
Are you using php 5.4 on your local? the render line is using the new way of initializing arrays. Try replacing ["title" => "Welcome "]
with array("title" => "Welcome ")
The official way to find out if you have 4.5 installed (and not 4.0) is in the registry keys :
HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\NET Framework Setup\NDP\v4\Full
Relesae DWORD needs to be bigger than 378675 Here is the Microsoft doc for it
all the other answers of checking the minor version after 4.0.30319.xxxxx seem correct though (msbuild.exe -version , or properties of clr.dll), i just needed something documented (not a blog)
You can kill two birds with one regex stone:
>>> r = """
... \n\tName: John Smith
... \n\t Home: Anytown USA
... \n\t Phone: 555-555-555
... \n\t Other Home: Somewhere Else
... \n\t Notes: Other data
... \n\tName: Jane Smith
... \n\t Misc: Data with spaces
... """
>>> import re
>>> print re.findall(r'(\S[^:]+):\s*(.*\S)', r)
[('Name', 'John Smith'), ('Home', 'Anytown USA'), ('Phone', '555-555-555'), ('Other Home', 'Somewhere Else'), ('Notes', 'Other data'), ('Name', 'Jane Smith'), ('Misc', 'Data with spaces')]
>>>
if(isset($_SESSION))
{}
else
{}
You can use:
$ jq 'keys' file.json
$ cat file.json:
{ "Archiver-Version" : "Plexus Archiver", "Build-Id" : "", "Build-Jdk" : "1.7.0_07", "Build-Number" : "", "Build-Tag" : "", "Built-By" : "cporter", "Created-By" : "Apache Maven", "Implementation-Title" : "northstar", "Implementation-Vendor-Id" : "com.test.testPack", "Implementation-Version" : "testBox", "Manifest-Version" : "1.0", "appname" : "testApp", "build-date" : "02-03-2014-13:41", "version" : "testBox" }
$ jq 'keys' file.json
[
"Archiver-Version",
"Build-Id",
"Build-Jdk",
"Build-Number",
"Build-Tag",
"Built-By",
"Created-By",
"Implementation-Title",
"Implementation-Vendor-Id",
"Implementation-Version",
"Manifest-Version",
"appname",
"build-date",
"version"
]
UPDATE: To create a BASH array using these keys:
Using BASH 4+:
mapfile -t arr < <(jq -r 'keys[]' ms.json)
On older BASH you can do:
arr=()
while IFS='' read -r line; do
arr+=("$line")
done < <(jq 'keys[]' ms.json)
Then print it:
printf "%s\n" ${arr[@]}
"Archiver-Version"
"Build-Id"
"Build-Jdk"
"Build-Number"
"Build-Tag"
"Built-By"
"Created-By"
"Implementation-Title"
"Implementation-Vendor-Id"
"Implementation-Version"
"Manifest-Version"
"appname"
"build-date"
"version"
I ran into this issue with custom types in stored procedures, and solved it with the script below. I didn't fully understand the scripts above, and I follow the rule of "if you don't know what it does, don't do it".
In a nutshell, I rename the old type, and create a new one with the original type name. Then, I tell SQL Server to refresh its details about each stored procedure using the custom type. You have to do this, as everything is still "compiled" with reference to the old type, even with the rename. In this case, the type I needed to change was "PrizeType". I hope this helps. I'm looking for feedback, too, so I learn :)
Note that you may need to go to Programmability > Types > [Appropriate User Type] and delete the object. I found that DROP TYPE doesn't appear to always drop the type even after using the statement.
/* Rename the UDDT you want to replace to another name */
exec sp_rename 'PrizeType', 'PrizeTypeOld', 'USERDATATYPE';
/* Add the updated UDDT with the new definition */
CREATE TYPE [dbo].[PrizeType] AS TABLE(
[Type] [nvarchar](50) NOT NULL,
[Description] [nvarchar](max) NOT NULL,
[ImageUrl] [varchar](max) NULL
);
/* We need to force stored procedures to refresh with the new type... let's take care of that. */
/* Get a cursor over a list of all the stored procedures that may use this and refresh them */
declare sprocs cursor
local static read_only forward_only
for
select specific_name from information_schema.routines where routine_type = 'PROCEDURE'
declare @sprocName varchar(max)
open sprocs
fetch next from sprocs into @sprocName
while @@fetch_status = 0
begin
print 'Updating ' + @sprocName;
exec sp_refreshsqlmodule @sprocName
fetch next from sprocs into @sprocName
end
close sprocs
deallocate sprocs
/* Drop the old type, now that everything's been re-assigned; must do this last */
drop type PrizeTypeOld;
Use UIWindow
or UIView
's safeAreaInsets
.bottom
.top
.left
.right
// #available(iOS 11.0, *)
// height - UIApplication.shared.keyWindow!.safeAreaInsets.bottom
// On iPhoneX
// UIApplication.shared.keyWindow!.safeAreaInsets.top = 44
// UIApplication.shared.keyWindow!.safeAreaInsets.bottom = 34
// Other devices
// UIApplication.shared.keyWindow!.safeAreaInsets.top = 0
// UIApplication.shared.keyWindow!.safeAreaInsets.bottom = 0
// example
let window = UIApplication.shared.keyWindow!
let viewWidth = window.frame.size.width
let viewHeight = window.frame.size.height - window.safeAreaInsets.bottom
let viewFrame = CGRect(x: 0, y: 0, width: viewWidth, height: viewHeight)
let aView = UIView(frame: viewFrame)
aView.backgroundColor = .red
view.addSubview(aView)
aView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
Just a quick change to wp-config.php
define('FS_METHOD','direct');
That’s it, enjoy your wordpress updates without ftp!
Alternate Method:
There are hosts out there that will prevent this method from working to ease your WordPress updating. Fortunately, there is another way to keep this pest from prompting you for your FTP user name and password.
Again, after the MYSQL login declarations in your wp-config.php file, add the following:
define("FTP_HOST", "localhost");
define("FTP_USER", "yourftpusername");
define("FTP_PASS", "yourftppassword");
I used Object.Keys to get the array of socket connected. Then in the same array iterate with map function to build a new array of objects
var connectedUsers = Object.keys(io.sockets.connected).map(function(socketId) {
return { socket_id : socketId, socket_username: io.sockets.connected[socketId].username };
});
// test
console.log(connectedUsers);
Perhaps this answer can help to get socket id/username array.
Another approach to test just for a JSON response (not that the content within contains an expected value), is to parse the response using ActiveSupport:
ActiveSupport::JSON.decode(response.body).should_not be_nil
If the response is not parsable JSON an exception will be thrown and the test will fail.
This will do it:
#signin input {
background-color:#FFF;
min-height:200px;
}
By definition arrays are fixed size. You can use instead an Arraylist wich is that, a "dynamic size" array. Actually what happens is that the VM "adjust the size"* of the array exposed by the ArrayList.
*using back-copy arrays
Though I'm usually against it (though in this case it seems that you have a genuine reason), have you tried providing any query hints on the SP version of the query? If SQL Server is preparing a different execution plan in those two instances, can you use a hint to tell it what index to use, so that the plan matches the first one?
For some examples, you can go here.
EDIT: If you can post your query plan here, perhaps we can identify some difference between the plans that's telling.
SECOND: Updated the link to be SQL-2000 specific. You'll have to scroll down a ways, but there's a second titled "Table Hints" that's what you're looking for.
THIRD: The "Bad" query seems to be ignoring the [IX_Openers_SessionGUID] on the "Openers" table - any chance adding an INDEX hint to force it to use that index will change things?
wget -O- http://www.example.com/cronit.php >> /dev/null
This means send the file to stdout, and send stdout to /dev/null
If you are using eclipse plugin, double click on the app-name in My Heroku Applications. In Processes tab, press Scale Button. A small window will pop-up. Increase/decrease the count and just say OK.
switch(KEYEVENT.getKeyCode()){
case KeyEvent.VK_ENTER:
// I was trying to use case 13 from the ascii table.
//Krewn Generated method stub...
break;
}
Diffuse is my favourite but of course I am biased. :-) It is very easy to use:
$ diffuse "mine" "output" "theirs"
Diffuse is a small and simple text merge tool written in Python. With Diffuse, you can easily merge, edit, and review changes to your code. Diffuse is free software.
Just return the following:
return Unauthorized();
Just use this constructor of List<T>
. It accepts any IEnumerable<T>
as an argument.
string[] arr = ...
List<string> list = new List<string>(arr);
I am opening user controls depending on what user controls the user have access to specified in a database. So I used this method to get the TypeName...
Dim strType As String = GetType(Namespace.ClassName).AssemblyQualifiedName.ToString
Dim obj As UserControl = Activator.CreateInstance(Type.GetType(strType))
So now one can use the value returned in strType to create an instance of that object.