To quote the documentation:
Typical implementations create a new instance of the class by invoking the superclass's __new__() method using "super(currentclass, cls).__new__(cls[, ...])"with appropriate arguments and then modifying the newly-created instance as necessary before returning it.
...
If __new__() does not return an instance of cls, then the new instance's __init__() method will not be invoked.
__new__() is intended mainly to allow subclasses of immutable types (like int, str, or tuple) to customize instance creation.
A default constructor is a constructor that either has no parameters, or if it has parameters, all the parameters have default values.
Everything except for point 2 is correct. There are many different notations for signed ints, some implementations use the first, others use the last and yet others use something completely different. That all depends on the platform you're working with.
@Bruno Lavit has a great answer, but if you want you can just access the log and download it as txt file to your workspace from the job's URL:
${BUILD_URL}/consoleText
Then it's only a matter of downloading this page to your ${Workspace}
Invoke ANT
" and use the GET targetGood luck!
Edit:
The actual log file on the file system is not on the slave, but kept in the Master machine. You can find it under: $JENKINS_HOME/jobs/$JOB_NAME/builds/lastSuccessfulBuild/log
If you're looking for another build just replace lastSuccessfulBuild
with the build you're looking for.
You typically restore purchases with this code:
[[SKPaymentQueue defaultQueue] restoreCompletedTransactions];
It will reinvoke -paymentQueue:updatedTransactions
on the observer(s) for the purchased items. This is useful for users who reinstall the app after deletion or install it on a different device.
Not all types of In-App purchases can be restored.
If you want to lookup/associate an object with a unique identifier without modifying the underlying object, you can use a WeakMap
:
// Note that object must be an object or array,
// NOT a primitive value like string, number, etc.
var objIdMap=new WeakMap, objectCount = 0;
function objectId(object){
if (!objIdMap.has(object)) objIdMap.set(object,++objectCount);
return objIdMap.get(object);
}
var o1={}, o2={}, o3={a:1}, o4={a:1};
console.log( objectId(o1) ) // 1
console.log( objectId(o2) ) // 2
console.log( objectId(o1) ) // 1
console.log( objectId(o3) ) // 3
console.log( objectId(o4) ) // 4
console.log( objectId(o3) ) // 3
Using a WeakMap
instead of Map
ensures that the objects can still be garbage-collected.
String value = "{first_name = naresh,last_name = kumar,gender = male}"
Let's start
{
and }
from the String
>>first_name = naresh,last_name = kumar,gender = maleString
from ,
>> array of 3 elementarray
with 3
elementarray
and split each element by =
Map<String,String>
put each part separated by =
. first part as Key
and second part as Value
It represents the scope (the lifetime) of the bean. This is easier to understand if you are familiar with "under the covers" working of a basic servlet web application: How do servlets work? Instantiation, sessions, shared variables and multithreading.
@Request/View/Flow/Session/ApplicationScoped
A @RequestScoped
bean lives as long as a single HTTP request-response cycle (note that an Ajax request counts as a single HTTP request too). A @ViewScoped
bean lives as long as you're interacting with the same JSF view by postbacks which call action methods returning null
/void
without any navigation/redirect. A @FlowScoped
bean lives as long as you're navigating through the specified collection of views registered in the flow configuration file. A @SessionScoped
bean lives as long as the established HTTP session. An @ApplicationScoped
bean lives as long as the web application runs. Note that the CDI @Model
is basically a stereotype for @Named @RequestScoped
, so same rules apply.
Which scope to choose depends solely on the data (the state) the bean holds and represents. Use @RequestScoped
for simple and non-ajax forms/presentations. Use @ViewScoped
for rich ajax-enabled dynamic views (ajaxbased validation, rendering, dialogs, etc). Use @FlowScoped
for the "wizard" ("questionnaire") pattern of collecting input data spread over multiple pages. Use @SessionScoped
for client specific data, such as the logged-in user and user preferences (language, etc). Use @ApplicationScoped
for application wide data/constants, such as dropdown lists which are the same for everyone, or managed beans without any instance variables and having only methods.
Abusing an @ApplicationScoped
bean for session/view/request scoped data would make it to be shared among all users, so anyone else can see each other's data which is just plain wrong. Abusing a @SessionScoped
bean for view/request scoped data would make it to be shared among all tabs/windows in a single browser session, so the enduser may experience inconsitenties when interacting with every view after switching between tabs which is bad for user experience. Abusing a @RequestScoped
bean for view scoped data would make view scoped data to be reinitialized to default on every single (ajax) postback, causing possibly non-working forms (see also points 4 and 5 here). Abusing a @ViewScoped
bean for request, session or application scoped data, and abusing a @SessionScoped
bean for application scoped data doesn't affect the client, but it unnecessarily occupies server memory and is plain inefficient.
Note that the scope should rather not be chosen based on performance implications, unless you really have a low memory footprint and want to go completely stateless; you'd need to use exclusively @RequestScoped
beans and fiddle with request parameters to maintain the client's state. Also note that when you have a single JSF page with differently scoped data, then it's perfectly valid to put them in separate backing beans in a scope matching the data's scope. The beans can just access each other via @ManagedProperty
in case of JSF managed beans or @Inject
in case of CDI managed beans.
@CustomScoped/NoneScoped/Dependent
It's not mentioned in your question, but (legacy) JSF also supports @CustomScoped
and @NoneScoped
, which are rarely used in real world. The @CustomScoped
must refer a custom Map<K, Bean>
implementation in some broader scope which has overridden Map#put()
and/or Map#get()
in order to have more fine grained control over bean creation and/or destroy.
The JSF @NoneScoped
and CDI @Dependent
basically lives as long as a single EL-evaluation on the bean. Imagine a login form with two input fields referring a bean property and a command button referring a bean action, thus with in total three EL expressions, then effectively three instances will be created. One with the username set, one with the password set and one on which the action is invoked. You normally want to use this scope only on beans which should live as long as the bean where it's being injected. So if a @NoneScoped
or @Dependent
is injected in a @SessionScoped
, then it will live as long as the @SessionScoped
bean.
As last, JSF also supports the flash scope. It is backed by a short living cookie which is associated with a data entry in the session scope. Before the redirect, a cookie will be set on the HTTP response with a value which is uniquely associated with the data entry in the session scope. After the redirect, the presence of the flash scope cookie will be checked and the data entry associated with the cookie will be removed from the session scope and be put in the request scope of the redirected request. Finally the cookie will be removed from the HTTP response. This way the redirected request has access to request scoped data which was been prepared in the initial request.
This is actually not available as a managed bean scope, i.e. there's no such thing as @FlashScoped
. The flash scope is only available as a map via ExternalContext#getFlash()
in managed beans and #{flash}
in EL.
If you are changing the font size, but it is only working for the currently open file, then I suspect that you are changing the wrong preferences.
Check that you do not have per-project preferences. These will override the top-level preferences.
Per comment below, this has moved to the Eclipse Preferences menu (no longer named the Window menu).
The Window menu is live again, that is, menu Window ? Preferences.
Note Be sure to check out the ChandraBhan Singh's answer, it shows the key bindings to change the font size.
I do not think the warnings you have received are related. I had the same warnings which turned out to be the chrome extension React Dev Tools. Removed the extension and the errors have gone.
You can use The Oracle Enterprise Manager to monitor the active sessions, with the query that is being executed, its execution plan, locks, some statistics and even a progress bar for the longer tasks.
See: http://download.oracle.com/docs/cd/B10501_01/em.920/a96674/db_admin.htm#1013955
Go to Instance -> sessions and watch the SQL Tab of each session.
There are other ways. Enterprise manager just puts with pretty colors what is already available in specials views like those documented here: http://www.oracle.com/pls/db92/db92.catalog_views?remark=homepage
And, of course you can also use Explain PLAN FOR, TRACE tool and tons of other ways of instrumentalization. There are some reports in the enterprise manager for the top most expensive SQL Queries. You can also search recent queries kept on the cache.
After long research, I got this thing working. See the following code:
Test.java
import android.app.Activity;
import android.os.Bundle;
import android.view.KeyEvent;
public class Test extends Activity {
HTML5WebView mWebView;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mWebView = new HTML5WebView(this);
if (savedInstanceState != null) {
mWebView.restoreState(savedInstanceState);
} else {
mWebView.loadUrl("http://192.168.1.18/xxxxxxxxxxxxxxxx/");
}
setContentView(mWebView.getLayout());
}
@Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
mWebView.saveState(outState);
}
@Override
public void onStop() {
super.onStop();
mWebView.stopLoading();
}
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK) {
if (mWebView.inCustomView()) {
mWebView.hideCustomView();
// mWebView.goBack();
//mWebView.goBack();
return true;
}
}
return super.onKeyDown(keyCode, event);
}
}
HTML%VIDEO.java
package com.ivz.idemandtest;
import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.util.AttributeSet;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.webkit.GeolocationPermissions;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.FrameLayout;
public class HTML5WebView extends WebView {
private Context mContext;
private MyWebChromeClient mWebChromeClient;
private View mCustomView;
private FrameLayout mCustomViewContainer;
private WebChromeClient.CustomViewCallback mCustomViewCallback;
private FrameLayout mContentView;
private FrameLayout mBrowserFrameLayout;
private FrameLayout mLayout;
static final String LOGTAG = "HTML5WebView";
private void init(Context context) {
mContext = context;
Activity a = (Activity) mContext;
mLayout = new FrameLayout(context);
mBrowserFrameLayout = (FrameLayout) LayoutInflater.from(a).inflate(R.layout.custom_screen, null);
mContentView = (FrameLayout) mBrowserFrameLayout.findViewById(R.id.main_content);
mCustomViewContainer = (FrameLayout) mBrowserFrameLayout.findViewById(R.id.fullscreen_custom_content);
mLayout.addView(mBrowserFrameLayout, COVER_SCREEN_PARAMS);
// Configure the webview
WebSettings s = getSettings();
s.setBuiltInZoomControls(true);
s.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.NARROW_COLUMNS);
s.setUseWideViewPort(true);
s.setLoadWithOverviewMode(true);
// s.setSavePassword(true);
s.setSaveFormData(true);
s.setJavaScriptEnabled(true);
mWebChromeClient = new MyWebChromeClient();
setWebChromeClient(mWebChromeClient);
setWebViewClient(new WebViewClient());
setScrollBarStyle(View.SCROLLBARS_INSIDE_OVERLAY);
// enable navigator.geolocation
// s.setGeolocationEnabled(true);
// s.setGeolocationDatabasePath("/data/data/org.itri.html5webview/databases/");
// enable Web Storage: localStorage, sessionStorage
s.setDomStorageEnabled(true);
mContentView.addView(this);
}
public HTML5WebView(Context context) {
super(context);
init(context);
}
public HTML5WebView(Context context, AttributeSet attrs) {
super(context, attrs);
init(context);
}
public HTML5WebView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
init(context);
}
public FrameLayout getLayout() {
return mLayout;
}
public boolean inCustomView() {
return (mCustomView != null);
}
public void hideCustomView() {
mWebChromeClient.onHideCustomView();
}
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK) {
if ((mCustomView == null) && canGoBack()){
goBack();
return true;
}
}
return super.onKeyDown(keyCode, event);
}
private class MyWebChromeClient extends WebChromeClient {
private Bitmap mDefaultVideoPoster;
private View mVideoProgressView;
@Override
public void onShowCustomView(View view, WebChromeClient.CustomViewCallback callback)
{
//Log.i(LOGTAG, "here in on ShowCustomView");
HTML5WebView.this.setVisibility(View.GONE);
// if a view already exists then immediately terminate the new one
if (mCustomView != null) {
callback.onCustomViewHidden();
return;
}
mCustomViewContainer.addView(view);
mCustomView = view;
mCustomViewCallback = callback;
mCustomViewContainer.setVisibility(View.VISIBLE);
}
@Override
public void onHideCustomView() {
System.out.println("customview hideeeeeeeeeeeeeeeeeeeeeeeeeee");
if (mCustomView == null)
return;
// Hide the custom view.
mCustomView.setVisibility(View.GONE);
// Remove the custom view from its container.
mCustomViewContainer.removeView(mCustomView);
mCustomView = null;
mCustomViewContainer.setVisibility(View.GONE);
mCustomViewCallback.onCustomViewHidden();
HTML5WebView.this.setVisibility(View.VISIBLE);
HTML5WebView.this.goBack();
//Log.i(LOGTAG, "set it to webVew");
}
@Override
public View getVideoLoadingProgressView() {
//Log.i(LOGTAG, "here in on getVideoLoadingPregressView");
if (mVideoProgressView == null) {
LayoutInflater inflater = LayoutInflater.from(mContext);
mVideoProgressView = inflater.inflate(R.layout.video_loading_progress, null);
}
return mVideoProgressView;
}
@Override
public void onReceivedTitle(WebView view, String title) {
((Activity) mContext).setTitle(title);
}
@Override
public void onProgressChanged(WebView view, int newProgress) {
((Activity) mContext).getWindow().setFeatureInt(Window.FEATURE_PROGRESS, newProgress*100);
}
@Override
public void onGeolocationPermissionsShowPrompt(String origin, GeolocationPermissions.Callback callback) {
callback.invoke(origin, true, false);
}
}
static final FrameLayout.LayoutParams COVER_SCREEN_PARAMS =
new FrameLayout.LayoutParams( ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
}
custom_screen.xml
<?xml version="1.0" encoding="utf-8"?>
<!-- Copyright (C) 2009 The Android Open Source Project
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
-->
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android">
<FrameLayout android:id="@+id/fullscreen_custom_content"
android:visibility="gone"
android:background="@color/black"
android:layout_width="match_parent"
android:layout_height="match_parent"
/>
<LinearLayout android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout android:id="@+id/error_console"
android:layout_width="match_parent"
android:layout_height="wrap_content"
/>
<FrameLayout android:id="@+id/main_content"
android:layout_width="match_parent"
android:layout_height="match_parent"
/>
</LinearLayout>
</FrameLayout>
video_loading_progress.xml
<?xml version="1.0" encoding="utf-8"?>
<!-- Copyright (C) 2009 The Android Open Source Project
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
-->
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/progress_indicator"
android:orientation="vertical"
android:layout_centerInParent="true"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<ProgressBar android:id="@android:id/progress"
style="?android:attr/progressBarStyleLarge"
android:layout_gravity="center"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<TextView android:paddingTop="5dip"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:text="@string/loading_video" android:textSize="14sp"
android:textColor="?android:attr/textColorPrimary" />
</LinearLayout>
colors.xml
<?xml version="1.0" encoding="utf-8"?>
<!--
/* //device/apps/common/assets/res/any/http_authentication_colors.xml
**
** Copyright 2006, The Android Open Source Project
**
** Licensed under the Apache License, Version 2.0 (the "License");
** you may not use this file except in compliance with the License.
** You may obtain a copy of the License at
**
** http://www.apache.org/licenses/LICENSE-2.0
**
** Unless required by applicable law or agreed to in writing, software
** distributed under the License is distributed on an "AS IS" BASIS,
** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
** See the License for the specific language governing permissions and
** limitations under the License.
*/
-->
<!-- FIXME: Change the name of this file! It is now being used generically
for the browser -->
<resources>
<color name="username_text">#ffffffff</color>
<color name="username_edit">#ff000000</color>
<color name="password_text">#ffffffff</color>
<color name="password_edit">#ff000000</color>
<color name="ssl_text_label">#ffffffff</color>
<color name="ssl_text_value">#ffffffff</color>
<color name="white">#ffffffff</color>
<color name="black">#ff000000</color>
<color name="geolocation_permissions_prompt_background">#ffdddddd</color>
</resources>
Manifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.test"
android:versionCode="1"
android:versionName="1.0">
<uses-sdk android:minSdkVersion="7" />
<application android:icon="@drawable/icon" android:label="@string/app_name">
<activity android:name=".Test"
android:label="@string/app_name" android:theme="@android:style/Theme.NoTitleBar.Fullscreen"
android:configChanges="orientation|keyboardHidden|keyboard">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
<uses-permission android:name="android.permission.INTERNET"></uses-permission>
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_MOCK_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_GPS" />
<uses-permission android:name="android.permission.ACCESS_ASSISTED_GPS" />
<uses-permission android:name="android.permission.ACCESS_LOCATION" />
</manifest>
Expecting rest of things you can understand.
This works with my IP camera:
import cv2
#print("Before URL")
cap = cv2.VideoCapture('rtsp://admin:[email protected]/H264?ch=1&subtype=0')
#print("After URL")
while True:
#print('About to start the Read command')
ret, frame = cap.read()
#print('About to show frame of Video.')
cv2.imshow("Capturing",frame)
#print('Running..')
if cv2.waitKey(1) & 0xFF == ord('q'):
break
cap.release()
cv2.destroyAllWindows()
I found the Stream URL in the Camera's Setup screen:
Note that I added the Username (admin) and Password (123456) of the camera and ended it with an @ symbol before the IP address in the URL (admin:123456@)
Make sure all required services are running
Step 1 : Check if hbase-master is running
sudo /etc/init.d/hbase-master status
if not, then start it sudo /etc/init.d/hbase-master start
Step 2 : Check if hbase-regionserver is running
sudo /etc/init.d/hbase-regionserver status
if not, then start it sudo /etc/init.d/hbase-regionserver start
Step 3 : Check if zookeeper-server is running
sudo /etc/init.d/zookeeper-server status
if not, then start it sudo /etc/init.d/zookeeper-server start
or simply run these 3 commands in a row.
sudo /etc/init.d/hbase-master restart
sudo /etc/init.d/hbase-regionserver restart
sudo /etc/init.d/zookeeper-server restart
after that don't forget to check the status
sudo /etc/init.d/hbase-master status
sudo /etc/init.d/hbase-regionserver status
sudo /etc/init.d/zookeeper-server status
You might find that zookeeper is still not running: then you can run the zookeeper
sudo /usr/lib/zookeeper/bin/zkServer.sh stop
sudo /usr/lib/zookeeper/bin/zkServer.sh start
after that again check the status and make sure its running
sudo /etc/init.d/zookeeper-server status
This should work.
Also you can add <br> instead of \n.
And then you can add text to TexView:
articleTextView.setText(Html.fromHtml(textForTextView));
SELECT employee_id,department_id AS department
FROM employees
order by department
SELECT employee_id,department_id AS "department"
FROM employees
order by department
--error on oracle--
so better to use AS without double quotation if you use ORDER BY clause
Just add this to config
<system.net>
<defaultProxy useDefaultCredentials="true" >
</defaultProxy>
</system.net>
foreach ($Contents as $index=>$item) {
$item[$index];// if there are 15 $item[number] in this foreach, I want get the value : 15
}
I had this issue and I thought I was crazy. I have been using SSH for 20 years. and git over SSH since 2012... but why couldn't I fetch my bitbucket repository on my home computer?
well, I have two bitbucket accounts and had 4 SSH keys loaded inside my agent. even if my .ssh/config was configured to use the right key. when ssh was initializing the connection, it was using them in order loaded into the agent. so I was getting logged into my personal bitbucket account.
then getting a Forbidden error trying to fetch the repo. makes sense.
I unloaded the key from the agent
ssh-add -d ~/.ssh/personal_rsa
then I could fetch the repos.
... Later I found out I can force it to use the specified identity only
Host bitbucket.org-user2
HostName bitbucket.org
User git
IdentityFile ~/.ssh/user2
IdentitiesOnly yes
I didn't know about that last option IdentitiesOnly
from the bitbucket documentation itself
https://blog.developer.atlassian.com/different-ssh-keys-multiple-bitbucket-accounts/
I know this question is old, however I ran into this problem on Windows 8.1 while trying to use .htaccess files for rewriting. My solution was simple, I forgot to modify the following line in httpd.conf
#LoadModule rewrite_module modules/mod_rewrite.so
to
LoadModule rewrite_module modules/mod_rewrite.so
Restarted the apache monitor, now all works well. Just posting this as an answer because someone in the future may run across the same issue with a simple fix.
Good luck!
Here's another way to do it, using a LINQ lambda:
C#:
SomeObject.GetType().GetProperties().ToList().ForEach(x => Console.WriteLine($"{x.Name} = {x.GetValue(SomeObject, null)}"));
VB.NET:
SomeObject.GetType.GetProperties.ToList.ForEach(Sub(x) Console.WriteLine($"{x.Name} = {x.GetValue(SomeObject, Nothing)}"))
Adding some visual representation to the list of answers.
MySQL uses an extra layer of indirection: secondary index records point to primary index records, and the primary index itself holds the on-disk row locations. If a row offset changes, only the primary index needs to be updated.
Caveat: Disk data structure looks flat in the diagram but actually is a B+ tree.
Source: link
Related information, especially if you are using NTVS for working with the Visual Studio IDE. The NTVS adds both NodeJS and Express tools, scaffolding, project templates to Visual Studio 2012, 2013.
Also, the verbiage that calls ExpressJS or Connect as a "WebServer" is incorrect. You can create a basic WebServer with or without them. A basic NodeJS program can also use the http module to handle http requests, Thus becoming a rudimentary web server.
This is an example OPML parser working with FeedDemon opml files:
Sub debugPrintOPML()
' http://msdn.microsoft.com/en-us/library/ms763720(v=VS.85).aspx
' http://msdn.microsoft.com/en-us/library/system.xml.xmlnode.selectnodes.aspx
' http://msdn.microsoft.com/en-us/library/ms256086(v=VS.85).aspx ' expressions
' References: Microsoft XML
Dim xmldoc As New DOMDocument60
Dim oNodeList As IXMLDOMSelection
Dim oNodeList2 As IXMLDOMSelection
Dim curNode As IXMLDOMNode
Dim n As Long, n2 As Long, x As Long
Dim strXPathQuery As String
Dim attrLength As Byte
Dim FilePath As String
FilePath = "rss.opml"
xmldoc.Load CurrentProject.Path & "\" & FilePath
strXPathQuery = "opml/body/outline"
Set oNodeList = xmldoc.selectNodes(strXPathQuery)
For n = 0 To (oNodeList.length - 1)
Set curNode = oNodeList.Item(n)
attrLength = curNode.Attributes.length
If attrLength > 1 Then ' or 2 or 3
Call processNode(curNode)
Else
Call processNode(curNode)
strXPathQuery = "opml/body/outline[position() = " & n + 1 & "]/outline"
Set oNodeList2 = xmldoc.selectNodes(strXPathQuery)
For n2 = 0 To (oNodeList2.length - 1)
Set curNode = oNodeList2.Item(n2)
Call processNode(curNode)
Next
End If
Debug.Print "----------------------"
Next
Set xmldoc = Nothing
End Sub
Sub processNode(curNode As IXMLDOMNode)
Dim sAttrName As String
Dim sAttrValue As String
Dim attrLength As Byte
Dim x As Long
attrLength = curNode.Attributes.length
For x = 0 To (attrLength - 1)
sAttrName = curNode.Attributes.Item(x).nodeName
sAttrValue = curNode.Attributes.Item(x).nodeValue
Debug.Print sAttrName & " = " & sAttrValue
Next
Debug.Print "-----------"
End Sub
This one takes multilevel trees of folders (Awasu, NewzCrawler):
...
Call xmldocOpen4
Call debugPrintOPML4(Null)
...
Dim sText4 As String
Sub debugPrintOPML4(strXPathQuery As Variant)
Dim xmldoc4 As New DOMDocument60
'Dim xmldoc4 As New MSXML2.DOMDocument60 ' ?
Dim oNodeList As IXMLDOMSelection
Dim curNode As IXMLDOMNode
Dim n4 As Long
If IsNull(strXPathQuery) Then strXPathQuery = "opml/body/outline"
' http://msdn.microsoft.com/en-us/library/ms754585(v=VS.85).aspx
xmldoc4.async = False
xmldoc4.loadXML sText4
If (xmldoc4.parseError.errorCode <> 0) Then
Dim myErr
Set myErr = xmldoc4.parseError
MsgBox ("You have error " & myErr.reason)
Else
' MsgBox xmldoc4.xml
End If
Set oNodeList = xmldoc4.selectNodes(strXPathQuery)
For n4 = 0 To (oNodeList.length - 1)
Set curNode = oNodeList.Item(n4)
Call processNode4(strXPathQuery, curNode, n4)
Next
Set xmldoc4 = Nothing
End Sub
Sub processNode4(strXPathQuery As Variant, curNode As IXMLDOMNode, n4 As Long)
Dim sAttrName As String
Dim sAttrValue As String
Dim x As Long
For x = 0 To (curNode.Attributes.length - 1)
sAttrName = curNode.Attributes.Item(x).nodeName
sAttrValue = curNode.Attributes.Item(x).nodeValue
'If sAttrName = "text"
Debug.Print strXPathQuery & " :: " & sAttrName & " = " & sAttrValue
'End If
Next
Debug.Print ""
If curNode.childNodes.length > 0 Then
Call debugPrintOPML4(strXPathQuery & "[position() = " & n4 + 1 & "]/" & curNode.nodeName)
End If
End Sub
Sub xmldocOpen4()
Dim oFSO As New FileSystemObject ' Microsoft Scripting Runtime Reference
Dim oFS
Dim FilePath As String
FilePath = "rss_awasu.opml"
Set oFS = oFSO.OpenTextFile(CurrentProject.Path & "\" & FilePath)
sText4 = oFS.ReadAll
oFS.Close
End Sub
or better:
Sub xmldocOpen4()
Dim FilePath As String
FilePath = "rss.opml"
' function ConvertUTF8File(sUTF8File):
' http://www.vbmonster.com/Uwe/Forum.aspx/vb/24947/How-to-read-UTF-8-chars-using-VBA
' loading and conversion from Utf-8 to UTF
sText8 = ConvertUTF8File(CurrentProject.Path & "\" & FilePath)
End Sub
but I don't understand, why xmldoc4 should be loaded each time.
This works in all chrome, IE, Firefox.
In Database > table > field type .for example set the symbol column TO varchar(2) utf8_bin
php code:
$symbol = '£';
echo mb_convert_encoding($symbol, 'UTF-8', 'HTML-ENTITIES');
or
html_entity_decode($symbol, ENT_NOQUOTES, 'UTF-8');
And also make sure set the HTML OR XML encoding to encoding="UTF-8"
Note: You should make sure that database, document type and php code all have a same encoding
How ever the better solution would be using £
You can set max value for your seekbar by using this code:
sb1.setMax(100);
This will set the max value for your seekbar.
But you cannot set the minimum value but yes you can do some arithmetic to adjust value. Use arithmetic to adjust your application-required value.
For example, suppose you have data values from -50 to 100 you want to display on the SeekBar. Set the SeekBar's maximum to be 150 (100-(-50)), then subtract 50 from the raw value to get the number you should use when setting the bar position.
You can get more info via this link.
Just as an addition: This way you can access properties with names that would be otherwise unusable
$x = new StdClass;$prop = 'a b'; $x->$prop = 1; $x->{'x y'} = 2; var_dump($x);
object(stdClass)#1 (2) { ["a b"]=> int(1) ["x y"]=> int(2) }(not that you should, but in case you have to).
hash.collect { |k, v| v }
#returns [["a", "b", "c"], ["b", "c"]]
Enumerable#collect
takes a block, and returns an array of the results of running the block once on every element of the enumerable. So this code just ignores the keys and returns an array of all the values.
The Enumerable
module is pretty awesome. Knowing it well can save you lots of time and lots of code.
Give my credit to @chad-m 's answer.
Here is the Swift version:
MyNavigationController.swift
import UIKit
class MyNavigationController: UINavigationController, UINavigationControllerDelegate {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
self.delegate = self
}
func navigationController(_ navigationController: UINavigationController, willShow viewController: UIViewController, animated: Bool) {
if viewController == self.viewControllers.first {
self.setNavigationBarHidden(true, animated: animated)
} else {
self.setNavigationBarHidden(false, animated: animated)
}
}
}
Difference between chad-m's answer and mine:
Inherit from UINavigationController, so you won't pollute your rootViewController.
use self.viewControllers.first
rather than homeViewController
, so you won't do this 100 times for your 100 UINavigationControllers in 1 StoryBoard.
I've had the same problem.
The reason was, that my local branch had somehow lost the tracking to the remote counterpart.
After
git branch branch_name --set-upstream-to=origin/branch_name
git pull
and resolving the merging conflicts, I was able to push.
Use IFNULL:
IFNULL(expr1, 0)
From the documentation:
If expr1 is not NULL, IFNULL() returns expr1; otherwise it returns expr2. IFNULL() returns a numeric or string value, depending on the context in which it is used.
Instead of manipulating the CMAKE_CXX_FLAGS
strings directly (which could be done more nicely using string(APPEND CMAKE_CXX_FLAGS_DEBUG " -g3")
btw), you can use add_compiler_options
:
add_compile_options(
"-Wall" "-Wpedantic" "-Wextra" "-fexceptions"
"$<$<CONFIG:DEBUG>:-O0;-g3;-ggdb>"
)
This would add the specified warnings to all build types, but only the given debugging flags to the DEBUG
build. Note that compile options are stored as a CMake list, which is just a string separating its elements by semicolons ;
.
Ryan Stewart's answer was almost there. In the case where you actually don't want to delete your local changes, there's a workflow you can use to merge:
git status
. It will give you a list of unmerged files.git commit
Git will commit just the merges into a new commit. (In my case, I had additional added files on disk, which weren't lumped into that commit.)
Git then considers the merge successful and allows you to move forward.
This goes also for statements like this (auto-formatted by PyCharm):
return combine_sample_generators(sample_generators['train']), \
combine_sample_generators(sample_generators['dev']), \
combine_sample_generators(sample_generators['test'])
Which will give the same style-warning. In order to get rid of it I had to rewrite it to:
return \
combine_sample_generators(sample_generators['train']), \
combine_sample_generators(sample_generators['dev']), \
combine_sample_generators(sample_generators['test'])
You are declaring a local variable, not a class variable. To set an instance variable (attribute), use
class Example(object):
def the_example(self):
self.itsProblem = "problem" # <-- remember the 'self.'
theExample = Example()
theExample.the_example()
print(theExample.itsProblem)
To set a class variable (a.k.a. static member), use
class Example(object):
def the_example(self):
Example.itsProblem = "problem"
# or, type(self).itsProblem = "problem"
# depending what you want to do when the class is derived.
I have just found a PHP function "strip_tags()" and its working in my case.
I tried to convert the following HTML :
<p><span style="font-family: 'Verdana','sans-serif'; color: black; font-size: 7.5pt;"> </span>Many practitioners are optimistic that the eyeglass and contact lens industry will recover from the recent economic storm. Did your practice feel its affects? Statistics show revenue notably declined in 2008 and 2009. But interestingly enough, those that monitor these trends state that despite the industry's lackluster performance during this time, revenue has grown at an average annual rate of 2.2% over the last five years, to $9.0 billion in 2010. So despite the downturn, how were we able to manage growth as an industry?</p>
After applying strip_tags() function, I have got the following output :
&nbsp;Many practitioners are optimistic that the eyeglass and contact lens industry will recover from the recent economic storm. Did your practice feel its affects?&nbsp; Statistics show revenue notably declined in 2008 and 2009. But interestingly enough, those that monitor these trends state that despite the industry's lackluster performance during this time, revenue has grown at an average annual rate&nbsp;of 2.2% over the last five years, to $9.0 billion in 2010.&nbsp; So despite the downturn, how were we able to manage growth as an industry?
Not sure if this is a feature or a bug but this worked for us:
git commit '' -m "Message"
Note the empty file list ''. Git interprets this to commit all modified tracked files, even if they are not staged, and ignore untracked files.
You can use lambda expression like this.
int index = listOfElements.FindIndex(item => item.Id == id);
if (index != -1)
{
listOfElements[index] = newValue;
}
BitmapFactory.Options options = new Options();
options.inSampleSize = 32;
//img = BitmapFactory.decodeFile(imageids[position], options);
Bitmap theImage = BitmapFactory.decodeStream(imageStream,null, options);
Bitmap img=theImage.copy(Bitmap.Config.RGB_565,true);
theImage.recycle();
theImage = null;
System.gc();
//ivlogdp.setImageBitmap(img);
Runtime.getRuntime().gc();
use - !important - to override default black
.fa-heart:hover{_x000D_
color:red !important;_x000D_
}_x000D_
.fa-heart-o:hover{_x000D_
color:red !important;_x000D_
}
_x000D_
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css">_x000D_
_x000D_
<i class="fa fa-heart fa-2x"></i>_x000D_
<i class="fa fa-heart-o fa-2x"></i>
_x000D_
Looks like git
now comes with wincred
out-of-the-box on Windows (msysgit):
git config --global credential.helper wincred
Reference: https://github.com/msysgit/git/commit/e2770979fec968a25ac21e34f9082bc17a71a780
Use the ExecuteStoreQuery method of the entity context. This avoids downloading the entire result set and deserializing into objects to do a simple row count.
int count;
using (var db = new MyDatabase()){
string sql = "SELECT COUNT(*) FROM MyTable where FkId = {0}";
object[] myParams = {1};
var cntQuery = db.ExecuteStoreQuery<int>(sql, myParams);
count = cntQuery.First<int>();
}
Some mentioned SPSS, StatTransfer, they are not free. R and Python (also mentioned above) may be your choice. But personally, I would like to recommend Python, the syntax is much more intuitive than R. You can just use several command lines with Pandas in Python to read and export most of the commonly used data formats:
import pandas as pd
df = pd.read_stata('YourDataName.dta')
df.to_csv('YourDataName.csv')
Bootstrap 4.x
With Bootstrap 4 (and Font Awesome), we still can use the input-group
wrapper around our form-control
element, and now we can use an input-group-append
(or input-group-prepend
) wrapper with an input-group-text
to get the job done:
<div class="input-group mb-3">
<input type="text" class="form-control" placeholder="Search" aria-label="Search" aria-describedby="my-search">
<div class="input-group-append">
<span class="input-group-text" id="my-search"><i class="fas fa-filter"></i></span>
</div>
</div>
It will look something like this (thanks to KyleMit for the screenshot):
Learn more by visiting the Input group documentation.
You can do it this way inside a program:
#include <sys/resource.h>
// core dumps may be disallowed by parent of this process; change that
struct rlimit core_limits;
core_limits.rlim_cur = core_limits.rlim_max = RLIM_INFINITY;
setrlimit(RLIMIT_CORE, &core_limits);
If you have several files or directories and want to compare non continuous commits, you could do this:
Make a temporary branch ("revision" in this example)
git checkout -b revision
Rewind to the first commit target
git reset --hard <commit_target>
Cherry picking on those commit interested
git cherry-pick <commit_interested> ...
Apply diff
git diff <commit-target>^
When you done
git branch -D revision
class Outer(object):
outer_var = 1
class Inner(object):
@property
def inner_var(self):
return Outer.outer_var
This isn't quite the same as similar things work in other languages, and uses global lookup instead of scoping the access to outer_var
. (If you change what object the name Outer
is bound to, then this code will use that object the next time it is executed.)
If you instead want all Inner
objects to have a reference to an Outer
because outer_var
is really an instance attribute:
class Outer(object):
def __init__(self):
self.outer_var = 1
def get_inner(self):
return self.Inner(self)
# "self.Inner" is because Inner is a class attribute of this class
# "Outer.Inner" would also work, or move Inner to global scope
# and then just use "Inner"
class Inner(object):
def __init__(self, outer):
self.outer = outer
@property
def inner_var(self):
return self.outer.outer_var
Note that nesting classes is somewhat uncommon in Python, and doesn't automatically imply any sort of special relationship between the classes. You're better off not nesting. (You can still set a class attribute on Outer
to Inner
, if you want.)
It should suffice to say whether bcrypt or SHA-512 (in the context of an appropriate algorithm like PBKDF2) is good enough. And the answer is yes, either algorithm is secure enough that a breach will occur through an implementation flaw, not cryptanalysis.
If you insist on knowing which is "better", SHA-512 has had in-depth reviews by NIST and others. It's good, but flaws have been recognized that, while not exploitable now, have led to the the SHA-3 competition for new hash algorithms. Also, keep in mind that the study of hash algorithms is "newer" than that of ciphers, and cryptographers are still learning about them.
Even though bcrypt as a whole hasn't had as much scrutiny as Blowfish itself, I believe that being based on a cipher with a well-understood structure gives it some inherent security that hash-based authentication lacks. Also, it is easier to use common GPUs as a tool for attacking SHA-2–based hashes; because of its memory requirements, optimizing bcrypt requires more specialized hardware like FPGA with some on-board RAM.
Note: bcrypt is an algorithm that uses Blowfish internally. It is not an encryption algorithm itself. It is used to irreversibly obscure passwords, just as hash functions are used to do a "one-way hash".
Cryptographic hash algorithms are designed to be impossible to reverse. In other words, given only the output of a hash function, it should take "forever" to find a message that will produce the same hash output. In fact, it should be computationally infeasible to find any two messages that produce the same hash value. Unlike a cipher, hash functions aren't parameterized with a key; the same input will always produce the same output.
If someone provides a password that hashes to the value stored in the password table, they are authenticated. In particular, because of the irreversibility of the hash function, it's assumed that the user isn't an attacker that got hold of the hash and reversed it to find a working password.
Now consider bcrypt. It uses Blowfish to encrypt a magic string, using a key "derived" from the password. Later, when a user enters a password, the key is derived again, and if the ciphertext produced by encrypting with that key matches the stored ciphertext, the user is authenticated. The ciphertext is stored in the "password" table, but the derived key is never stored.
In order to break the cryptography here, an attacker would have to recover the key from the ciphertext. This is called a "known-plaintext" attack, since the attack knows the magic string that has been encrypted, but not the key used. Blowfish has been studied extensively, and no attacks are yet known that would allow an attacker to find the key with a single known plaintext.
So, just like irreversible algorithms based cryptographic digests, bcrypt produces an irreversible output, from a password, salt, and cost factor. Its strength lies in Blowfish's resistance to known plaintext attacks, which is analogous to a "first pre-image attack" on a digest algorithm. Since it can be used in place of a hash algorithm to protect passwords, bcrypt is confusingly referred to as a "hash" algorithm itself.
Assuming that rainbow tables have been thwarted by proper use of salt, any truly irreversible function reduces the attacker to trial-and-error. And the rate that the attacker can make trials is determined by the speed of that irreversible "hash" algorithm. If a single iteration of a hash function is used, an attacker can make millions of trials per second using equipment that costs on the order of $1000, testing all passwords up to 8 characters long in a few months.
If however, the digest output is "fed back" thousands of times, it will take hundreds of years to test the same set of passwords on that hardware. Bcrypt achieves the same "key strengthening" effect by iterating inside its key derivation routine, and a proper hash-based method like PBKDF2 does the same thing; in this respect, the two methods are similar.
So, my recommendation of bcrypt stems from the assumptions 1) that a Blowfish has had a similar level of scrutiny as the SHA-2 family of hash functions, and 2) that cryptanalytic methods for ciphers are better developed than those for hash functions.
Editing Windows registries is not worth it and not safe, use Map network drive
and load the network share as if it's loaded from one of your local drives.
Hey I got the solution. I did not set the category as "Default". Also I was using the Main activity for the intent Data. Now i am using a different activity for the intent data. Thanks for the help. :)
It is possible. Have a look at JSch.addIdentity(...)
This allows you to use key either as byte array or to read it from file.
import com.jcraft.jsch.Channel;
import com.jcraft.jsch.ChannelSftp;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.Session;
public class UserAuthPubKey {
public static void main(String[] arg) {
try {
JSch jsch = new JSch();
String user = "tjill";
String host = "192.18.0.246";
int port = 10022;
String privateKey = ".ssh/id_rsa";
jsch.addIdentity(privateKey);
System.out.println("identity added ");
Session session = jsch.getSession(user, host, port);
System.out.println("session created.");
// disabling StrictHostKeyChecking may help to make connection but makes it insecure
// see http://stackoverflow.com/questions/30178936/jsch-sftp-security-with-session-setconfigstricthostkeychecking-no
//
// java.util.Properties config = new java.util.Properties();
// config.put("StrictHostKeyChecking", "no");
// session.setConfig(config);
session.connect();
System.out.println("session connected.....");
Channel channel = session.openChannel("sftp");
channel.setInputStream(System.in);
channel.setOutputStream(System.out);
channel.connect();
System.out.println("shell channel connected....");
ChannelSftp c = (ChannelSftp) channel;
String fileName = "test.txt";
c.put(fileName, "./in/");
c.exit();
System.out.println("done");
} catch (Exception e) {
System.err.println(e);
}
}
}
GetDateTimeFormats can parse DateTime to different formats. Example to "yyyy-MM-dd" format.
SomeDate.Value.GetDateTimeFormats()[5]
Also note that if, for whatever reason, you make a method in a @Service
as final
, the autowired beans you will access from it will always be null
.
GroupBox
is better.But not only group box, even you can use Panels
(System.Windows.Forms.Panel
).
The libraries mentioned in other answers would be fine solutions, but if you already happen to be digging through real-world html in your project, the Jsoup
project has a lot more to offer than just managing "ampersand pound FFFF semicolon" things.
// textValue: <p>This is a sample. \"Granny\" Smith –.<\/p>\r\n
// becomes this: This is a sample. "Granny" Smith –.
// with one line of code:
// Jsoup.parse(textValue).getText(); // for older versions of Jsoup
Jsoup.parse(textValue).text();
// Another possibility may be the static unescapeEntities method:
boolean strictMode = true;
String unescapedString = org.jsoup.parser.Parser.unescapeEntities(textValue, strictMode);
And you also get the convenient API for extracting and manipulating data, using the best of DOM, CSS, and jquery-like methods. It's open source and MIT licence.
The base-class constructor is already automatically called by your derived-class constructor. In C++, if the base class has a default constructor (takes no arguments, can be auto-generated by the compiler!), and the derived-class constructor does not invoke another base-class constructor in its initialisation list, the default constructor will be called. I.e. your code is equivalent to:
class PetStore: public Farm
{
public :
PetStore()
: Farm() // <---- Call base-class constructor in initialision list
{
idF=0;
};
private:
int idF;
string nameF;
}
python -m timeit -h
Yes. bar.a
and bar.b
are set to true, but bar.c
is undefined. However, certain compilers will set it to false.
See a live example here: struct demo
According to C++ standard Section 8.5.12:
if no initialization is performed, an object with automatic or dynamic storage duration has indeterminate value
For primitive built-in data types (bool, char, wchar_t, short, int, long, float, double, long double), only global variables (all static storage variables) get default value of zero if they are not explicitly initialized.
If you don't really want undefined bar.c
to start with, you should also initialize it like you did for bar.a
and bar.b
.
If it needs to run on the onload
event of the page, meaning that the document and all its assets have loaded, this needs to be in a content script embedded in each page for which you wish to track onload
.
I'm confused by one thing: You're planning to create a new naming convention for a new project. Generally you should have a naming convention that is company- or team-wide. If you already have projects that have any form of naming convention, you should not change the convention for a new project. If the convention above is just codification of your existing practices, then you are golden. The more it differs from existing de facto standards the harder it will be to gain mindshare in the new standard.
About the only suggestion I would add is I've taken a liking to _t at the end of types in the style of uint32_t and size_t. It's very C-ish to me although some might complain it's just "reverse" Hungarian.
If one wants to change the cell in the position (0,0) of the df to a string such as '"236"76"'
, the following options will do the work:
df[0][0] = '"236"76"'
# %timeit df[0][0] = '"236"76"'
# 938 µs ± 83.4 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)
Or using pandas.DataFrame.at
df.at[0, 0] = '"236"76"'
# %timeit df.at[0, 0] = '"236"76"'
#15 µs ± 2.09 µs per loop (mean ± std. dev. of 7 runs, 100000 loops each)
Or using pandas.DataFrame.iat
df.iat[0, 0] = '"236"76"'
# %timeit df.iat[0, 0] = '"236"76"'
# 41.1 µs ± 3.09 µs per loop (mean ± std. dev. of 7 runs, 10000 loops each)
Or using pandas.DataFrame.loc
df.loc[0, 0] = '"236"76"'
# %timeit df.loc[0, 0] = '"236"76"'
# 5.21 ms ± 401 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
Or using pandas.DataFrame.iloc
df.iloc[0, 0] = '"236"76"'
# %timeit df.iloc[0, 0] = '"236"76"'
# 5.12 ms ± 300 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
If time is of relevance, using pandas.DataFrame.at
is the fastest approach.
Don't :-
xyz = Blogs.objects.get(user_id=id)
Use:-
xyz = Blogs.objects.all().filter(user_id=id)
You can achieve this using the location
object.
location.href = "http://someurl";
Closures can be declared as typealias
as below
typealias Completion = (Bool, Any, Error) -> Void
If you want to use in your function anywhere in code; you can write like normal variable
func xyz(with param1: String, completion: Completion) {
}
HTTP and HTTPS:
const getScript = (url) => {
return new Promise((resolve, reject) => {
const http = require('http'),
https = require('https');
let client = http;
if (url.toString().indexOf("https") === 0) {
client = https;
}
client.get(url, (resp) => {
let data = '';
// A chunk of data has been recieved.
resp.on('data', (chunk) => {
data += chunk;
});
// The whole response has been received. Print out the result.
resp.on('end', () => {
resolve(data);
});
}).on("error", (err) => {
reject(err);
});
});
};
(async (url) => {
console.log(await getScript(url));
})('https://sidanmor.com/');
From Auth0.com
Token-Based Authentication, relies on a signed token that is sent to the server on each request.
What are the benefits of using a token-based approach?
Cross-domain / CORS: cookies + CORS don't play well across different domains. A token-based approach allows you to make AJAX calls to any server, on any domain because you use an HTTP header to transmit the user information.
Stateless (a.k.a. Server side scalability): there is no need to keep a session store, the token is a self-contained entity that conveys all the user information. The rest of the state lives in cookies or local storage on the client side.
CDN: you can serve all the assets of your app from a CDN (e.g. javascript, HTML, images, etc.), and your server side is just the API.
Decoupling: you are not tied to any particular authentication scheme. The token might be generated anywhere, hence your API can be called from anywhere with a single way of authenticating those calls.
Mobile ready: when you start working on a native platform (iOS, Android, Windows 8, etc.) cookies are not ideal when consuming a token-based approach simplifies this a lot.
CSRF: since you are not relying on cookies, you don't need to protect against cross site requests (e.g. it would not be possible to sib your site, generate a POST request and re-use the existing authentication cookie because there will be none).
Performance: we are not presenting any hard perf benchmarks here, but a network roundtrip (e.g. finding a session on database) is likely to take more time than calculating an HMACSHA256 to validate a token and parsing its contents.
Remove the old event handler
$('#id').unbind('click');
And attach the new one
$('#id').click(function(){
// your code here
});
MartinVonMartinsgrün and 4Levels methods confirmed work great on Mac OS X Mountain Lion.
The file I needed to update was ~/.profile.
However, I couldn't leave this question without recommending my favorite application, iTerm 2.
iTerm 2 lets you load global color schemes from a file. Really easy to experiment and try a bunch of color schemes.
Here's a screenshot of the iTerm 2 window and the color preferences.
Once I added the following to my ~/.profile file iTerm 2 was able to override the colors.
export CLICOLOR=1
export LSCOLORS=GxFxCxDxBxegedabagaced
export PS1='\[\033[01;32m\]\u@\h\[\033[00m\]:\[\033[01;34m\]\w\[\033[00m\]\$ '
Here is a great repository with some nice presets:
iTerm2 Color Schemes on Github by mbadolato
Bonus: Choose "Show/hide iTerm2 with a system-wide hotkey" and bind the key with BetterTouchTool for an instant hide/show the terminal with a mouse gesture.
You can use following code which generate pdf file in background as like on button click and then would popup in brwoser with SaveAs and cancel option.
Warning[] warnings;
string[] streamIds;
string mimeType = string.Empty;
string encoding = string.Empty;`enter code here`
string extension = string.Empty;
DataSet dsGrpSum, dsActPlan, dsProfitDetails,
dsProfitSum, dsSumHeader, dsDetailsHeader, dsBudCom = null;
enter code here
//This is optional if you have parameter then you can add parameters as much as you want
ReportParameter[] param = new ReportParameter[5];
param[0] = new ReportParameter("Report_Parameter_0", "1st Para", true);
param[1] = new ReportParameter("Report_Parameter_1", "2nd Para", true);
param[2] = new ReportParameter("Report_Parameter_2", "3rd Para", true);
param[3] = new ReportParameter("Report_Parameter_3", "4th Para", true);
param[4] = new ReportParameter("Report_Parameter_4", "5th Para");
DataSet dsData= "Fill this dataset with your data";
ReportDataSource rdsAct = new ReportDataSource("RptActDataSet_usp_GroupAccntDetails", dsActPlan.Tables[0]);
ReportViewer viewer = new ReportViewer();
viewer.LocalReport.Refresh();
viewer.LocalReport.ReportPath = "Reports/AcctPlan.rdlc"; //This is your rdlc name.
viewer.LocalReport.SetParameters(param);
viewer.LocalReport.DataSources.Add(rdsAct); // Add datasource here
byte[] bytes = viewer.LocalReport.Render("PDF", null, out mimeType, out encoding, out extension, out streamIds, out warnings);
// byte[] bytes = viewer.LocalReport.Render("Excel", null, out mimeType, out encoding, out extension, out streamIds, out warnings);
// Now that you have all the bytes representing the PDF report, buffer it and send it to the client.
// System.Web.HttpContext.Current.Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.Buffer = true;
Response.Clear();
Response.ContentType = mimeType;
Response.AddHeader("content-disposition", "attachment; filename= filename" + "." + extension);
Response.OutputStream.Write(bytes, 0, bytes.Length); // create the file
Response.Flush(); // send it to the client to download
Response.End();
You're close, you just need to delete the file before trying to over-write it.
dim infolder: set infolder = fso.GetFolder(IN_PATH)
dim file: for each file in infolder.Files
dim name: name = file.name
dim parts: parts = split(name, ".")
if UBound(parts) = 2 then
' file name like a.c.pdf
dim newname: newname = parts(0) & "." & parts(2)
dim newpath: newpath = fso.BuildPath(OUT_PATH, newname)
' warning:
' if we have source files C:\IN_PATH\ABC.01.PDF, C:\IN_PATH\ABC.02.PDF, ...
' only one of them will be saved as D:\OUT_PATH\ABC.PDF
if fso.FileExists(newpath) then
fso.DeleteFile newpath
end if
file.Move newpath
end if
next
Here is a sed
solution that extracts path components in a variety of forms and can handle most edge cases:
## Enter the input path and field separator character, for example:
## (separatorChar must not be present in inputPath)
inputPath="/path/to/Foo.bar"
separatorChar=":"
## sed extracts the path components and assigns them to output variables
oldIFS="$IFS"
IFS="$separatorChar"
read dirPathWithSlash dirPath fileNameWithExt fileName fileExtWithDot fileExt <<<"$(sed -En '
s/^[[:space:]]+//
s/[[:space:]]+$//
t l1
:l1
s/^([^/]|$)//
t
s/[/]+$//
t l2
:l2
s/^$/filesystem\/\
filesystem/p
t
h
s/^(.*)([/])([^/]+)$/\1\2\
\1\
\3/p
g
t l3
:l3
s/^.*[/]([^/]+)([.])([a-zA-Z0-9]+)$/\1\
\2\3\
\3/p
t
s/^.*[/](.+)$/\1/p
' <<<"$inputPath" | tr "\n" "$separatorChar")"
IFS="$oldIFS"
## Results (all use separatorChar=":")
## inputPath = /path/to/Foo.bar
## dirPathWithSlash = /path/to/
## dirPath = /path/to
## fileNameWithExt = Foo.bar
## fileName = Foo
## fileExtWithDot = .bar
## fileExt = bar
## inputPath = /path/to/Foobar
## dirPathWithSlash = /path/to/
## dirPath = /path/to
## fileNameWithExt = Foobar
## fileName = Foobar
## fileExtWithDot =
## fileExt =
## inputPath = /path/to/...bar
## dirPathWithSlash = /path/to/
## dirPath = /path/to
## fileNameWithExt = ...bar
## fileName = ..
## fileExtWithDot = .bar
## fileExt = bar
## inputPath = /path/to/..bar
## dirPathWithSlash = /path/to/
## dirPath = /path/to
## fileNameWithExt = ..bar
## fileName = .
## fileExtWithDot = .bar
## fileExt = bar
## inputPath = /path/to/.bar
## dirPathWithSlash = /path/to/
## dirPath = /path/to
## fileNameWithExt = .bar
## fileName = .bar
## fileExtWithDot =
## fileExt =
## inputPath = /path/to/...
## dirPathWithSlash = /path/to/
## dirPath = /path/to
## fileNameWithExt = ...
## fileName = ...
## fileExtWithDot =
## fileExt =
## inputPath = /path/to/Foo.
## dirPathWithSlash = /path/to/
## dirPath = /path/to
## fileNameWithExt = Foo.
## fileName = Foo.
## fileExtWithDot =
## fileExt =
## inputPath = / (the root directory)
## dirPathWithSlash = filesystem/
## dirPath = filesystem
## fileNameWithExt =
## fileName =
## fileExtWithDot =
## fileExt =
## inputPath = (invalid because empty)
## dirPathWithSlash =
## dirPath =
## fileNameWithExt =
## fileName =
## fileExtWithDot =
## fileExt =
## inputPath = Foo/bar (invalid because doesn't start with a forward slash)
## dirPathWithSlash =
## dirPath =
## fileNameWithExt =
## fileName =
## fileExtWithDot =
## fileExt =
Here's how it works:
sed
parses the input path and prints the following path components in order on separate lines:
tr
converts the sed
output into a separator character-delimited string of the above path components.
read
uses the separator character as the field separator (IFS="$separatorChar"
) and assigns each of the path components to its respective variable.
Here's how the sed
construct works:
s/^[[:space:]]+//
and s/[[:space:]]+$//
strip any leading and/or trailing whitespace characterst l1
and :l1
refreshes the t
function for the next s
functions/^([^/]|$)//
and t
tests for an invalid input path (one that does not begin with a forward slash), in which case it leaves all output lines blank and quits the sed
commands/[/]+$//
strips any trailing slashest l2
and :l2
refreshes the t
function for the next s
functions/^$/filesystem\/\\[newline]filesystem/p
and t
tests for the special case where the input path consists of the root directory /, in which case it prints filesystem/ and filesystem for the dirPathWithSlash and dirPath output lines, leaves all other output lines blank, and quits the sed commandh
saves the input path in the hold spaces/^(.*)([/])([^/]+)$/\1\2\\[newline]\1\\[newline]\3/p
prints the dirPathWithSlash, dirPath, and fileNameWithExt output linesg
retrieves the input path from the hold spacet l3
and :l3
refreshes the t
function for the next s
functions/^.*\[/]([^/]+)([.])([a-zA-Z0-9]+)$/\1\\[newline]\2\3\\[newline]\3/p
and t
prints the fileName, fileExtWithDot, and fileExt output lines for the case where a file extension exists, (assumed to consist of alphanumeric characters only), then quits the sed
commands/^.*\[/](.+)$/\1/p
prints the fileName but not the fileExtWithDot, and fileExt output lines for the case where a file extension does not exist, then quits the sed
command.If you just want to compute (column a) % (column b), you don't need apply
, just do it directly:
In [7]: df['a'] % df['c']
Out[7]:
0 -1.132022
1 -0.939493
2 0.201931
3 0.511374
4 -0.694647
5 -0.023486
Name: a
In the beginning, a compiler was responsible for turning a high-level language (defined as higher level than assembler) into object code (machine instructions), which would then be linked (by a linker) into an executable.
At one point in the evolution of languages, compilers would compile a high-level language into pseudo-code, which would then be interpreted (by an interpreter) to run your program. This eliminated the object code and executables, and allowed these languages to be portable to multiple operating systems and hardware platforms. Pascal (which compiled to P-Code) was one of the first; Java and C# are more recent examples. Eventually the term P-Code was replaced with bytecode, since most of the pseudo-operations are a byte long.
A Just-In-Time (JIT) compiler is a feature of the run-time interpreter, that instead of interpreting bytecode every time a method is invoked, will compile the bytecode into the machine code instructions of the running machine, and then invoke this object code instead. Ideally the efficiency of running object code will overcome the inefficiency of recompiling the program every time it runs.
The getPosts()
function seems to be expecting $con
to be global, but you're not declaring it as such.
A lot of programmers regard bald global variables as a "code smell". The alternative at the other end of the scale is to always pass around the connection resource. Partway between the two is a singleton call that always returns the same resource handle.
I wanted to do the same thing, but with 5 instead of 10, and came up with a simple function. Hope it's useful:
def roundToFive(num):
remaining = num % 5
if remaining in range(0, 3):
return num - remaining
return num + (5 - remaining)
Avoid PNG in any case if you want reliable IE6 compatibility.
Try this:
var res = list.ToDictionary(x => x, x => x);
The first lambda lets you pick the key, the second one picks the value.
You can play with it and make values differ from the keys, like this:
var res = list.ToDictionary(x => x, x => string.Format("Val: {0}", x));
If your list contains duplicates, add Distinct()
like this:
var res = list.Distinct().ToDictionary(x => x, x => x);
EDIT To comment on the valid reason, I think the only reason that could be valid for conversions like this is that at some point the keys and the values in the resultant dictionary are going to diverge. For example, you would do an initial conversion, and then replace some of the values with something else. If the keys and the values are always going to be the same, HashSet<String>
would provide a much better fit for your situation:
var res = new HashSet<string>(list);
if (res.Contains("string1")) ...
add this to your form:
<form id="regform" action="insert.php" method="post">
add this to your function:
<script>
function myFunction() {
var pass1 = document.getElementById("pass1").value;
var pass2 = document.getElementById("pass2").value;
if (pass1 != pass2) {
//alert("Passwords Do not match");
document.getElementById("pass1").style.borderColor = "#E34234";
document.getElementById("pass2").style.borderColor = "#E34234";
}
else {
alert("Passwords Match!!!");
document.getElementById("regForm").submit();
}
}
</script>
You can also do ORDER BY TITLE COLLATE NOCASE
.
Edit: If you need to specify ASC
or DESC
, add this after NOCASE
like
ORDER BY TITLE COLLATE NOCASE ASC
or
ORDER BY TITLE COLLATE NOCASE DESC
you should run the code inside the scroll.post like this:
scroll.post(new Runnable() {
@Override
public void run() {
scroll.fullScroll(View.FOCUS_DOWN);
}
});
Yes - different
chmod a+x
will add the exec bits to the file but will not touch other bits. For example file might be still unreadable to others
and group
.
chmod 755
will always make the file with perms 755
no matter what initial permissions were.
This may or may not matter for your script.
None of these answers helped me because I still had untracked files even after reset and stash. I had to do:
git reset --hard HEAD
git clean -d -f
For self-containing Maven project I usually installing all external jar dependencies into project's repository. For SQL Server JDBC driver you can do:
local-repo
in your Maven projectsqljdbc42.jar
into local-repo
folderlocal-repo
folder run mvn deploy:deploy-file -Dfile=sqljdbc42.jar -DartifactId=sqljdbc42 -DgroupId=com.microsoft.sqlserver -DgeneratePom=true -Dpackaging=jar -Dversion=6.0.7507.100 -Durl=file://.
to deploy JAR into local repository (stored together with your code in SCM)sqljdbc42.jar
and downloaded files can be deletedpom.xml
and add reference to project's local repository:
xml
<repositories>
<repository>
<id>parent-local-repository</id>
<name>Parent Local repository</name>
<layout>default</layout>
<url>file://${basedir}/local-repo</url>
<releases>
<enabled>true</enabled>
</releases>
<snapshots>
<enabled>true</enabled>
</snapshots>
</repository>
</repositories>
Now you can run your project everywhere without any additional configurations or installations.try:
SELECT CAST( CAST([field] AS VARBINARY) AS varchar)
We are also getting the same error while we are trying to access a same resource with in milliseconds. Like if i try to POST
some data to www.abc.com/blog
and with in milliseconds an other request will also go for the same resource i.e. www.abc.com/blog
from the same user. So it'll give the 409
error.
Here is how I do (2018 version ?) :
const index = [...el.parentElement.children].indexOf(el);
Tadaaaam. And, if ever you want to consider raw text nodes too, you can do this instead :
const index = [...el.parentElement.childNodes].indexOf(el);
I spread the children into an array as they are an HTMLCollection (thus they do not work with indexOf).
Be careful that you are using Babel or that browser coverage is sufficient for what you need to achieve (thinkings about the spread operator which is basically an Array.from behind the scene).
Another option, just for the heck of it would be:
if ( $('#myFav > *').length > 0 ) {
// do something
}
May actually be the fastest since it strictly uses the Sizzle engine and not necessarily any jQuery, as it were. Could be wrong though. Nevertheless, it works.
Here's the working code. Works in desktop and mobile browsers. hope it helps. thanks for everyone responding.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Test Layout</title>
<style type="text/css">
body, html
{
margin: 0; padding: 0; height: 100%; overflow: hidden;
}
#content
{
position:absolute; left: 0; right: 0; bottom: 0; top: 0px;
}
</style>
</head>
<body>
<div id="content">
<iframe width="100%" height="100%" frameborder="0" src="http://cnn.com" />
</div>
</body>
</html>
If you use Animator for make animation you can
anim (directory) -> fade_out.xml
<?xml version="1.0" encoding="UTF-8"?>
<objectAnimator
android:propertyName="alpha"
android:valueFrom="0"
android:valueTo="1"
xmlns:android="http://schemas.android.com/apk/res/android"/>
In java
Animator animator = AnimatorInflater.loadAnimator(context, R.animator.fade_out);
animator.setTarget(the_view_you_want_to_animation);
animator.setDuration(1000);
animator.start();
Other way to make animation fade out with only java code is
ObjectAnimator fadeOut = ObjectAnimator.ofFloat(the_view_you_want_to_animation, "alpha", 1f, 0);
fadeOut.setDuration(2000);
fadeOut.start();
For installing multiple packages on the command line, just pass them as a space-delimited list, e.g.:
pip install wsgiref boto
For installing from a text file, then, from pip install --help
:
-r FILENAME, --requirement=FILENAME
Install all the packages listed in the given requirements file. This option can be used multiple times.
Take a look at the pip documentation regarding requirements files for their general layout and syntax - note that you can generate one based on current environment / site-packages with pip freeze
if you want a quick example - e.g. (based on having installed wsgiref
and boto
in a clean virtualenv):
$ pip freeze
boto==2.3.0
wsgiref==0.1.2
I got the same error but in PyCharm because I accidentally deleted my VCS origin. After re-adding my origin I ran:
git fetch
which reloaded all of my branches. I then clicked the button to update the project, and I was back to normal.
Date format class work with cheat code to make date. Like
You can check more cheats here.
In malfaux's answer '^' and '$' has been used to detect the beginning and the end of the text.
These are usually used to detect the beginning and the end of a line.
However this may be the correct way in this case.
But if you wish to match an exact word the more elegant way is to use '\b'. In this case following pattern will match the exact phrase'123456'.
/\b123456\b/
I've seen it used when the number of conditions can be variable.
You can concatenate conditions using an " AND " string. Then, instead of counting the number of conditions you're passing in, you place a "WHERE 1=1" at the end of your stock SQL statement and throw on the concatenated conditions.
Basically, it saves you having to do a test for conditions and then add a "WHERE" string before them.
Another approach that is really fast is the MSS module. It is different from other solutions in the way that it uses only the ctypes
standard module, so it does not require big dependencies. It is OS independant and its use is made easy:
from mss import mss
with mss() as sct:
sct.shot()
And just find the screenshot.png
file containing the screen shot of the first monitor. There are a lot of possibile customizations, you can play with ScreenShot
objects and OpenCV/Numpy/PIL/etc..
SOLVED I struggled with this and later on, I realized that I was working on PHP 5.6, so I upgraded to PHP 7.0, then I released there were comments placed by git for conflicting codes. I found something like this in my code <<<<<<<< But solved it.
Try to use the DataColumn.SetOrdinal method. For example:
dataTable.Columns["Qty"].SetOrdinal(0);
dataTable.Columns["Unit"].SetOrdinal(1);
UPDATE: This answer received much more attention than I expected. To avoid confusion and make it easier to use I decided to create an extension method for column ordering in DataTable:
Extension method:
public static class DataTableExtensions
{
public static void SetColumnsOrder(this DataTable table, params String[] columnNames)
{
int columnIndex = 0;
foreach(var columnName in columnNames)
{
table.Columns[columnName].SetOrdinal(columnIndex);
columnIndex++;
}
}
}
Usage:
table.SetColumnsOrder("Qty", "Unit", "Id");
or
table.SetColumnsOrder(new string[]{"Qty", "Unit", "Id"});
This worked for me.
create extension IF NOT EXISTS "uuid-ossp" schema pg_catalog version "1.1";
make sure the extension should by on pg_catalog and not in your schema...
As mentioned here, https://stackoverflow.com/a/50941562/2186220, use gradle plugin version 3 or higher while using 'implementation'.
Also, use the google()
repository in buildscript
.
buildscript {
repositories {
google()
}
dependencies {
classpath 'com.android.tools.build:gradle:3.1.2'
}
}
These changes should solve the issue.
Override onDestroy of the Activity and Dismiss your Dialog & make it null
protected void onDestroy ()
{
if(mProgressDialog != null)
if(mProgressDialog.isShowing())
mProgressDialog.dismiss();
mProgressDialog= null;
}
You are getting a table scan there, meaning that you do not have an index defined on er101_upd_date_iso
, or if that column is part of an existing index, the index can't be used (possibly it is not the primary indexer column).
Adding missing indexes will help performance no end.
there are already indexs on the columns which are queried most commonly
That does not mean they are used in this query (and they probably are not).
I suggest reading Finding the Causes of Poor Performance in SQL Server by Gail Shaw, part 1 and part 2.
instead of
mySelect.toSource()
use
mySelect.val()
"This is a comment in vimrc. It does not have a closing quote
Source: http://vim.wikia.com/wiki/Backing_up_and_commenting_vimrc
In my case, the C:\Users\{user}\AppData\local\npm
files were hidden, so I was not able to find & delete the trouble directory. Took me DAYS to realize this!
So double check to un-hide any folders so you don't miss them! Here's a link to do this if you don't know how.
yes you can do that.
declaring class abstract means that class will not be instantiated by any other class.
and there should be at least one abstract method inside that and meaning of that you can declare abstract method in that class if you are not declaring method than its ok.
example:
public abstract class abs {
protected int cx = 0, cy = 0;
public void p() {
System.out.print("hello");
}
}
this will work for sure.
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.client.RestTemplate;
@Configuration
public class RestTemplateClient {
@Bean
public RestTemplate restTemplate() {
return new RestTemplate();
}
}
None of the answers worked for me. In my case there was a standard
a:-webkit-any-link {
text-decoration: underline;
in my code. Basically whatever link it is, the text color goes blue, and the link stays whatever it is.
So I added the code at the end of the header like this:
<head>
</style>
a:-webkit-any-link {
text-decoration: none;
}
</style>
</head>
and problem is no more.
If you want to leave only numbers - use preg_replace like: (int)preg_replace("/[^\d]+/","",$b).
If you are going to use it with Retrofit library, I suggest you to use Square's gson library as:
implementation 'com.squareup.retrofit2:converter-gson:2.4.0'
From tom, on http://www.php.net/manual/en/function.uniqid.php
$r = unpack('v*', fread(fopen('/dev/random', 'r'),16));
$uuid = sprintf('%04x%04x-%04x-%04x-%04x-%04x%04x%04x',
$r[1], $r[2], $r[3], $r[4] & 0x0fff | 0x4000,
$r[5] & 0x3fff | 0x8000, $r[6], $r[7], $r[8])
Or if you want to bound the value to the interval:
public static T EnsureRange<T>(this T value, T min, T max) where T : IComparable<T>
{
if (value.CompareTo(min) < 0)
return min;
else if (value.CompareTo(max) > 0)
return max;
else
return value;
}
It is like two-sided Math.Min/Max
You can also try turning off the SSL option in settings, in case you are sending it through POSTMAN
var
variables still have a type - and the compiler error message says this type must be established during the declaration.
The specific request (assigning an initial null value) can be done, but I don't recommend it. It doesn't provide an advantage here (as the type must still be specified) and it could be viewed as making the code less readable:
var x = (String)null;
Which is still "type inferred" and equivalent to:
String x = null;
The compiler will not accept var x = null
because it doesn't associate the null with any type - not even Object. Using the above approach, var x = (Object)null
would "work" although it is of questionable usefulness.
Generally, when I can't use var
's type inference correctly then
The second approach can be done by moving code into methods or functions.
I would recommend the following:
Define a behavior
public static class ComboBoxBehaviors
{
public static readonly DependencyProperty DefaultTextProperty =
DependencyProperty.RegisterAttached("DefaultText", typeof(String), typeof(ComboBox), new PropertyMetadata(null));
public static String GetDefaultText(DependencyObject obj)
{
return (String)obj.GetValue(DefaultTextProperty);
}
public static void SetDefaultText(DependencyObject obj, String value)
{
var combo = (ComboBox)obj;
RefreshDefaultText(combo, value);
combo.SelectionChanged += (sender, _) => RefreshDefaultText((ComboBox)sender, GetDefaultText((ComboBox)sender));
obj.SetValue(DefaultTextProperty, value);
}
static void RefreshDefaultText(ComboBox combo, string text)
{
// if item is selected and DefaultText is set
if (combo.SelectedIndex == -1 && !String.IsNullOrEmpty(text))
{
// Show DefaultText
var visual = new TextBlock()
{
FontStyle = FontStyles.Italic,
Text = text,
Foreground = Brushes.Gray
};
combo.Background = new VisualBrush(visual)
{
Stretch = Stretch.None,
AlignmentX = AlignmentX.Left,
AlignmentY = AlignmentY.Center,
Transform = new TranslateTransform(3, 0)
};
}
else
{
// Hide DefaultText
combo.Background = null;
}
}
}
User the behavior
<ComboBox Name="cmb" Margin="72,121,0,0" VerticalAlignment="Top"
local:ComboBoxBehaviors.DefaultText="-- Select Team --"/>
One more way to add the image to Database using Cloud Function to track every uploaded image and store it in Database.
exports.fileUploaded = functions.storage.object().onChange(event => {
const object = event.data; // the object that was just uploaded
const contentType = event.data.contentType; // This is the image Mimme type\
// Exit if this is triggered on a file that is not an image.
if (!contentType.startsWith('image/')) {
console.log('This is not an image.');
return null;
}
// Get the Signed URLs for the thumbnail and original image.
const config = {
action: 'read',
expires: '03-01-2500'
};
const bucket = gcs.bucket(event.data.bucket);
const filePath = event.data.name;
const file = bucket.file(filePath);
file.getSignedUrl(config, function(err, fileURL) {
console.log(fileURL);
admin.database().ref('images').push({
src: fileURL
});
});
});
Full code here: https://gist.github.com/bossly/fb03686f2cb1699c2717a0359880cf84
let tap = UITapGestureRecognizer(target: self, action: Selector("handleFrontTap:"))
frontView.addGestureRecognizer(tap)
// Make sure this is not private
func handleFrontTap(gestureRecognizer: UITapGestureRecognizer) {
print("tap working")
}
You could use width: 100%;
in your css.
While the idea behind LINQ syntax is to emulate the SQL syntax, you shouldn't always think of directly translating your SQL code into LINQ. In this particular case, we don't need to do group into since join into is a group join itself.
Here's my solution:
from p in context.ParentTable
join c in context.ChildTable on p.ParentId equals c.ChildParentId into joined
select new { ParentId = p.ParentId, Count = joined.Count() }
Unlike the mostly voted solution here, we don't need j1, j2 and null checking in Count(t => t.ChildId != null)
Some of it is possible, specifically accessing subtotals:
"In Excel 2010+, you can right-click on the values and select Show Values As –> % of Parent Row Total." (or % of Parent Column Total)
Source: http://datapigtechnologies.com/blog/index.php/excel-2010-pivottable-subtotals/
A real problem often exists because any variables set inside will not be exported when that batch file finishes. So its not possible to export, which caused us issues. As a result, I just set the registry to ALWAYS used delayed expansion (I don't know why it's not the default, could be speed or legacy compatibility issue.)
Backbone.js is basically an uber-light framework that allows you to structure your Javascript code in an MVC (Model, View, Controller) fashion where...
Model is part of your code that retrieves and populates the data,
View is the HTML representation of this model (views change as models change, etc.)
and optional Controller that in this case allows you to save the state of your Javascript application via a hashbang URL, for example: http://twitter.com/#search?q=backbone.js
Some pros that I discovered with Backbone:
No more Javascript Spaghetti: code is organized and broken down into semantically meaningful .js files which are later combined using JAMMIT
No more jQuery.data(bla, bla)
: no need to store data in DOM, store data in models instead
event binding just works
extremely useful Underscore utility library
backbone.js code is well documented and a great read. Opened my eyes to a number of JS code techniques.
Cons:
Here is a set of great tutorials on using Backbone with Rails as the back-end:
CloudEdit: A Backbone.js Tutorial with Rails:
http://www.jamesyu.org/2011/01/27/cloudedit-a-backbone-js-tutorial-by-example/
http://www.jamesyu.org/2011/02/09/backbone.js-tutorial-with-rails-part-2/
p.s. There is also this wonderful Collection class that lets you deal with collections of models and mimic nested models, but I don't want to confuse you from the start.
-- Create a function that always returns the first non-NULL item
CREATE OR REPLACE FUNCTION public.first_agg ( anyelement, anyelement )
RETURNS anyelement LANGUAGE SQL IMMUTABLE STRICT AS $$
SELECT $1;
$$;
-- And then wrap an aggregate around it
CREATE AGGREGATE public.FIRST (
sfunc = public.first_agg,
basetype = anyelement,
stype = anyelement
);
-- Create a function that always returns the last non-NULL item
CREATE OR REPLACE FUNCTION public.last_agg ( anyelement, anyelement )
RETURNS anyelement LANGUAGE SQL IMMUTABLE STRICT AS $$
SELECT $2;
$$;
-- And then wrap an aggregate around it
CREATE AGGREGATE public.LAST (
sfunc = public.last_agg,
basetype = anyelement,
stype = anyelement
);
Got it from here: https://wiki.postgresql.org/wiki/First/last_(aggregate)
Another way to think of it is to calculate the unit vector for a given direction and then apply a 90 degree counterclockwise rotation to get the normal vector.
The matrix representation of the general 2D transformation looks like this:
x' = x cos(t) - y sin(t)
y' = x sin(t) + y cos(t)
where (x,y) are the components of the original vector and (x', y') are the transformed components.
If t = 90 degrees, then cos(90) = 0 and sin(90) = 1. Substituting and multiplying it out gives:
x' = -y
y' = +x
Same result as given earlier, but with a little more explanation as to where it comes from.
Don't know if of help, but in my case I had my resource in the /src/ folder and was getting this error. I then moved the picture to the bin folder and it fixed the issue.
use this
if ($this.hasClass('tb-email')) {
var email = $this.val();
var txt = /^([a-zA-Z0-9_\.\-\+])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
if (!txt.test(email)) {
e.preventDefault();
$this.addClass('error');
} else {
$this.removeClass('error');
}
}
check out this solution... works for me >> https://jsfiddle.net/y49jpdns/
<html lang="en" class="no-js">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width,initial-scale=1.0">
<style>
html body {width: 100%;height: 100%;padding: 0px;margin: 0px;overflow: hidden;font-family: arial;font-size: 10px;color: #6e6e6e;background-color: #000;} #preview-frame {width: 100%;background-color: #fff;}</style>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script>
var calcHeight = function() {
$('#preview-frame').height($(window).height());
}
$(document).ready(function() {
calcHeight();
});
$(window).resize(function() {
calcHeight();
}).load(function() {
calcHeight();
});
</script>
</head>
<body>
<iframe id="preview-frame" src="http://leowebguy.com/" name="preview-frame" frameborder="0" noresize="noresize">
</iframe>
</body>
</html>
iframe doesn't have onclick event but we can implement this by using iframe's onload event and javascript like this...
function iframeclick() {
document.getElementById("theiframe").contentWindow.document.body.onclick = function() {
document.getElementById("theiframe").contentWindow.location.reload();
}
}
<iframe id="theiframe" src="youriframe.html" style="width: 100px; height: 100px;" onload="iframeclick()"></iframe>
I hope it will helpful to you....
I'd go for regexp_replace, although I'm not 100% sure this is usable in PL/SQL
my_value := regexp_replace(my_value, '[[:space:]]*','');
These is a little thing to point out.
Using the function pg_get_viewdef or pg_views or information_schema.views you will always get a rewrited version of your original DDL.
The rewited version may or not be the same as your originl DDL script.
If the Rule Manager rewrite your view definition your original DLL will be lost and you will able to read the only the rewrited version of your view definition.
Not all views are rewrited but if you use sub-select or joins probably your views will be rewrited.
This is my solution using pure Win32/C++ based on the top answer. The idea is to wrap everything required into one function without the need for external callback functions or structures:
#include <utility>
HWND FindTopWindow(DWORD pid)
{
std::pair<HWND, DWORD> params = { 0, pid };
// Enumerate the windows using a lambda to process each window
BOOL bResult = EnumWindows([](HWND hwnd, LPARAM lParam) -> BOOL
{
auto pParams = (std::pair<HWND, DWORD>*)(lParam);
DWORD processId;
if (GetWindowThreadProcessId(hwnd, &processId) && processId == pParams->second)
{
// Stop enumerating
SetLastError(-1);
pParams->first = hwnd;
return FALSE;
}
// Continue enumerating
return TRUE;
}, (LPARAM)¶ms);
if (!bResult && GetLastError() == -1 && params.first)
{
return params.first;
}
return 0;
}
You can use the limit(n)
function:
l = [('Alice', 1),('Jim',2),('Sandra',3)]
df = sqlContext.createDataFrame(l, ['name', 'age'])
df.limit(2).withColumn('age2', df.age + 2).toPandas()
Or:
l = [('Alice', 1),('Jim',2),('Sandra',3)]
df = sqlContext.createDataFrame(l, ['name', 'age'])
df.withColumn('age2', df.age + 2).limit(2).toPandas()
for i=1,#target do
game.Players.target[i].Character:BreakJoints()
end
Is incorrect, if "target" contains "FakeNameHereSoNoStalkers" then the run code would be:
game.Players.target.1.Character:BreakJoints()
Which is completely incorrect.
c = game.Players:GetChildren()
Never use "Players:GetChildren()", it is not guaranteed to return only players.
Instead use:
c = Game.Players:GetPlayers()
if msg:lower()=="me" then
table.insert(people, source)
return people
Here you add the player's name in the list "people", where you in the other places adds the player object.
Fixed code:
local Admins = {"FakeNameHereSoNoStalkers"}
function Kill(Players)
for i,Player in ipairs(Players) do
if Player.Character then
Player.Character:BreakJoints()
end
end
end
function IsAdmin(Player)
for i,AdminName in ipairs(Admins) do
if Player.Name:lower() == AdminName:lower() then return true end
end
return false
end
function GetPlayers(Player,Msg)
local Targets = {}
local Players = Game.Players:GetPlayers()
if Msg:lower() == "me" then
Targets = { Player }
elseif Msg:lower() == "all" then
Targets = Players
elseif Msg:lower() == "others" then
for i,Plr in ipairs(Players) do
if Plr ~= Player then
table.insert(Targets,Plr)
end
end
else
for i,Plr in ipairs(Players) do
if Plr.Name:lower():sub(1,Msg:len()) == Msg then
table.insert(Targets,Plr)
end
end
end
return Targets
end
Game.Players.PlayerAdded:connect(function(Player)
if IsAdmin(Player) then
Player.Chatted:connect(function(Msg)
if Msg:lower():sub(1,6) == ":kill " then
Kill(GetPlayers(Player,Msg:sub(7)))
end
end)
end
end)
https://www.kaggle.com/jboysen/quick-gz-pandas-tutorial
Please follow this link.
import pandas as pd
traffic_station_df = pd.read_csv('C:\\Folders\\Jupiter_Feed.txt.gz', compression='gzip',
header=1, sep='\t', quotechar='"')
#traffic_station_df['Address'] = 'address'
#traffic_station_df.append(traffic_station_df)
print(traffic_station_df)
Run package declaration and body separately.
Paste following link to directly under link button click event, otherwise use javascript to call code behind function
Protected Sub lnkOpen_Click(ByVal sender As Object, ByVal e As EventArgs)
System.Diagnostics.Process.Start(FilePath)
End Sub
this will do the magic
<script>
document.addEventListener("DOMContentLoaded", function(event) {
var scrollpos = localStorage.getItem('scrollpos');
if (scrollpos) window.scrollTo(0, scrollpos);
});
window.onbeforeunload = function(e) {
localStorage.setItem('scrollpos', window.scrollY);
};
</script>
If you want a one-liner solution (ignoring imports) that only requires O(max(n, m))
work for inputs of length n
and m
, not O(n * m)
work, you can do so with the itertools
module:
from itertools import filterfalse
main_list = list(filterfalse(set(list_1).__contains__, list_2))
This takes advantage of the functional functions taking a callback function on construction, allowing it to create the callback once and reuse it for every element without needing to store it somewhere (because filterfalse
stores it internally); list comprehensions and generator expressions can do this, but it's ugly.†
That gets the same results in a single line as:
main_list = [x for x in list_2 if x not in list_1]
with the speed of:
set_1 = set(list_1)
main_list = [x for x in list_2 if x not in set_1]
Of course, if the comparisons are intended to be positional, so:
list_1 = [1, 2, 3]
list_2 = [2, 3, 4]
should produce:
main_list = [2, 3, 4]
(because no value in list_2
has a match at the same index in list_1
), you should definitely go with Patrick's answer, which involves no temporary list
s or set
s (even with set
s being roughly O(1)
, they have a higher "constant" factor per check than simple equality checks) and involves O(min(n, m))
work, less than any other answer, and if your problem is position sensitive, is the only correct solution when matching elements appear at mismatched offsets.
†: The way to do the same thing with a list comprehension as a one-liner would be to abuse nested looping to create and cache value(s) in the "outermost" loop, e.g.:
main_list = [x for set_1 in (set(list_1),) for x in list_2 if x not in set_1]
which also gives a minor performance benefit on Python 3 (because now set_1
is locally scoped in the comprehension code, rather than looked up from nested scope for each check; on Python 2 that doesn't matter, because Python 2 doesn't use closures for list comprehensions; they operate in the same scope they're used in).
This will not work:
wget -q -S -O - google.com 1>wget.txt 2>&1
since redirects are evaluated right to left, this sends html to wget.txt and the header to STDOUT:
wget -q -S -O - google.com 2>&1 1>wget.txt
The FileNameExtensionFilter
class is intended for Swing to be used in a JFileChooser
.
Try using a FilenameFilter
instead. For example:
File dir = new File("/users/blah/dirname");
File[] files = dir.listFiles(new FilenameFilter() {
public boolean accept(File dir, String name) {
return name.toLowerCase().endsWith(".txt");
}
});
localeCompare()
is slow, so if you don't care about the "correct" ordering of non-English-character strings, try your original method or the cleaner-looking:
str1 < str2 ? -1 : +(str1 > str2)
This is an order of magnitude faster than localeCompare()
on my machine.
The +
ensures that the answer is always numeric rather than boolean.
Sure, you can build a specific function for each variation of date string representations. If you consider international date formats you wind up with dozens of specific functions with rediculous names and hard to distinguish.
There is no reasonable function that matches all formats, but there is a reasonable function composition that does:
const pipe2 = f => g => x =>_x000D_
g(f(x));_x000D_
_x000D_
const pipe3 = f => g => h => x =>_x000D_
h(g(f(x)));_x000D_
_x000D_
const invoke = (method, ...args) => o =>_x000D_
o[method] (...args);_x000D_
_x000D_
const padl = (c, n) => s =>_x000D_
c.repeat(n)_x000D_
.concat(s)_x000D_
.slice(-n);_x000D_
_x000D_
const inc = n => n + 1;_x000D_
_x000D_
// generic format date function_x000D_
_x000D_
const formatDate = stor => (...args) => date =>_x000D_
args.map(f => f(date))_x000D_
.join(stor);_x000D_
_x000D_
// MAIN_x000D_
_x000D_
const toYYYYMMDD = formatDate("") (_x000D_
invoke("getFullYear"),_x000D_
pipe3(invoke("getMonth")) (inc) (padl("0", 2)),_x000D_
pipe2(invoke("getDate")) (padl("0", 2)));_x000D_
_x000D_
console.log(toYYYYMMDD(new Date()));
_x000D_
Yes, this is a lot of code. But you can express literally every string date representation by simply changing the function arguments passed to the higher order function formatDate
. Everything is explicit and declarative i.e., you can almost read what's happening.
As of June 2020, adding role='button'
to any HTML tag would add cursor: "pointer"
to the element styling.
<span role="button">Non-button element button</span>
Official discussion on this feature - https://github.com/twbs/bootstrap/issues/23709
Documentation link - https://getbootstrap.com/docs/4.5/content/reboot/#pointers-on-buttons
REMOVE DEFAULT LINK SOLVED that :visited thing is css.... you just go to your HTML and add a simple
< a href="" style="text-decoration: none" > < /a>
... thats the way html pages used to be
How about something like this:
for (int row = 0; row < 3; row ++)
for (int col = 0; col < 3; col++)
table[row][col] = (char) ('1' + row * 3 + col);
The following complete Java program:
class Test {
public static void main(String[] args) {
char[][] table = new char[3][3];
for (int row = 0; row < 3; row ++)
for (int col = 0; col < 3; col++)
table[row][col] = (char) ('1' + row * 3 + col);
for (int row = 0; row < 3; row ++)
for (int col = 0; col < 3; col++)
System.out.println (table[row][col]);
}
}
outputs:
1
2
3
4
5
6
7
8
9
This works because the digits in Unicode are consecutive starting at \u0030 (which is what you get from '0'
).
The expression '1' + row * 3 + col
(where you vary row
and col
between 0
and 2
inclusive) simply gives you a character from 1
to 9
.
Obviously, this won't give you the character 10
(since that's two characters) if you go further but it works just fine for the 3x3 case. You would have to change the method of generating the array contents at that point such as with something like:
String[][] table = new String[5][5];
for (int row = 0; row < 5; row ++)
for (int col = 0; col < 5; col++)
table[row][col] = String.format("%d", row * 5 + col + 1);
First of all it is unclear what type name has. If it has the type std::string
then instead of
string nametext;
nametext = "Your name is" << name;
you should write
std::string nametext = "Your name is " + name;
where operator + serves to concatenate strings.
If name
is a character array then you may not use operator + for two character arrays (the string literal is also a character array), because character arrays in expressions are implicitly converted to pointers by the compiler. In this case you could write
std::string nametext( "Your name is " );
nametext.append( name );
or
std::string nametext( "Your name is " );
nametext += name;
When comparing only the date of the datatimes, use the Date property. So this should work fine for you
datetime1.Date == datetime2.Date
If sudo make uninstall
is unavailable:
In a Debian based system, instead of (or after*) doing make install
you can run sudo checkinstall
to make a .deb
file that gets automatically installed. You can then remove it using the system package manager (e.g. apt
/synaptic
/aptitude
/dpkg
). Checkinstall also supports creating other types of package, e.g. RPM.
See also http://community.linuxmint.com/tutorial/view/162 and some basic checkinstall usage and debian checkinstall package.
*: If you're reading this after having installed with make install
you can still follow the above instructions and do a dpkg -r $PACKAGE_NAME_YOU_CHOSEN
afterwards.
In my case I had a component in a Shared module.
The component was loading and worked well but typescript was highlighting the html tag with red line and showed this error message.
Inside this component, I noticed I didn't import a rxjs operator.
import {map} from 'rxjs/operators';
When I added this import the error message disappeared.
Check all imports inside the component.
Hope it helps someone.
Just hit the same issue and in my case the problem was related to BOM
(byte order mark) at the beginning of the file.
json.tool
would refuse to process even empty file (just curly braces) until i removed the UTF BOM mark.
What I have done is:
set nobomb
)This resolved the problem with json.tool. Hope this helps!
BEST Approach:
I will not recommend removing public, instead on local computer create a virtual host point to public directory
and on remote hosting change public to public_html and point your domain to this directory
. Reason, your whole laravel code will be secure because its one level down to your public directory :)
I just rename server.php
to index.php
and it works
This work well for all laravel version...
Here is my Directory Structure,
/laravel/
... app
... bootstrap
... public
... etc
Follow these easy steps
require DIR.'/../bootstrap/autoload.php';
to
require DIR.'/bootstrap/autoload.php';
and
$app = require_once DIR.'/../bootstrap/start.php';
to
$app = require_once DIR.'/bootstrap/start.php';
'public' => DIR.'/../public',
to
'public' => DIR.'/..',
and that's it, now try http:// localhost/laravel/
Another way of finding out your key information is to go to your java folder, for me it was at
C:\Program Files\Java\jdk1.8.0_60\bin
and run the following command
keytool -list -v -keystore "%USERPROFILE%\.android\debug.keystore" -alias androiddebugkey -storepass android -keypass android
from the command you can easily see that keystore address is "c:\users/<%mylogin%>.android\debug.keystore" , alias is "androiddebugkey" store password is "android" key password is "android"
This is the default configuration from the Android 'Get API Key' documentation. https://developers.google.com/maps/documentation/android-api/signup
HTTP 499 in Nginx means that the client closed the connection before the server answered the request. In my experience is usually caused by client side timeout. As I know it's an Nginx specific error code.
You start new activities with intents. One method to send data to an intent is to pass a class that implements parcelable in the intent. Take note you are passing a copy of the class.
http://developer.android.com/reference/android/os/Parcelable.html
Here I have an onItemClick. I create intent and putExtra an entire class into the intent. The class I'm sending has implemented parcelable. Tip: You only need implement the parseable over what is minimally needed to re-create the class. Ie maybe a filename or something simple like a string something that a constructor can use to create the class. The new activity can later getExtras and it is essentially creating a copy of the class with its constructor method.
Here I launch the kmlreader class of my app when I recieve an onclick in the listview.
Note: below summary is a list of the class that I am passing so get(position) returns the class infact it is the same list that populates the listview
List<KmlSummary> summary = null;
...
public final static String EXTRA_KMLSUMMARY = "com.gosylvester.bestrides.util.KmlSummary";
...
@Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
lastshownitem = position;
Intent intent = new Intent(context, KmlReader.class);
intent.putExtra(ImageTextListViewActivity.EXTRA_KMLSUMMARY,
summary.get(position));
startActivity(intent);
}
later in the new activity I pull out the parseable class with
kmlSummary = intent.getExtras().getParcelable(
ImageTextListViewActivity.EXTRA_KMLSUMMARY);
//note:
//KmlSummary implements parcelable.
//there is a constructor method for parcel in
// and a overridden writetoparcel method
// these are really easy to setup.
public KmlSummary(Parcel in) {
this._id = in.readInt();
this._description = in.readString();
this._name = in.readString();
this.set_bounds(in.readDouble(), in.readDouble(), in.readDouble(),
in.readDouble());
this._resrawid = in.readInt();
this._resdrawableid = in.readInt();
this._pathstring = in.readString();
String s = in.readString();
this.set_isThumbCreated(Boolean.parseBoolean(s));
}
@Override
public void writeToParcel(Parcel arg0, int arg1) {
arg0.writeInt(this._id);
arg0.writeString(this._description);
arg0.writeString(this._name);
arg0.writeDouble(this.get_bounds().southwest.latitude);
arg0.writeDouble(this.get_bounds().southwest.longitude);
arg0.writeDouble(this.get_bounds().northeast.latitude);
arg0.writeDouble(this.get_bounds().northeast.longitude);
arg0.writeInt(this._resrawid);
arg0.writeInt(this._resdrawableid);
arg0.writeString(this.get_pathstring());
String s = Boolean.toString(this.isThumbCreated());
arg0.writeString(s);
}
Good Luck Danny117
Use setDataAndType on the Intent
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(Uri.parse(newVideoPath), "video/mp4");
startActivity(intent);
Use "video/mp4" as MIME or use "video/*" if you don't know the type.
I used fontWithSize
for a label with light system font, but it changes back to normal system font.
If you want to keep the font's traits, better to include the descriptors.
label.font = UIFont(descriptor: label.font.fontDescriptor(), size: 16.0)
If you don't want to commit, or want to commit later (commit message will still be prepared for you, which you can also edit):
git revert -n <commit>
None of the above answers worked for me due to their specified attachment format (application/octet-stream
). Use application/pdf
for best results with PDF files.
<?php
// just edit these
$to = "[email protected], [email protected]"; // addresses to email pdf to
$from = "[email protected]"; // address message is sent from
$subject = "Your PDF email subject"; // email subject
$body = "<p>The PDF is attached.</p>"; // email body
$pdfLocation = "./your-pdf.pdf"; // file location
$pdfName = "pdf-file.pdf"; // pdf file name recipient will get
$filetype = "application/pdf"; // type
// creates headers and mime boundary
$eol = PHP_EOL;
$semi_rand = md5(time());
$mime_boundary = "==Multipart_Boundary_$semi_rand";
$headers = "From: $from$eolMIME-Version: 1.0$eol" .
"Content-Type: multipart/mixed;$eol boundary=\"$mime_boundary\"";
// add html message body
$message = "--$mime_boundary$eol" .
"Content-Type: text/html; charset=\"iso-8859-1\"$eol" .
"Content-Transfer-Encoding: 7bit$eol$eol$body$eol";
// fetches pdf
$file = fopen($pdfLocation, 'rb');
$data = fread($file, filesize($pdfLocation));
fclose($file);
$pdf = chunk_split(base64_encode($data));
// attaches pdf to email
$message .= "--$mime_boundary$eol" .
"Content-Type: $filetype;$eol name=\"$pdfName\"$eol" .
"Content-Disposition: attachment;$eol filename=\"$pdfName\"$eol" .
"Content-Transfer-Encoding: base64$eol$eol$pdf$eol--$mime_boundary--";
// Sends the email
if(mail($to, $subject, $message, $headers)) {
echo "The email was sent.";
}
else {
echo "There was an error sending the mail.";
}
Multiple attributes can be connected with an and
:
GroupMember.find_or_create_by_member_id_and_group_id(4, 7)
(use find_or_initialize_by
if you don't want to save the record right away)
Edit: The above method is deprecated in Rails 4. The new way to do it will be:
GroupMember.where(:member_id => 4, :group_id => 7).first_or_create
and
GroupMember.where(:member_id => 4, :group_id => 7).first_or_initialize
Edit 2: Not all of these were factored out of rails just the attribute specific ones.
https://github.com/rails/rails/blob/4-2-stable/guides/source/active_record_querying.md
Example
GroupMember.find_or_create_by_member_id_and_group_id(4, 7)
became
GroupMember.find_or_create_by(member_id: 4, group_id: 7)
Just to summarise all the answers:
Agree with all the answers......also,
<TextView android:text=""
android:layout_width="match_parent"
android:layout_height="30dp"
android:layout_weight="2" />
should work :) I am just messing with others as TextView is my favourite (waste of memory though!)
I met with this problem too. And I figured it out by the following way:
First, open the terminal and write
mongod --dbpath {your project's path}
Second, open a new terminal and enter your project's path, write
mongo
Then it runs successfully
For the background color - the fill
property can be accessed like so:
svgElement.style.fill = '#fff';
To set the border color, do the same for the stroke
property.
Please refer to the W3C reference on SVG, as it's a broad issue.
For first 5 lines, simply do:
N=5
with open("data_file", "r") as file:
for i in range(N):
print file.next()
Assuming Table is 'SalesLT.Customer
' and the Column you are trying to figure out is 'CompanyName
' and AggCompanyName
is an Alias.
Select CompanyName, Count(CompanyName) as AggCompanyName from SalesLT.Customer
group by CompanyName
Order By Count(CompanyName) Desc;
I have spent the last few days trying to figure this out myself. Using the old json dataType gives you cross origin problems, while setting the dataType to jsonp makes the data "unreadable" as explained above. So there are apparently two ways out, the first hasn't worked for me but seems like a potential solution and that I might be doing something wrong. This is explained here [ https://learn.jquery.com/ajax/working-with-jsonp/ ].
The one that worked for me is as follows: 1- download the ajax cross origin plug in [ http://www.ajax-cross-origin.com/ ]. 2- add a script link to it just below the normal jQuery link. 3- add the line "crossOrigin: true," to your ajax function.
Good to go! here is my working code for this:
$.ajax({_x000D_
crossOrigin: true,_x000D_
url : "https://maps.googleapis.com/maps/api/place/nearbysearch/json?location=-33.86,151.195&radius=5000&type=ATM&keyword=ATM&key=MyKey",_x000D_
type : "GET",_x000D_
success:function(data){_x000D_
console.log(data);_x000D_
}_x000D_
})
_x000D_
I had similar problem and the issue was in wrong value in htaccess as shamittomar mentioned.
Change php_value post_max_size 10MB
to php_value post_max_size 10M
we can extract int from it like
$string = 'In My Car_Price : 50660.00';
echo intval(preg_replace('/[^0-9.]/','',$string)); # without number format output: 50660
echo number_format(intval(preg_replace('/[^0-9.]/','',$string))); # with number format output :50,660
demo : http://sandbox.onlinephpfunctions.com/code/82d58b5983e85a0022a99882c7d0de90825aa398
It worked for me on 000webhost by doing the following:
$headers = "MIME-Version: 1.0" . "\r\n";
$headers .= "Content-type: text/html; charset=iso-8859-1" . "\r\n";
$headers .= "From: ". $from. "\r\n";
$headers .= "Reply-To: ". $from. "\r\n";
$headers .= "X-Mailer: PHP/" . phpversion();
$headers .= "X-Priority: 1" . "\r\n";
Enter directly the email address when sending the email:
mail('[email protected]', $subject, $message, $headers)
Use ''
and not ""
.
This code works, but the email was received with half an hour lag.
If you want to use the value of the email input somewhere else on the same page, for example to do some sort of validation, you could use JavaScript. First I would assign an "id" attribute to your email textbox:
<input type="text" name="email" id="email"/>
and then I would retrieve the value with JavaScript:
var email = document.getElementById('email').value;
From there, you can do additional processing on the value of 'email'.
You can use fall-through method in switch case.
const x = 'Welcome';
switch (x) {
case 'Come':
console.log(1)
break;
case 'Welcome':
case 'Wel':
case 'come':
console.log(2)
break;
case 'Wel':
console.log(3)
break;
default:
break;
}
> Result => 2
Add multiple classes:
$("p").addClass("class1 class2 class3");
or in cascade:
$("p").addClass("class1").addClass("class2").addClass("class3");
Very similar also to remove more classes:
$("p").removeClass("class1 class2 class3");
or in cascade:
$("p").removeClass("class1").removeClass("class2").removeClass("class3");
It is possible to make a symbolic link from e.g. C:\Android\sdk
to the actual location of the sdk (which contains whitespaces), and refer to this symbolic link from within Android Studio as the location of the SDK. I have, however, not tried whether NDK will work with such a setup, even though Android Studio stops giving this warning about whitespaces.
Just want to share here some helpful extensions for kotlin
fun BigDecimal.isZero() = compareTo(BigDecimal.ZERO) == 0
fun BigDecimal.isOne() = compareTo(BigDecimal.ONE) == 0
fun BigDecimal.isTen() = compareTo(BigDecimal.TEN) == 0
In a specific case where your epoch seconds timestamp comes from SQL or is related to SQL somehow, you can obtain it like this:
long startDateLong = <...>
LocalDate theDate = new java.sql.Date(startDateLong).toLocalDate();
In the pgAdmin4, Right click on table select backup like this
After that into the backup dialog there is Dump options tab into that there is section queries you can select Use Insert Commands which include all insert queries as well in the backup.
This did the trick for me:
echo trim($entry->title);
The compiler must provide a consistent type system, and provide a set of standard conversions. Neither the integer value 0 nor the NULL pointer need to be represented by all-zero bits, but the compiler must take care of converting the "0" token in the input file to the correct representation for integer zero, and the cast to pointer type must convert from integer to pointer representation.
The implication of this is that
void *p;
memset(&p, 0, sizeof p);
if(p) { ... }
is not guaranteed to behave the same on all target systems, as you are making an assumption about the bit pattern here.
As an example, I have an embedded platform that has no memory protection, and keeps the interrupt vectors at address 0, so by convention, integers and pointers are XORed with 0x2000000 when converted, which leaves (void *)0 pointing at an address that generates a bus error when dereferenced, however testing the pointer with an if
statement will return it to integer representation first, which is then all-zeros.
At the time of writing in 2013, this was one way to do it. Composer has added support for better ways: See @igorw 's answer
DO YOU HAVE A REPOSITORY?
Git, Mercurial and SVN is supported by Composer.
DO YOU HAVE WRITE ACCESS TO THE REPOSITORY?
Yes?
DOES THE REPOSITORY HAVE A composer.json
FILE
If you have a repository you can write to: Add a composer.json
file, or fix the existing one, and DON'T use the solution below.
Go to @igorw 's answer
ONLY USE THIS IF YOU DON'T HAVE A REPOSITORY
OR IF THE REPOSITORY DOES NOT HAVE A composer.json
AND YOU CANNOT ADD IT
This will override everything that Composer may be able to read from the original repository's composer.json
, including the dependencies of the package and the autoloading.
Using the package
type will transfer the burden of correctly defining everything onto you. The easier way is to have a composer.json
file in the repository, and just use it.
This solution really only is for the rare cases where you have an abandoned ZIP download that you cannot alter, or a repository you can only read, but it isn't maintained anymore.
"repositories": [
{
"type":"package",
"package": {
"name": "l3pp4rd/doctrine-extensions",
"version":"master",
"source": {
"url": "https://github.com/l3pp4rd/DoctrineExtensions.git",
"type": "git",
"reference":"master"
}
}
}
],
"require": {
"l3pp4rd/doctrine-extensions": "master"
}
Executable file needs a main function. See below hello world demo.
#include <stdio.h>
int main(void)
{
printf("Hello world!\n");
return 0;
}
As you can see there is a main function. if you don't have this main function, ld will report "undefined reference to main' "
check my result:
$ cat es3.c
#include <stdio.h>
int main(void)
{
printf("Hello world!\n");
return 0;
}
$ gcc -Wall -g -c es3.c
$ gcc -Wall -g es3.o -o es3
~$ ./es3
Hello world!
please use $ objdump -t es3.o
to check if there is a main symbol. Below is my result.
$ objdump -t es3.o
es3.o: file format elf32-i386
SYMBOL TABLE:
00000000 l df *ABS* 00000000 es3.c
00000000 l d .text 00000000 .text
00000000 l d .data 00000000 .data
00000000 l d .bss 00000000 .bss
00000000 l d .debug_abbrev 00000000 .debug_abbrev
00000000 l d .debug_info 00000000 .debug_info
00000000 l d .debug_line 00000000 .debug_line
00000000 l d .rodata 00000000 .rodata
00000000 l d .debug_frame 00000000 .debug_frame
00000000 l d .debug_loc 00000000 .debug_loc
00000000 l d .debug_pubnames 00000000 .debug_pubnames
00000000 l d .debug_aranges 00000000 .debug_aranges
00000000 l d .debug_str 00000000 .debug_str
00000000 l d .note.GNU-stack 00000000 .note.GNU-stack
00000000 l d .comment 00000000 .comment
00000000 g F .text 0000002b main
00000000 *UND* 00000000 puts
Didn't find the answer I wanted, so I solved it myself:
modify a container div!
<div class="rotation"> <!-- Set the container div's css -->
<div class="content" id='content-1'>This div gets scaled on hover</div>
</div>
<!-- Since there is no parent here the transform doesnt have specificity! -->
<div class="rotation content" id='content-2'>This div does not</div>
css you want to persist after executing $target.css()
.content:hover {
transform: scale(1.5);
}
modify content's containing div with css()
$(".rotation").css("transform", "rotate(" + degrees + "deg)");
The following will work with new versions of jQuery.
$(window).on('load', function(){
var toggle = false;
$('button').click(function() {
toggle = !toggle;
if(toggle){
$('#B').animate({left: 0});
}
else{
$('#B').animate({left: 200});
}
});
});
This is a feature, not a bug.
See http://docs.python.org/howto/unicode.html, specifically the 'unicode type' section.
You can use Theme.applyStyle to modify your theme at runtime by applying another style to it.
Let's say you have these style definitions:
<style name="DefaultTheme" parent="Theme.AppCompat.Light">
<item name="colorPrimary">@color/md_lime_500</item>
<item name="colorPrimaryDark">@color/md_lime_700</item>
<item name="colorAccent">@color/md_amber_A400</item>
</style>
<style name="OverlayPrimaryColorRed">
<item name="colorPrimary">@color/md_red_500</item>
<item name="colorPrimaryDark">@color/md_red_700</item>
</style>
<style name="OverlayPrimaryColorGreen">
<item name="colorPrimary">@color/md_green_500</item>
<item name="colorPrimaryDark">@color/md_green_700</item>
</style>
<style name="OverlayPrimaryColorBlue">
<item name="colorPrimary">@color/md_blue_500</item>
<item name="colorPrimaryDark">@color/md_blue_700</item>
</style>
Now you can patch your theme at runtime like so:
getTheme().applyStyle(R.style.OverlayPrimaryColorGreen, true);
The method applyStyle
has to be called before the layout gets inflated! So unless you load the view manually you should apply styles to the theme before calling setContentView
in your activity.
Of course this cannot be used to specify an arbitrary color, i.e. one out of 16 million (2563) colors. But if you write a small program that generates the style definitions and the Java code for you then something like one out of 512 (83) should be possible.
What makes this interesting is that you can use different style overlays for different aspects of your theme. Just add a few overlay definitions for colorAccent
for example. Now you can combine different values for primary color and accent color almost arbitrarily.
You should make sure that your overlay theme definitions don't accidentally inherit a bunch of style definitions from a parent style definition. For example a style called AppTheme.OverlayRed
implicitly inherits all styles defined in AppTheme
and all these definitions will also be applied when you patch the master theme. So either avoid dots in the overlay theme names or use something like Overlay.Red
and define Overlay
as an empty style.
BigInteger would only be used if you know it will not be a decimal and there is a possibility of the long data type not being large enough. BigInteger has no cap on its max size (as large as the RAM on the computer can hold).
From here.
It is implemented using an int[]
:
110 /**
111 * The magnitude of this BigInteger, in <i>big-endian</i> order: the
112 * zeroth element of this array is the most-significant int of the
113 * magnitude. The magnitude must be "minimal" in that the most-significant
114 * int ({@code mag[0]}) must be non-zero. This is necessary to
115 * ensure that there is exactly one representation for each BigInteger
116 * value. Note that this implies that the BigInteger zero has a
117 * zero-length mag array.
118 */
119 final int[] mag;
From the source
From the Wikipedia article Arbitrary-precision arithmetic:
Several modern programming languages have built-in support for bignums, and others have libraries available for arbitrary-precision integer and floating-point math. Rather than store values as a fixed number of binary bits related to the size of the processor register, these implementations typically use variable-length arrays of digits.
error: command 'gcc' failed with exit status 1
yum remove audit
yum install gcc
yum install libxslt-devel libxml2-devel
cd lxml-x.x.x
python setup.py build
python setup.py install
This is a procedure to configure run release version
1- Change build variants to release version.
easiest and fastest way to check if an Object is an Array or not.
var arr = [];
arr.constructor.name ==='Array' //return true;
or
arr.constructor ===Array //return true;
or you can make a utility function:
const isArray = (obj)=> !!obj && obj.constructor ===Array;
usage:
isArray(arr); //return true
Although I guess you do not need an answer any longer, I am giving the solution for those who will come to see this post.
Derived from book.cls
\def\@endpart{\vfil\newpage
\if@twoside
\null
\thispagestyle{empty}%
\newpage
\fi
\if@tempswa
\twocolumn
\fi}
It is "\newpage" at the first line of this fragment that adds a redundant blank page after the part header page. So you must redefine the command \@endpart. Add the following snippet to the beggining of your tex file.
\makeatletter
\renewcommand\@endpart{\vfil
\if@twoside
\null
\thispagestyle{empty}%
\newpage
\fi
\if@tempswa
\twocolumn
\fi}
\makeatother
I am able to have my emulator to run my app with Google Map V.2 (with Google Play Service V.4). I followed steps that others suggested with some failures, however I learned from it and somehow make it work. This is how:
First of all: You must have coded your map app. correctly with all the appropriate permissions setup in your metafile XML, and have Google Play Services APK part of your app. To verify this is true, you must run your app on REAL device and know it works with its map there. Then you can proceed to process your emulator as shown below.
Create a new emulator, or use your existing emulator with specs:
Run you emulator (your target emulator must be running!)
Download the following APKs (available via dropbox per 4/2/2013) to your local directory (scan for virus!):
com.android.vending.apk, (Google Play Store, v.3.10.9)
com.google.android.gms.apk, (Google Play Service, v.2.0.12)
Install these two APK into your running (target) emulator with ADB command:
DOS/Console Prompt> adb -e install [path-to-APK-file]
NOTE: Possibly, you have had these APKs installed in your emulator during this trial-error, and need to re-install for some reason. You must uninstall them first by: adb -e uninstall (com.google.android.gms or com.android.vending)
Here, it is where things could get tricky. You think you were done, but when you open your app with Map again, but all you get is an error saying something in the form of: "Google Play services out of date. Requires 2012100 but found 2010110", and may see a button to "Update" Google Play. If this is the case, do NOT attempt to click the update button since it won't do anything. I got this error too, and I resolved it by both of these additional steps:
That's it, it works now nicely.
You can also create a new jsp file sayng that form is submited and in your main action file just write its file name
Eg. Your form is submited is in a file succes.jsp Then your action file will have
Request.sendRedirect("success.jsp")
All javascript methods are applicable with angularjs because angularjs itself is a javascript framework so you can use indexOf() inside angular directives
<li ng-repeat="select in Items">
<foo ng-repeat="newin select.values">
<span ng-if="newin.label.indexOf(x) !== -1">{{newin.label}}</span></foo>
</li>
//where x is your character to be found
It looks like Git tried to remove the .git/rebase-merge
directory but wasn't able to remove it completely. Have you tried copying that folder away? Also copy away the .git/rebase-apply
folder if that is present.
If anyone is using GoDaddy Shared Hosting, you can try for following solution, worked for me.
When starting DB connection, set the time_zone command in my PDO object e.g.:
$pdo = new PDO($dsn, $user, $pass, $opt);
$pdo->exec("SET time_zone='+05:30';");
Where "+05:30" is the TimeZone of India. You can change it as per your need.
After that; all the MySQL processes related to Date and Time are set with required timezone.
Source : https://in.godaddy.com/community/cPanel-Hosting/How-to-change-TimeZone-for-MySqL/td-p/31861
This is a very old question, but i don't see my understanding here so I will add my 2 cents:
Every level corresponds/maps to a type of user:
For now this should solve your problem
File source = new File("H:\\work-temp\\file");
File dest = new File("H:\\work-temp\\file2");
try {
FileUtils.copyDirectory(source, dest);
} catch (IOException e) {
e.printStackTrace();
}
FileUtils
class from apache commons-io library, available since version 1.2.
Using third party tools instead of writing all utilities by ourself seems to be a better idea. It can save time and other valuable resources.
Uninstalling(version: 2.19.2) and installing(version: 2.21.0) git client fixed the issue for me.
In case the problem is caused by an old version of the assembly in the GAC.
This can help: How to: Remove an Assembly from the Global Assembly Cache.
Consider TCP over ATM. ATM uses 48 byte frames, but clearly TCP packets can be bigger than that. A frame is the chunk of data sent as a unit over the data link (Ethernet, ATM). A packet is the chunk of data sent as a unit over the layer above it (IP). If the data link is made specifically for IP, as Ethernet and WiFi are, these will be the same size and packets will correspond to frames.
Depends exactly what you mean by create but some other ones are: