text:
Q: How to make an element fixed on top of the mobile keyboard? I am building an editor using editorJS. For PC, I created a sticky toolbar at the top which follows the viewport scroll. However, for mobile, the stikcy toolbar just won't get fixed on top of the viewport because of the damn virtual keyboard.
So I decided to remove the position: sticky; and apply position: fixed; bottom: 0; for mobile screen so that it sticks on top of the keyboard. I thought I would be able to calculate the right position for the toolbar in the resize and scroll event handlers. The procedures are as follows.

*

*if resize happens, that means either the virtual keyboard is up/down or the browser header/footer is shown/disappeared by the scroll.

*debounce the resize event so to store the visualViewport.height before the resize and after the resize.

*when resize event ends, compare the the visualViewport.height before and after and set the difference as the style.bottom of the toolbar.

*if scroll happens, visibility: hidden; the toolbar and calculate the position when the event ends. (also debouncing the scroll event)

*visiblity: visible the toolbar to show it on top of the keyboard.

But, I was not able to achieve it because the [2] did not work. The resize event did not catch the visualViewport.height before the resize even with the debounce.
handleIOSKeyboardAppear(event) {
  if (!this.isMobileResizing) {
    console.log('start!', window.visualViewport?.height) <-- the same value
    this.isMobileResizing = true
  }

  console.log('resizing...')
  if (this.mobileResizeDebounceTimerId) {
    clearTimeout(this.mobileResizeDebounceTimerId)
  }

  this.mobileResizeDebounceTimerId = setTimeout(() => {
    console.log('end!', window.visualViewport?.height)  <-- the same value
    this.isMobileResizing = false
  }, 500)

A: I found my own solution to this. Basically re-calculating the style.bottom every time the resize, scroll event happens.
the value of the style.bottom: window.innerHeight - window.visualViewport.offsetTop - window.visualViewport.height
// MARK: hang events on creation.
created() {
  if (this.isMobile) {
    window.visualViewport?.addEventListener('resize', this.handleIOSKeyboardAppear)
    window.addEventListener('scroll', this.handleMobileScroll)
  }
}

...

handleMobileScroll(event) {
  // MARK: hide the toolbar when scroll starts.
  if (!this.isMobileScrolling) {
    this.$refs.blockToolbar.style.visibility = 'hidden'
    this.isMobileScrolling = true
  }

  if (this.mobileScrollDebounceTimerId !== null) {
    clearTimeout(this.mobileScrollDebounceTimerId)
  }

  // MARK: if scroll ends, show the toolbar after 150ms.
  this.mobileScrollDebounceTimerId = setTimeout(() => {
    const toolbarBottomPosition =
      window.innerHeight -
      window.visualViewport?.offsetTop -
      window.visualViewport?.height
    const blockToolbar = this.$refs.blockToolbar
    blockToolbar.style.visibility = 'visible'
    blockToolbar.style.bottom = `${toolbarBottomPosition}px`
    this.isMobileScrolling = false
  }, 150)
},
handleIOSKeyboardAppear(event) {
  // MARK: hide the toolbar when mobile VisualViewport resize starts.
  if (!this.isMobileResizing) {
    this.$refs.blockToolbar.style.visibility = 'hidden'
    this.isMobileResizing = true
  }

  if (this.mobileResizeDebounceTimerId !== null) {
    clearTimeout(this.mobileResizeDebounceTimerId)
  }

  // MARK: if mobile VisualViewport resize ends, show the toolbar.
  this.mobileResizeDebounceTimerId = setTimeout(() => {
    const toolbarBottomPosition =
      window.innerHeight -
      window.visualViewport?.offsetTop -
      window.visualViewport?.height
    this.$refs.blockToolbar.style.bottom = `${toolbarBottomPosition}px`
    this.$refs.blockToolbar.style.visibility = 'visible'
    this.isMobileResizing = false
  }, 150)
},


text:
Q: Does Stack Overflow have automated tests? Does Stack Overflow have automated tests? If yes, what kind of (unit, integration, etc)? How are they organized and used?

A: Jeff has previously stated that certain aspects of the site's code have unit tests, but not very many. He and Joel aren't unit testing's biggest advocates ;)

A: Due to extensive use of IoC containers the code base for Stackoverflow is extremely testable, the bulk of the tests are written in Cobol and Brainf*ck, a smaller yet significant portion is tested using 42 magic 8 balls, which when shaken in harmony produce magnificent and hypnotizing sounds.

A: This goes without saying, but IMHO.
Individual reusable components are eminently testable. So much so that they are huge wins, and you'd be a fool not to have tons of unit testing wrapped around them.
Thinks like.. say... our c# markdown processor.
However, almost none of the code that most programmers produce on real world, typical projects is actually reusable in any meaningful way. And writing truly reusable code is about two orders of magnitude harder -- even with unit tests -- than writing typical one-off "just get it done" code. It takes many times the amount of effort to produce the same result if you want to build something that is legitimately reusable.
Related: The "Rule of Three"
http://maheshpai.info/?p=20

redpajama_set_name: RedPajamaStackExchange


text:
Q: Apache LDAP Auth idle-timeout As part of the security policy we are upgrading out systems to comply with, I need to set our Apache LDAP Auth to have a idle-timeout of 15 minutes.
I.e. If the user stops using the system for over 15 minutes, the next time they go to use it they will need to re-authenticate.
Is this even possible?
If so, how can I achieve it?
My auth config in my .htaccess file looks like this:
AuthName "AD Authentication"
AuthType Basic
AuthBasicProvider ldap
AuthLDAPUrl "URL"
AuthLDAPBindDN "DN"
AuthLDAPBindPassword "PASSWORD"
AuthzLDAPAuthoritative Off
require valid-user

Any ideas?

A: Unfortunately, basic authentication is not session-aware in any way.  From the web server's perspective, they're actually forced to re-authenticate with every single request.
However, all browsers cache the credentials used for a basic auth connection, so that you don't need to re-enter credentials for every resource loaded from the server.  The issue that this creates in your situation is that there's no way to 'expire' that data from the client browser; it keeps it as long as it wants.
To implement session timeouts, you may be stuck moving away from basic auth and toward a session-aware application.

A: A way to manually tell the browser to forget current credentials is to open the current address with another/invalid user.
http://testuser@www.mypage.com

A: Try instructions from this site:
http://search.cpan.org/~ksolomko/Apache2-AuthCookieLDAP-1.14/lib/Apache2/AuthCookieLDAP.pm


text:
Q: Auto zoom HTML content in wkwebview In my app I have an option for the user to top up their wallet and this uses a payment gateway which is controlled within a wkwebview. In my Xcode simulator the OTP screen zooms automatically but on a hard iPhone device it does not.
How can I force the wkwebview to fit the screen with the content?
On my Xcode simulator the content zooms automatically.

On my iPhone it doe not.

A: In place after your webView initiated add this code:
let js = "var style = document.createElement('meta'); style.name = 'viewport'; style.content = 'width=device-width, initial-scale=1, maximum-scale=1'; document.head.appendChild(style);"
webView.evaluateJavaScript(js)

This code add small piece of js to the page and "execute" it. This js code turn off autoscaling effect. For me it work well.


text:
Q: Auto Resize Background Image To Fit All Devices And Orientations Swift I am making some colorful themes for my iOS tabbed app using Swift 5 and Xcode 11. I have multiple themes with background images on them. These background images have the perfect aspect ratio for portrait orientation and hence, they work exactly how I want them to in portrait orientation:

But things go wonky when I put my device into the landscape:

The image duplicates. Is there any possible way I could solve this? I've read some other alike questions on StackOverflow, all to no results.
Here's part of my view controller's 'theme' function, which gets called every time the view loads or the view appears(these are just 2 of my themes):
func theme(){
        if UserDefaults.standard.integer(forKey: "like") == 1{
            self.tabBarController?.tabBar.barTintColor = UIColor(red:0.84, green:0.84, blue:0.84, alpha:1.0)
            self.tabBarController?.tabBar.tintColor = UIColor(red:0.21, green:0.56, blue:0.96, alpha:1.0)
            view1.backgroundColor = UIColor(red:0.78, green:0.78, blue:0.78, alpha:1.0)
            ansView.backgroundColor = UIColor.white
            historyButton.backgroundColor = UIColor.black
            for button in operatorButtons {
                button.backgroundColor = UIColor.black
            }
            for button in numberButtons {
                button.backgroundColor = UIColor(red:0.53, green:0.52, blue:0.53, alpha:0.5)
            }
            equalButton.backgroundColor = UIColor(red:1.00, green:0.49, blue:0.18, alpha:1.0)
            self.view.backgroundColor = UIColor(red:0.78, green:0.78, blue:0.78, alpha:1.0)
            view1.contentMode = UIView.ContentMode.scaleAspectFill
        }else if UserDefaults.standard.integer(forKey: "like") == 2{
            self.tabBarController?.tabBar.barTintColor = UIColor.black
            self.tabBarController?.tabBar.tintColor = UIColor(red:0.98, green:0.64, blue:0.02, alpha:1.0)
            view1.backgroundColor = UIColor(patternImage: UIImage(named: "Black-6")!)
            ansView.backgroundColor = UIColor(red:0.53, green:0.52, blue:0.53, alpha:0.5)
            historyButton.backgroundColor = UIColor(red:0.00, green:0.00, blue:0.00, alpha:0.9)
            for button in operatorButtons {
                button.backgroundColor = UIColor(red:0.00, green:0.00, blue:0.00, alpha:0.9)
            }
            for button in numberButtons {
                button.backgroundColor = UIColor(red:0.53, green:0.52, blue:0.53, alpha:0.5)
            }
            equalButton.backgroundColor = UIColor(red:0.53, green:0.52, blue:0.53, alpha:0.5)
            self.view.backgroundColor = UIColor.black
            view1.contentMode = UIView.ContentMode.scaleAspectFill
        }
//more themes
    }

By the way, I have tried:
view1.contentMode = UIView.ContentMode.scaleAspectFit

And:
view1.contentMode = UIView.ContentMode.scaleToFill

A: There is no single image that will work for you in both portrait and landscape mode. You might have to implement an adaptive design.


text:
Q: Cannot update ListView from another Activity I have a main-activity that contains a search bar and a search-activity. When I enter a string in the search bar and hit return, the search-activity is called. I am trying to update the listview in main-activity from search-activity, but that does not work. whats wrong? thx
public class MainActivity extends Activity {
static List<String> valueList;

@Override
protected void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    valueList = new ArrayList<String>();

    MainActivity.valueList.add("eins");
    MainActivity.valueList.add("zwei");
    MainActivity.valueList.add("drei");
    MainActivity.valueList.add("vier");
    MainActivity.valueList.add("fünf");
    MainActivity.valueList.add("sechs");

    ListAdapter adapter = new ArrayAdapter<String>(getApplicationContext(), android.R.layout.simple_list_item_1, MainActivity.valueList);

    final ListView lv = (ListView)findViewById(R.id.listView1);

    lv.setAdapter(adapter);

    lv.setOnItemClickListener(new AdapterView.OnItemClickListener()
    {
        @Override
        public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3)
        { }
    });
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    MenuInflater inflater = getMenuInflater();
    inflater.inflate(R.menu.options_menu, menu);

    SearchManager searchManager = (SearchManager) getSystemService(Context.SEARCH_SERVICE);
    SearchView searchView = (SearchView) menu.findItem(R.id.menu_search).getActionView();

    searchView.setSearchableInfo(searchManager.getSearchableInfo(getComponentName()));
    searchView.setIconifiedByDefault(false);

    return true;
}

}
public class SearchableActivity extends Activity {
ListView lv;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_searchable);

    android.util.Log.v("my_search", "onCreate()");
    handleIntent(getIntent());
}

@Override
protected void onNewIntent(Intent intent) {
    android.util.Log.v("my_search", "onNewIntent()");
    handleIntent(intent);
}

private void handleIntent(Intent intent) {

    if (Intent.ACTION_SEARCH.equals(intent.getAction())) {
        String query = intent.getStringExtra(SearchManager.QUERY);

        android.util.Log.v("my_search", "handleIntent()");
        android.util.Log.v("my_search", "Query: "+query);

        TextView tv;
        tv=(TextView) findViewById(R.id.textview_searchable);
        tv.setText("Suche nach: "+query);
        doMySearch(query);
    }
}

public void doMySearch(String query)
{
    List<String> valueList_new = new ArrayList<String>();

    for(String s : MainActivity.valueList) {
        if(s.contains(query)) {
            android.util.Log.v("my_search", "gefunden: "+s);
            valueList_new.add(s);
        }
    }

    setContentView(R.layout.activity_main);
    lv=(ListView)findViewById(R.id.listView1);

    ArrayAdapter adapter = new ArrayAdapter<String>(getApplicationContext(), android.R.layout.simple_list_item_1, valueList_new);
    lv.setAdapter(adapter);
    adapter.notifyDataSetChanged();

    finish();
}

}

A: I'm sure this option is not the best way but that how I solved it once.
Try to keep an attribute (a public static List) in the MainActivity with the values you want to show.
Now, set up your apadter everytime the activity comes to foreground:
@Override
public void onResume(){

    adapter = new ExpandListAdapter(MainActivity.this, valueList);
    lv.setAdapter(adapter);
    super.onResume();
}

So you just need to edit your valueList from SearchableActivity and the ListView will be automatically updated.
If you don't like public attributes, you can implement a superActivity that contains a Protected static List. The both activities should inherit from the super.
But anyway, can't you handle the intent directly from inside the MainActivity?

A: Just try this code
public void doMySearch(String query)
                {
                    List<String> valueList_new = new ArrayList<String>();

                    for (int i = 0; i < MainActivity.valueList.size(); i++) {
                        if((valueList.get(i).contains(query)))
                        {
                             valueList_new.add(valueList.get(i));
                        }
                    }
                        }

A: You cannot update listview by New another Adapter. ListView only has 1 adapter which is the first time of setting dapter for listview.
To update listview, you need to update data of your adapter. Refer: Update ListView items from another class


text:
Q: Can't get JSON response with backbone and rails My apologies now, it's been a while since I last worked in Rails and this is my first taste of backbonejs. I'm using Rails and backbonejs (both latest - rails 4.1.1, backbone 1.1.2) on a project. The rails aspect is setup correctly and returning JSON as backbone likes it, like this:
http://localhost:3000/artists
[
  {
    "id":1,
    "name":"Jeff Beck",
    "sort_name":"Beck, Jeff",
    "musicbrainz_id":"14a4bc78-1c2d-4ca7-8d1b-9b58076a2a17"
  }
]

that's from a rails controller that looks like this:
class ArtistsController < ApplicationController
  def index
    render :json => Artist.all
  end

[...]

end

the backbone model looks like this. It's in coffeescript.
class AppName.Collections.HomeCollection extends Backbone.Collection
  model: AppName.Models.Home
  url: -> '/artists'
  parse: (response) ->
    console.log "parse response %o", response
    response

class AppName.Models.Home extends Backbone.Model
  paramRoot: 'home'
  defaults: {
    name: 'default name',
    sort_name: 'default sort_name'
    musicbrainz_id: "default musicbrainz_id"
  }

the backbone router:
class AppName.Routers.HomeRouter extends Backbone.Router
  initialize: (options) ->
    @homecollection = new AppName.Collections.ArtistsCollection
    @homecollection.reset

  routes:
    ""     : "index"
    ".*"   : "index"

  index: ->
    @homecollection.fetch
      success: (collection, response, options) ->
        console.log "success fetch collection %o, response %o, options %o",
          collection, response, options
        new AppName.Views.Home.IndexView collection: collection

      error: ->
        console.log "HomeRouter error fetch, response %o"
    undefined

UPDATE: the console.log output on the fetch() success callback looks something like this:
"success fetch
    collection"
            ArtistsCollection
                    _byId: Object
                    _events: Object
                    _listenId: "l3"
                    length: 1
                    models: Array[1]
                    __proto__: ctor
            ",
    response "
            ArtistsCollection
                _byId: Object
                _events: Object
                _listenId: "l3"
                length: 1
                models: Array[1]
                __proto__: ctor
            ",
    options "
            Object
                error: function (resp) {
                    parse: true
                }
                success: function (resp) {
                    __proto__: Object
                }

and then finally the view:
AppName.Views.Home ||= {}

class AppName.Views.Home.IndexView extends Backbone.View

  el: '#home'

  tagName: 'ul'

  template: JST["backbone/templates/home/index"]

  initialize: ->
    @listenTo @collection, 'sync', @render
    console.log "home index_view init, Home.IndexView.collection %o", @collection

  render: ->
    $(@el).html @template collection: @collection
    return this

Where I'm struggling is my fetch request in the backbone router returns a collection object, but from what I've read I should be getting the JSON? The console.log from the fetch request shows the same object for both the collection and response arguments passed to success
If I try interacting with backbone in the browser console I can do the following:
var home = new AppName.Collections.ArtistsCollection
var home = home.fetch()
JSON.stringify(home.responseJSON)
"[{"id":1,"name":"Jeff Beck","sort_name":"Beck, Jeff","musi... etc"}]"

So, after all that, where am I going wrong and why can I not get JSON data from the rails request and pass that to my backbone view template?


text:
Q: In the Ideal Gas Law, why is the variable for Gas Constant labeled as an R? The formula is written as PV=nRT.
Seems like they had a logical progression going on in regards to labeling for the most part:
Pressure being a P,
Volume being a V, and
Temperature being a T.
But the Gas Constant being labeled R makes no real sense. Maybe it was a random letter chosen, but I suspect the real answer might prove interesting.

A: Quote from Wikipedia

Some have suggested that it might be appropriate to name the symbol R
  the Regnault constant in honour of the French chemist Henri Victor
  Regnault, whose accurate experimental data were used to calculate the
  early value of the constant; however, the exact reason for the
  original representation of the constant by the letter R is elusive.


text:
Q: UnitTest middleware in Larave5 I have a small middle ware for which I would like to write a test for.. I would like to do two tests:

*

*Mock role_id with 1; handle should return TRUE

*Mock role_id with 2; handle should return FALSE

How can this be done?
namespace App\Http\Middleware;

use Closure;
use Auth;
use Redirect;

class RedirectIfNotAdminUser {

    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next) {
        if (Auth::user()->role_id != config('Roles.admin')) {
            return Redirect::action('Auth\AuthController@getLogin');
        }

        return $next($request);
    }

}

At the moment the test that I run as follows:
public function testIsAdminUser() {
    $user = factory(App\User::class)->make(['role_id' => '1']);

    $this->be($user);

    $response = $this->action('GET', 'admin\DashboardController@index');

    $this->assertEquals(200, $response->getStatusCode());
}

I also had to add a line in the setup, without it $this->be() doesn't work
public function setUp() {
    $this->refreshApplication();
}

Is their a better way of doing the test?

A: Try this:
public function setUp()
{
    $this->redirectIfNotAdminUser = new App\Http\Middleware\RedirectIfNotAdminUser;
}

public function testIsAdminUser()
{
    // create a $user object (using a factory or something else).
    // assuming $user has a property role_id = 1.
    $this->actingAs($user);

    // create a mock of $request and $next.
    $response = $this->redirectIfNotAdminUser->handle($request, $next);

    $this->assertEquals(200, $response->getStatusCode());
}

public function testIsNotAdminUser()
{
    // create a $user object (using a factory or something else).
    // assuming $user has a property role_id = 2.
    $this->actingAs($user);

    // create a mock of $request and $next.
    $response = $this->redirectIfNotAdminUser->handle($request, $next);

    $this->assertEquals(302, $response->getStatusCode());
}

I believe the middleware returns a response with a status code 200 if it's OK and 302 if not.
Remember, you'll be the one to create a User instance and have it logged in (using the actingAs() method) and you'll be the one to create mocks of $request and $next that would be passed to your middleware's handle() method.


text:
Q: Create a divs table using javascript I'm trying to create a divs table using javascript. Here is my code.

var data = ['a', 'b', 'c', 'd', 'e'];
var html='';
data.forEach((item, i) => {
  if (i % 2 == 0)
    html += `<div class="row">`;
  if (i % 2 == 0)
    html += `<div class="left">${item}</div>`;
  if (i % 2 != 0)
    html += `<div class="right">${item}</div>`;
  if (i % 2 == 0)
    html += `</div>`;
    html+=`<div class="seperator"></div>`;
})

console.log(html);

the output that I get is

a

b

c

d

e

But my target Is something like this, in terms of the table. have a 2 columns table.
When coming to div, the first column is going to be
 and 2nd being
, the new row seperator will be

. My expected output is as below.

a

b

c

d

e

Please let me know how Can I achieve this.
Thanks

A: Why not just do it in a for loop and loop by 2? That way you do not have to worry about closing the tags.

const makeRow = (col1, col2) => {
  const col2HTML = col2 ? `<div class="right">${col2}</div>` : '';
  return `

${col1}

    ${col2HTML}

`;
};

var data = ['a', 'b', 'c', 'd', 'e'];
var html='';

for(let i=0; i< data.length; i+=2) {
  html += makeRow(data[i], data[i+1]);
}

console.log(html);

If you really want to do it your way, you have to add a check to see if you are at the end of the array.

var data = ['a', 'b', 'c', 'd', 'e'];
var html='';
data.forEach((item, i, arr) => {
  if (i % 2 == 0)
    html += `<div class="row">\n`;
  if (i % 2 == 0)
    html += `  <div class="left">${item}</div>\n`;
  if (i % 2 != 0)
    html += `  <div class="right">${item}</div>\n`;
  if (i % 2 != 0 || i === arr.length - 1) {
    html += `</div>\n`;
    html+=`<div class="seperator"></div>\n`;
  }
})

console.log(html);

A: It's probably easier to accomplish if you just loop through the array in 2-big steps.

var data = ['a', 'b', 'c', 'd', 'e'];
    var html='';

    for (let i = 0; i < data.length; i += 2){
        html += `<div class="row">\n`;
        if (i < data.length - 1){
            html += `<div class="left">${data[i]}</div>\n`;
            html += `<div class="right">${data[i+1]}</div>\n`;
        }else if (i = data.length - 1){
            html += `<div class="left">${data[i]}</div>\n`;
        }
        html += `</div>\n`;
        html+=`<div class="seperator"></div>\n`;
    }

    console.log(html);

A: The easiest way is to use CSS Grids

const data = ['a', 'b', 'c', 'd', 'e'];

const container = document.querySelector('#container');

for (const datum in data) {
  let div = document.createElement('div')
  div.innerText = datum;
  container.append(div);
}
#container {
  display: grid;
  grid-template-columns: 1fr 1fr;
}


text:
Q: CSS selector for elements with the same class as parent which works for any class Is it possible to select elements with the same class as the parent element using CSS without explicitly writing the class name?

Text1

Text2

Text3

Text4

Text5

For example, in this code, it should select child divs 2, 4 and 5. But I do not want write selector .cl1 .cl1{dislay: none;} since I have dozens of classes like this and I do not want to create identical selectors for each one.


text:
Q: How do I interrupt an SKAction.animate that is repeating forever to run another animation each time the .touchesBegan is called? I have a game, in SpriteKit, where the character is using one animation forever to give the illusion he is bouncing along.
let frankieTexture = SKTexture(imageNamed: "image1.png")
    let frankieTexture2 = SKTexture(imageNamed: "image2.png")
    let frankieTexture3 = SKTexture(imageNamed: "image3.png")

    let frankieBounceAnimation = SKAction.animate(with: [frankieTexture, frankieTexture2, frankieTexture3], timePerFrame: 0.3)
    let makeFrankieBounce = SKAction.repeatForever(frankieBounceAnimation)

    frankie = SKSpriteNode(texture: frankieTexture)

    frankie.position = CGPoint(x: self.frame.midX - 250, y: self.frame.midY - 450)
    frankie.size = CGSize(width: frame.size.width * 0.25, height: frame.size.height * 0.25)

    frankie.run(makeFrankieBounce)

Then under the touchesBegan, when the user taps the screen I want to interrupt that animation and replace it for another animation. This one:
let frankieOtherAnimationTexture1 = SKTexture(imageNamed: "OtherAnimation1.png")
    let frankieOtherAnimationTexture2 = SKTexture(imageNamed: "OtherAnimation2.png")
    let frankieOtherAnimationTexture3 = SKTexture(imageNamed: "OtherAnimation3.png")
    let frankieOtherAnimationTexture4 = SKTexture(imageNamed: "OtherAnimation4.png")

    let frankieOtherAnimationAnimate = SKAction.animate(with: [frankieOtherAnimationTexture1, frankieOtherAnimationTexture2, frankieOtherAnimationTexture3, frankieOtherAnimationTexture4], timePerFrame: 0.2)

    let makeFrankieOtherAnimation = SKAction.repeat(frankieOtherAnimationAnimate, count: 1)

How do I get the repeatForever to pause and run the second animation and then restart? I have played with a few if, then statements and can't seem to get it to do it...
Thanks in advance!

A: Wow! Sorry everyone... I realized after fiddling for several hours that I forgot the
Frankie.run(SKAction)

in my code after my second animation in the .touchesBegan method... It runs fine without having to pause the first animation that is repeating forever.


text:
Q: Using TreeVew to navigate to different pages I would like to make a Settings window similar to the Options box in VS2012. I expect to write a XAML page for each set of settings. But how do I use a TreeView to choose which XAML page gets shown? Should the XAML page be part of the objects that are loaded in the tree?
(I should say, how do I do this in an MVVM way... if possible.)

A: I would do it along the lines of the following:
Have a view model class, call it something like SettingsPageVM, which contains a Title and PageUrl to your page.
Having created a list of your SettingsPageVM, bind it to your TreeView with a list called something like Items, with a HierarchicalDataTemplate, such as:
<HierarchicalDataTemplate DataType="{x:Type vm:SettingsPageVM}" ItemsSource="{Binding Items, Mode=OneWay}">
    <StackPanel>
        <Button Content="{Binding Title}" Command="Open"/>
    </StackPanel>
</HierarchicalDataTemplate>

Then, bind the open command to handle navigating to your page:
<UserControl.CommandBindings>
    <CommandBinding Command="Open" CanExecute="OpenCanExecute" Executed="OpenExecuted"></CommandBinding>
</UserControl.CommandBindings>

Is the issue you are having deeper than this?


text:
Q: How to sort files in a directory by name, size, last modified or other OS supported? Does java have underlying or direct method to sort files in a directory by name, size, last modified or other OS supported?
Common way to sort files is: read all file info in a container, than sort elements of that container.
But I want to know, does java provide some APIs which is native or invoke system call to sort directly? Maybe OS or underlying file system can provide better method? is there?


text:
Q: insert with subquery and select I would like to insert rows into a table using  a select statement to query specific data but use data from a different table as part of the insert.  EXmaple:
Table A: Clients  where data is being queried and copied
Table B: MailOptOut where data is being inserted
I want to insert in MailOptOut table two values, a hardcoded field 'Summer Promotion' and then the acct# from the clients table (client.acct_no)
Here is my code that isn't working:
INSERT INTO PL00.DBO.mailcoptout (MC_NAME, ACCT_NO)
VALUES
('Summer Service Promo',  client.acct_no),
('Referral Rewards Doubled', client.acct_no),
('Holiday Decorating 1',  client.acct_no),
('Holiday Decorating 2', client.acct_no)
select client.acct_no, mailcoptout.* from plshared.dbo.client  left join PL00.DBO.mailcoptout on mailcoptout.ACCT_NO = client.ACCT_NO
where client.U_SOLICIT = 'y'
and client.acct_no = '131335'
and client.INACTIVE <> 'y'
and mailcoptout.MC_NAME is null

A: Is this what you are trying to do?
INSERT INTO PL00.DBO.mailcoptout (MC_NAME, ACCT_NO)
    select x.mc_name, client.acct_no
    from plshared.dbo.client c left join
         PL00.DBO.mailcoptout mc
         on mailcoptout.ACCT_NO = client.ACCT_NO cross join
         (select 'Summer Service Promo' as MC_NAME union all,
          select 'Referral Rewards Doubled' as MC_NAME union all
          select 'Holiday Decorating 1' as MC_NAME union all
          select 'Holiday Decorating 2' as MC_NAME
         ) x
    where c.U_SOLICIT = 'y' and
          c.acct_no = '131335' and
          c.INACTIVE <> 'y' and
          mc.MC_NAME is null;


text:
Q: How to show that $\int\nabla^2\psi_n (x)\overline{\psi_m (x)}dx=0$ Let us consider the three-dimensional time-dependent Schrödinger equation that has the general solution $\psi(x,t)=\sum_n c_n\psi_n(x)e^{-iE_nt/\hbar},$ where the functions $\psi_n$ are orthogonal.
How to show that
$$\int[\nabla^2\psi_n (x)]\overline{\psi_m (x)}dx=0.$$

A: I don't think the result is true in general.  It is certainly not true for the harmonic oscillator ground state where $\psi_0^{\prime\prime}(x)$ is proportional to $\psi_0(x)$ and $\psi_2(x)$.
More generally, recall that the kinetic energy $T=-\frac{1}{2m}\nabla^2$
and that, by assumption of your problem,
$$
H\psi_n(x)=E_n\psi_n(x)=T\psi_n(x)+V\psi_n(x)
$$
so that
\begin{align}
T\psi_n(x)&= E_n\psi_n(x)-V\psi_n(x)\\
T_{mn}&=\int dx\,\psi^*_m T\psi_n(x)= E_n\delta_{mn} - V_{mn}
\end{align}
so unless the potential is diagonal, the kinetic energy will not be diagonal either, and thus $\psi^{\prime\prime}_n(x)$ will not be a multiple of itself, implying that
$$
\int dx\,\psi^*_m(x) \left(\frac{d^2}{dx^2}\psi_n(x)\right)\ne 0\, .
$$


text:
Q: It's necessary that I not be lazy?
It's necessary that I not be lazy?

Is this sentence correct? Because it sounds odd - but due to the structure of subjunctive:

It's important /(un)necessary /essential + that + Subject + (should) + V.inf without to.

A: The sentence

It's necessary that I not be lazy?

is not a subjunctive form. It is grammatical but a bit unusual, and thus feels awkward. I think this is partly due to the negative form. An equivalent positive form feels better.

*

*It is necessary that I be diligent?

*It is necessary that I be productive?

Also, when asking this as a question, it is more usual to invert subject and verb:

*

*Is it necessary that I be diligent?

*Is it necessary that I be productive?

leading to

Is it necessary that I not be lazy?

A: It is not a very good sentence.
It is structured as a statement, but it has a question mark. Questions should use question syntax.
It has a confusing negative structure, and it uses a subjunctive, in a very odd way.
You would never say this.  How about?

Is laziness permitted?
Am I allowed to be lazy?

This sentence means the same, but I can understand this one easily.  It took me 5 minutes to work out what your sentence means.
Or you can change the adjective:

Is it necessary to be energetic and industrious?

But all of these questions are odd:  Nobody asks permission to be lazy.


text:
Q: How to alter a regex to be non-greedy (JS) I'm trying to replace var tags with an attribute so they are wrapped in square brackets
data.replace(/<var .*?="">(\d+)<\/var>/ig, '[[[$1]]]');

but this will not work if there are multiple var tags. For example,
<var id-0=""></var> responds in <var num="">1</var> days

will result in
[[[1]]] days

but the result I need is
<var id-0=""></var> responds in [[[1]]] days

A: using this <var [^=]*="">(\d+)<\/var>
regex101 - 1

in case there would be more than one attribute or the attribute has value like num="something" then the above wouldn't work, instead, use this <var( [^=]*="[^"]*")*>(\d+)<\/var> with [[[$2]]] for substitution.
regex101 - 2

A: Change the .*? to be [^=">]*?. Even though it isn't greedy, you are allowing it to capture far too much.


text:
Q: How to extract the shape of MovieClip? We have a flash application that we are planning on converting to javascript. It's a pretty simple map application with an image as the background and a bunch of simple polygon movie clips that represent destinations on the map.
I would like to iterate through each movie clip and extract the shape into an array of x,y points to redraw the polygon using an external javascript function.
Is this possible with actionscript?

A: If you want to export the shape coordinates at author time, you can do try the JSFL script recommented by @strille or this one or export transparent images (if that's not too limiting for your application).
If you need to export the shapes at runtime, you can use the awesome as3swf library to decompile the swf and export the shapes. Have a look at the ShapeExport wiki as there are couple of handy exporters for js like JSCanvasShapeExporter and the more generic JSONShapeExporter

A: Flash Player 11.6 introduced readGraphicsData() which does exactly what you ask for.
If you need to target an earlier version, then there's no simple way to read shape coordinates from a display object with ActionScript at runtime unfortunately.
If you just want to extract the shape coordinates once someone has written a jsfl script for Flash CS3 which looks like it might be able to help you out.

A: There are ways you can read the coordinates from an SWF. For instance, I've written a parser in PHP (link). Getting the data doesn't help though, as it turns out. The Flash painting model is different enough from the HTML5 one enough to make transfer exceeding difficult. The main obstacle I discovered is that in Flash, a path can be filled with two fill styles: one for area enclosed by the path, the other for enclosed area considered to be "outside" by the even-odd rule (e.g. the pentagon in the middle of a star). Since the HTML5 canvas let you specify only one fill style, you can't redraw shapes from Flash accurately. I was trying to create a tool that extract shapes as SVG and was getting a lot of gap and holes in the result.


text:
Q: Errors on Apple App Store submission I am currently deploying my first application to the Apple app store. I have gone through the provisioning profile, development profile set up and distribution certificates and I finally got as far as to be able to upload the app to the app store, but now it is giving me these errors:
=====================================================
ERROR ITMS-90032: "Invalid Image Path - No image found at the path referenced under key 'CFBundleIconFile': 'icon.png'"
ERROR ITMS-90032: "Invalid Image Path - No image found at the path referenced under key 'CFBundleIconFile': 'icon.png'"
=====================================================
ERROR ITMS-90023: "Missing required icon file. The bundle does not contain an app icon for iPad of exactly '76x76' pixels, in .png format for iOS versions >= 7.0."
ERROR ITMS-90023: "Missing required icon file. The bundle does not contain an app icon for iPad of exactly '76x76' pixels, in .png format for iOS versions >= 7.0."
=====================================================
ERROR ITMS-90023: "Missing required icon file. The bundle does not contain an app icon for iPad of exactly '152x152' pixels, in .png format for iOS versions >= 7.0."
ERROR ITMS-90023: "Missing required icon file. The bundle does not contain an app icon for iPad of exactly '152x152' pixels, in .png format for iOS versions >= 7.0."
=====================================================
ERROR ITMS-90474: "Invalid Bundle. iPad Multitasking support requires these orientations: 'UIInterfaceOrientationPortrait,UIInterfaceOrientationPortraitUpsideDown,UIInterfaceOrientationLandscapeLeft,UIInterfaceOrientationLandscapeRight'. Found 'UIInterfaceOrientationLandscapeLeft,UIInterfaceOrientationLandscapeRight' in bundle 'coza.companyname.appname'."
ERROR ITMS-90474: "Invalid Bundle. iPad Multitasking support requires these orientations: 'UIInterfaceOrientationPortrait,UIInterfaceOrientationPortraitUpsideDown,UIInterfaceOrientationLandscapeLeft,UIInterfaceOrientationLandscapeRight'. Found 'UIInterfaceOrientationLandscapeLeft,UIInterfaceOrientationLandscapeRight' in bundle 'coza.companyname.appname'."
=====================================================
ERROR ITMS-90475: "Invalid Bundle. iPad Multitasking support requires launch story board in bundle 'coza.companyname.appname'."
ERROR ITMS-90475: "Invalid Bundle. iPad Multitasking support requires launch story board in bundle 'coza.companyname.appname'."
I have Googled and tried suggestions but still exactly the same errors come up. Things I have tried is clearing up legacy options in the info-plist file as well as selecting all device orientation options and deselecting them, but I still get the same errors.
Any help would be appreciated.
Thanks!


text:
Q: Can conversion of MapInfo WOR to ArcGIS MXD preserve styles and coordinate systems? Is there any ways to migrate from MapInfo's data with WOR project file to ArcGIS MXD project file without leaving all styles and coordinate system?
I know that I can convert from TAB files to SHP files via ogr2ogr but what's about the styles information?
P.S. I have MapInfo Professional 12 and ArcGIS Desktop 9.3.1. Also, I can't use the Tab Reader Tool now.

A: There are some fundamental differences between MapInfo's styling and ArcGIS's.
Most importantly, MapInfo styles features per-feature in a style string (it's a weird encoding, including a funny representation of RGB in a single int value). ArcGIS styles things in a MapInfo 'thematic', which really means, in categories (that's a over-simplification, as there are other ways to do it, but that's default).
Now, there are some examples where folks have converted MapInfo styles into QGIS styles, which are similar in structure to ArcGIS styles, see: http://nathanw.net/2011/08/08/new-tool-mapinfo-to-qgis-style-converter/. And you can use FME to read and set MapInfo style attributes. I have a couple of custom FME transformers that convert a native MI style into a string that you can store in SQL Server and back again, which is a sort-of similar thing, but still per-feature.
Of course, your real question is about a whole workspace. Short answer is: no. The two packages are far too dissimilar for that to work in any nice way. And, really, there is so much different between them that you'd be missing out on functionality if you could convert them.
So, my recommendation is do it all again. It's not hard to make a workspace or MXD (or a QGIS project) and it gives you an opportunity to rethink things.


text:
Q: windows 8 PATH causes problems I have been trying to use both C++ and python on the atom editor, so I needed to add two paths to my system (The python3 executable and the MinGW compiler executable). The problem is apparently I cannot add two different paths to my system, so I have to change paths and restart atom each time I need to change languages.
In addition, this causes lots of problems, for example, I can't use pip anymore (the command tells me there is no such thing as pip!) even though it used to work perfectly before.
Just please tell me how can I fix the pip problem, I've used it before to install pytz, but after changing paths from Python to MinGW and back again to Python it stopped working.
I have a windows 8 32-bit system


text:
Q: BouncyCastle does not find algorithms that it provides? I'm playing around with BouncyCastle 1.46 To my surprise, the catch-block in the snippet below is tripped quite often.
Security.addProvider(new BouncyCastleProvider());

final Set<String> found = new HashSet<String>();
final Set<String> missing = new HashSet<String>();

final DefaultSignatureAlgorithmIdentifierFinder finder = new DefaultSignatureAlgorithmIdentifierFinder();
for (Service service : new BouncyCastleProvider().getServices()) {
    if ("Signature".equals(service.getType())) {
        final String algorithm = service.getAlgorithm();
        try {
            finder.find(algorithm);
            found.add(algorithm);
        } catch (IllegalArgumentException ex) {
            missing.add(algorithm);
        }
    }
}

System.out.println("Found: " + found);
System.out.println("Missing: " + missing);

I appear to be unable to use most of the algorithms through the Finder, even though Services exist that provide those algorithms. What am I doing wrong?
Update I've changed the code a little to illustrate the issue better. What might be of interest is that I am using the JDK1.5 version of BouncyCastle. The code above gives this output:
Found: [RIPEMD256WithRSAEncryption, MD5WithRSAEncryption, MD2WithRSAEncryption, SHA384WithRSAEncryption, SHA224WITHECDSA, SHA384WITHDSA, SHA256WITHDSA, SHA512WithRSAEncryption, SHA512WITHDSA, RIPEMD160WithRSAEncryption, SHA224WithRSAEncryption, SHA256WITHECDSA, RIPEMD128WithRSAEncryption, SHA384WITHECDSA, SHA256WithRSAEncryption, SHA512WITHECDSA, SHA1WithRSAEncryption, SHA224WITHDSA]
Missing: [SHA1WITHECNR, NONEwithECDSA, ECDSA, SHA512withRSA/PSS, RIPEMD160WITHECDSA, RSA, GOST3410, SHA256WITHECNR, MD5withRSA/ISO9796-2, SHA1WITHCVC-ECDSA, SHA384withRSA/PSS, SHA1withRSA/PSS, MD4WithRSAEncryption, RSASSA-PSS, SHA512WITHECNR, SHA256WITHCVC-ECDSA, SHA1withRSA/ISO9796-2, SHA224withRSA/PSS, SHA224WITHCVC-ECDSA, RAWRSASSA-PSS, SHA256withRSA/PSS, NONEWITHDSA, SHA384WITHECNR, RIPEMD160withRSA/ISO9796-2, DSA, ECGOST3410, SHA224WITHECNR, 1.2.840.113549.1.1.10]

A: I think that DefaultSignatureAlgorithmIdentifierFinder is part of the bcmail API. It returns algorithm identifiers recognized by this API. (Check Cryptographic Message Syntax) On the other hand the bouncy castle provider provides more algorithms. You may check the source of DefaultSignatureAlgorithmIdentifierFinder where the recognized algorithms are hardcoded:
algorithms.put("MD2WITHRSAENCRYPTION", PKCSObjectIdentifiers.md2WithRSAEncryption);
algorithms.put("MD2WITHRSA", PKCSObjectIdentifiers.md2WithRSAEncryption);
algorithms.put("MD5WITHRSAENCRYPTION", PKCSObjectIdentifiers.md5WithRSAEncryption);
algorithms.put("MD5WITHRSA", PKCSObjectIdentifiers.md5WithRSAEncryption);
algorithms.put("SHA1WITHRSAENCRYPTION", PKCSObjectIdentifiers.sha1WithRSAEncryption);
algorithms.put("SHA1WITHRSA", PKCSObjectIdentifiers.sha1WithRSAEncryption);
algorithms.put("SHA224WITHRSAENCRYPTION", PKCSObjectIdentifiers.sha224WithRSAEncryption);
algorithms.put("SHA224WITHRSA", PKCSObjectIdentifiers.sha224WithRSAEncryption);
algorithms.put("SHA256WITHRSAENCRYPTION", PKCSObjectIdentifiers.sha256WithRSAEncryption);
algorithms.put("SHA256WITHRSA", PKCSObjectIdentifiers.sha256WithRSAEncryption);
algorithms.put("SHA384WITHRSAENCRYPTION", PKCSObjectIdentifiers.sha384WithRSAEncryption);
algorithms.put("SHA384WITHRSA", PKCSObjectIdentifiers.sha384WithRSAEncryption);
algorithms.put("SHA512WITHRSAENCRYPTION", PKCSObjectIdentifiers.sha512WithRSAEncryption);
algorithms.put("SHA512WITHRSA", PKCSObjectIdentifiers.sha512WithRSAEncryption);
algorithms.put("SHA1WITHRSAANDMGF1", PKCSObjectIdentifiers.id_RSASSA_PSS);
algorithms.put("SHA224WITHRSAANDMGF1", PKCSObjectIdentifiers.id_RSASSA_PSS);
algorithms.put("SHA256WITHRSAANDMGF1", PKCSObjectIdentifiers.id_RSASSA_PSS);
algorithms.put("SHA384WITHRSAANDMGF1", PKCSObjectIdentifiers.id_RSASSA_PSS);
algorithms.put("SHA512WITHRSAANDMGF1", PKCSObjectIdentifiers.id_RSASSA_PSS);
algorithms.put("RIPEMD160WITHRSAENCRYPTION", TeleTrusTObjectIdentifiers.rsaSignatureWithripemd160);
algorithms.put("RIPEMD160WITHRSA", TeleTrusTObjectIdentifiers.rsaSignatureWithripemd160);
algorithms.put("RIPEMD128WITHRSAENCRYPTION", TeleTrusTObjectIdentifiers.rsaSignatureWithripemd128);
algorithms.put("RIPEMD128WITHRSA", TeleTrusTObjectIdentifiers.rsaSignatureWithripemd128);
algorithms.put("RIPEMD256WITHRSAENCRYPTION", TeleTrusTObjectIdentifiers.rsaSignatureWithripemd256);
algorithms.put("RIPEMD256WITHRSA", TeleTrusTObjectIdentifiers.rsaSignatureWithripemd256);
algorithms.put("SHA1WITHDSA", X9ObjectIdentifiers.id_dsa_with_sha1);
algorithms.put("DSAWITHSHA1", X9ObjectIdentifiers.id_dsa_with_sha1);
algorithms.put("SHA224WITHDSA", NISTObjectIdentifiers.dsa_with_sha224);
algorithms.put("SHA256WITHDSA", NISTObjectIdentifiers.dsa_with_sha256);
algorithms.put("SHA384WITHDSA", NISTObjectIdentifiers.dsa_with_sha384);
algorithms.put("SHA512WITHDSA", NISTObjectIdentifiers.dsa_with_sha512);
algorithms.put("SHA1WITHECDSA", X9ObjectIdentifiers.ecdsa_with_SHA1);
algorithms.put("ECDSAWITHSHA1", X9ObjectIdentifiers.ecdsa_with_SHA1);
algorithms.put("SHA224WITHECDSA", X9ObjectIdentifiers.ecdsa_with_SHA224);
algorithms.put("SHA256WITHECDSA", X9ObjectIdentifiers.ecdsa_with_SHA256);
algorithms.put("SHA384WITHECDSA", X9ObjectIdentifiers.ecdsa_with_SHA384);
algorithms.put("SHA512WITHECDSA", X9ObjectIdentifiers.ecdsa_with_SHA512);
algorithms.put("GOST3411WITHGOST3410", CryptoProObjectIdentifiers.gostR3411_94_with_gostR3410_94);
algorithms.put("GOST3411WITHGOST3410-94", CryptoProObjectIdentifiers.gostR3411_94_with_gostR3410_94);
algorithms.put("GOST3411WITHECGOST3410", CryptoProObjectIdentifiers.gostR3411_94_with_gostR3410_2001);
algorithms.put("GOST3411WITHECGOST3410-2001", CryptoProObjectIdentifiers.gostR3411_94_with_gostR3410_2001);
algorithms.put("GOST3411WITHGOST3410-2001", CryptoProObjectIdentifiers.gostR3411_94_with_gostR3410_2001);

Cheers!

A: Did you add BouncyCastle to the security providers? You can do that with this line:
Security.addProvider(new BouncyCastleProvider());

A: This answer is not directly related to BouncyCastle. But, I thought this would be useful for others:
In my case, I was using SpongyCastle. I got a similar problem:
org.e.h.p: cannot create signer: Provider SC does not provide SHA256WITHRSA
at org.e.h.a.a.a(SourceFile:101)
It turned out that proguard was removing some of the required classes. After adding the following in proguard config file:
    -keep class org.spongycastle.** { *; }
the problem was resolved.

A: You can add Bouncy Castle to security providers on Your java platform in two steps:
1. Copy BC librarys (currently bcpkix-jdk15on-149.jar, bcprov-jdk15on-149.jar) to directory $JAVA_HOME/jre/lib/ext/
2. Register BC provider: edit file $JAVA_HOME/jre/lib/security/java.security  and under line
security.provider.1=sun.security.provider.Sun

add Your BC provider
security.provider.2=org.bouncycastle.jce.provider.BouncyCastleProvider

Change numbers of rest providers. The whole block of providers should be similar to:
security.provider.1=sun.security.provider.Sun
security.provider.2=org.bouncycastle.jce.provider.BouncyCastleProvider
security.provider.3=sun.security.rsa.SunRsaSign
security.provider.4=sun.security.ec.SunEC
security.provider.5=com.sun.net.ssl.internal.ssl.Provider
security.provider.6=com.sun.crypto.provider.SunJCE
security.provider.7=sun.security.jgss.SunProvider
security.provider.8=com.sun.security.sasl.Provider
security.provider.9=org.jcp.xml.dsig.internal.dom.XMLDSigRI
security.provider.10=sun.security.smartcardio.SunPCSC


text:
Q: Как можно упростить этот `чудо` код? Привет, есть текущее положение (cur), максимальное значение (maxcur) нужно знать предыдущее и следующее:
cur = 0;       // current
maxcur = 5;    // maximum current
next = 1;      // init next frame
prev = maxcur; // init prev frame

function playMe(delta){
   // delta can be +1 or -1 (left/right)

   cur = cur + delta;
   if (cur>maxcur) cur = 0; if (cur<0) cur = maxcur;
   next = cur + 1; if (next>maxcur) next = 0;
   prev = cur - 1; if (prev<0) prev = maxcur;

   // any action with current,next and prev frames
}

$('#left').click(function(){ playMe(1); });
$('#right').click(function(){ playMe(-1); });

По сути получается обычный сдвиг, писал так всегда, а тут взглянул аж 4 условия (if) на одну итерацию. может быть есть способ сделать проще?
A: так:
cur = (cur+maxcur+delta)%maxcur;
next = (cur+1)%maxcur;
prev = (cur+maxcur-1)%maxcur;

зы только maxcur надо +1 сделать, а то это будет 0..maxcur-1...


text:
Q: What should VAGRANT_CWD be set to? What is the default value of VAGRANT_CWD? I set it to something else and now I need to "reset" it. I tried unset, but that won't work because it returns an error saying that the working directory is ~/. (invalid).

A: It should not be set at first place - if you have this value set in your env, make sure to remove it from where you set it.
The default value is the current directory (Dir.pwd in ruby). If you have the variable set, you can try to define the current directory as the default folder
export VAGRANT_CWD="./"

This will create the .vagrant directory along with the Vagrantfile in the current directory you run the command


text:
Q: Envio de anexo direto para o e-mail Eu uso um formulário bem simples de envio de dados para e-mail, eu incluí um botão de upload... Como faria uma programação simples pra que esse arquivo seja enviado no e-mail como anexo?

Inscreva-se já!

    <form action="email-2.php" method="post">

        <input type="text" name="nome" size="" placeholder="Nome Completo">

        <input type="text" name="endereco" size="" placeholder="Endereço">

        <input type="text" name="cpf" size="" placeholder="CPF">

        <input type="text" name="rg" size="" placeholder="RG">

        <input type="text" name="fone" size="" placeholder="Telefone">

        <input type="text" name="email" size="" placeholder="E-mail">

        <input type="file" />

        <textarea name="mensagem" cols="65" rows="8" placeholder="Escreva aqui sua mensagem"></textarea>

            <input class="botao" type="submit" value="Enviar">

    </form>

<?php
$nome = $_POST['nome'];
$endereco = $_POST['endereco'];
$cpf = $_POST['cpf'];
$rg = $_POST['rg'];
$email = $_POST['email'];
$fone = $_POST['fone'];
$msg = $_POST['mensagem'];

$destino = "destino@gmail.com";
$assunto = "Cadastro Via Site";

$headers = "From: ". $nome;
$headers .= "\r\n" . 'Cc: destino2@gmail.com' . "\r\n";

$corpoemail = 'Contato Via site

           Nome: '   .$nome.'
           Endereço: '   .$endereco.'
           CPF: '   .$cpf.'
           RG: '   .$rg.'
           Email: '   .$email.'
           Fone: ' .$fone.'
           Mensagem: '.$msg.' ';

if(mail($destino, $assunto, $corpoemail, $headers)){

   echo "";

} else{

  echo "";

}

?>


text:
Q: excel error 1004 unable to get the countifs property of worksheetfunction class appear hello i really hoping someone can help me with this.
i want to use countifs in VBA using 3 criteria and has this script
Sub Count()
Dim DateSmall As Date
Dim DateBig As Date
Dim Company As String

DateSmall = CDate(Sheet2.Range("C28"))
DateBig = CDate(Sheet2.Range("E28"))
Company = Sheet2.Range("B28").Value

Set rGo = Sheet1.Range("E10", Sheet1.Range("E" & Rows.Count).End(xlUp))
Set rCompany = Sheet1.Range("C10", Sheet1.Range("C" & Rows.Count).End(xlUp))

CountIn = Application.WorksheetFunction.CountIfs(rGo, ">=" & DateSmall, rGo, "<=" & DateBig, rCompany, Company)

MsgBox CountIn

End Sub

but it got error 1004 but when i use 2 criteria using the same script i can this is the script using 2 criteria
Sub Count()
Dim DateSmall As Date
Dim DateBig As Date

DateSmall = CDate(Sheet2.Range("C28"))
DateBig = CDate(Sheet2.Range("E28"))

Set rGo = Sheet1.Range("E10", Sheet1.Range("E" & Rows.Count).End(xlUp))

CountIn = Application.WorksheetFunction.CountIfs(rGo, ">=" & DateSmall, rGo, "<=" & DateBig)

MsgBox CountIn

End Sub

i hope someona can help me with this . . .
Sheet 1
02-Oct-14   SSI
02-Oct-14   SSI
02-Oct-14   SSI
03-Oct-14   SSI
03-Oct-14   SSI
03-Oct-14   SSI
07-Oct-14   SSI
07-Oct-14   SSI
07-Oct-14   SCI
03-Oct-14   SSI
06-Oct-14   SSI
06-Oct-14   SSI
06-Oct-14   SSI
06-Oct-14   SSI
06-Oct-14   SSI
03-Oct-14   SSI
07-Oct-14   SCI
02-Oct-14   JSU
02-Oct-14   JSU
30-Sep-14   JSU

Sheet 2
SSI     1-Jan-14        10-Jan-16

A: I think the reason is the range for rGO and rCompany is different.
IMPORTANT: Each additional range must have the same number of rows and columns as the criteria_range1 argument. The ranges do not have to be adjacent to each other.
For more details information, you can refer to
https://support.office.com/en-us/article/COUNTIFS-function-dda3dc6e-f74e-4aee-88bc-aa8c2a866842
Hope this help.

A: Sheet 1
02-Oct-14   SSI
02-Oct-14   SSI
02-Oct-14   SSI
03-Oct-14   SSI
03-Oct-14   SSI
03-Oct-14   SSI
07-Oct-14   SSI
07-Oct-14   SSI
07-Oct-14   SCI
03-Oct-14   SSI
06-Oct-14   SSI
06-Oct-14   SSI
06-Oct-14   SSI
06-Oct-14   SSI
06-Oct-14   SSI
03-Oct-14   SSI
07-Oct-14   SCI
02-Oct-14   JSU
02-Oct-14   JSU
30-Sep-14   JSU

sheet 2
SSI    1-Jan-14     10-Jan-16


text:
Q: React render return statements with () vs return with nothing I have a question regarding the difference between
import React from 'react';
import Container from 'react-bootstrap/Container';

class Home extends React.Component {
    render() {
        return (

          <Container></Container>

        )
      }
};

export default Home

and
import React from 'react';
import Container from 'react-bootstrap/Container';

class Home extends React.Component {
    render() {
        return

          <Container></Container>

      }
};

export default Home

Note the parentheses after return, if I don't have the parentheses I get a compile error


text:
Q: Sitecore: Serving lower resolution images to low bandwidth clients I'm looking for an easy way to serve lower resolution images to mobile browsers. I'd like to generate these lower quality images on the fly and store them in media cache for use by similar browsers. Any ideas as to a good implementation of this? (Note: We have sc:image tags all over the site, and I want to avoid changing these.)

A: Right, interesting question! Let's split this into two problems you need to handle: the lower quality image generation and the caching.
Lower Quality Images
For this I would look at adding a new processor into the getMediaStream pipeline. This processor could check the UserAgent of the incoming request and resample the image accordingly. For example if it determines the browser is a standard desktop browser it will do nothing, but if it is a mobile browser it will take the image stream and create a new one with a resampled image.
Take a look at this example which shows how you can add your own processor into the pipeline. Also you could reflect on the Sitecore.Resources.Media.ResizeProcessor for an idea on how to do this.
Caching
Looking through the code for the Sitecore media caching, it uses the current MediaOptions of the request to generate a unique key for the cache. MediaOptions has a CustomOptions property which is a string dictionary, anything you add into there will also get used in the hash to create the key.
I would look at extending the handler for image processing, override the ProcessRequest method and get the current MediaOptions for the request. At that point you could identify the browser (using similar code for the first part, you could share this logic), and if it is a mobile browser you could insert something into the Dictionary of the MediaOptions, e.g. "Mobile":"1". Then you would just call the base.ProcessRequest method and let the standard process continue on.
This page shows an example of extending the MediaRequestHandler.
Hope that helps, I haven't looked into it in more detail and there are likely some potential problems I've overlooked, but hopefully that's enough to allow you to make a start. It's a bit of code but it seems like a good library to have with plenty of reuse possibilities, and you won't need to alter the  tags across your site.


text:
Q: Can gapi.client.load for cloud endpoints return a promise? A google gapi.client.load for a google api can return a promise as discussed here.  However, if you wish to use the javascript client for your own app engine component using cloud endpoints, the gapi.client.load has a different method signature, as shown in this angular post:
  gapi.client.load('guestbook', 'v1', function() {
    $scope.is_backend_ready = true;
    $scope.list();
  }, '/_ah/api');

Here, there is a fourth parameter and it is not the success function.  So I'm not sure how a promise can be used.

A: Investigating this further, it seems that if you send "undefined" as the 3rd praameter, then you can use this call as a promise, like:
  gapi.client.load('guestbook', 'v1', undefined, '/_ah/api').then(function() {
    $scope.is_backend_ready = true;
    $scope.list();
  });

I haven't seen any google documentation of this.  Please let me know if this exists.

A: If the goal is just to perform some action after the client is loaded you could simply check for an error in the callback function. This will work with or without the client.init function. Something like this:
gapi.client.init({}).then(() => {
     gapi.client.load('some-api', "v1", (err) => { callback(err) }, "https://someapi.appspot.com/_ah/api");
}, err, err);

function callback(loadErr) {
    if (loadErr) { err(loadErr); return; }
    // success code here
}

function err(err){
     console.log('Error: ', err);
     // fail code here
}

Example
If you really need a promise returned you can simply wrap this code in a function and return a promise in the callback function above.

A: "Cloud Endpoints client library does not support the Promise API of AngularJS for describing this kind of asynchronous processing."
You can find this stated in https://cloud.google.com/solutions/angularjs-cloud-endpoints-recipe-for-building-modern-web-applications .
To get around this is to write (or better generate) thin wrapper by converting all callbacks to promises
as explained in https://riztaak.wordpress.com/2015/04/05/promises-promises-using-google-cloud-endpoint-in-angularjs/


text:
Q: Registar un plan dependiendo de la fecha actual Trabajo en laravel, y necesito hacer lo siguiente que un plan se registre si la fechaFin de la bd es es mayor a la fecha actual. Lo he intendado de esta manera:
$fechaFin = $buscar->fechaFinal; //obtenieno el dato de la base de datos

y validando estaticamente la fecha actual
if ($fechaFin >=  '2018-06-18') {
        $plan = new PlanesPago;
        $plan->codigoPlan=$request->get('codigoPlan');
        $plan->descripcion=$request->get('descripcion');
        $plan->idCiclo=$request->get('idCiclo');
        $plan->save();

    }else{

         return json_encode("No Puedes Crear Otro Plan en  un mismo Periodo");

    }

pero no hace la validación y registra.

A: No puedes comparar fechas directamente. Lo que esta pasando en tu código es que php esta comparado 2 String no dos fechas.
Para comparar fechas, te puedes apoyar en la clase DateTime que php proporciona.
Ejemplo:
$hoy = new DateTime(); // Fecha actual
$fechaFin = new DateTime($buscar->fechaFinal); // Fecha bd

if ($fechaFin >=  $hoy) {
    echo 'La fecha es mayor o igual a hoy';
} else {
    echo 'la fecha es menor a hoy';
}

A: El gestor de fechas de Laravel es Carbon.
Te pondre un par de ejemplos para que veas el funcionamiento y puedas hacer todo lo que quieres.

*

*Fecha actual
$hoy = Carbon::now();

*Compara fecha
$primera = Carbon::create(2012, 9, 5, 23, 26, 11);
$segunda= Carbon::create(2012, 9, 5, 20, 26, 11, 'America/Vancouver');
if($primera->gt($segunda)) // bool(false)
{
// Mayor
}


text:
Q: How do I configure Apache Camel to sequentially execute processes based on a trigger file? I have a situation where an external system will send me 4 different files at the same time.  Let's call them the following:

*

*customers.xml (optional)

*addresses.xml (optional)

*references.xml (optional)

*activity.xml (trigger file)

When the trigger file is sent and picked up by Camel, Camel should then look to see if file #1 exists, if it does then process it; if it doesn't then move on to file #2 and file #3 applying the same if/then logic.  Once that logic has been performed, then it can proceed with file #4.
I found elements like OnCompletion and determining if body is null or not but if someone has a much better idea, I would greatly appreciate it.

A: As I thought this further, it turns out this was more of a sequence problem.  The key here is that I would be receiving the files in batches at the same time.  That being said, I created a pluggable CustomComparator.
Once I created my CustomComparator class to order my files in a given ArrayList index position, I was able to route the messages in the order I wanted them in.


text:
Q: MYSQL query syntax - subquery with trim I have 2 tables
Table1 -> msqt_subjects
  id  category
 - 1   maths
 - 2   physics
 - 3   history

Table2 -> msqt_class

  id  subjects
 - 1   ,1,2,3,

My query is

select id, category from msqt_subjects where id IN (select TRIM(BOTH ',' FROM subjects) from msqt_class where id =1)

It returns only one row, actually it has to return 3 rows.
When I run subquery seperately it result as 1,2,3.
I like to use as single query instead of seperate queries.
Is the query correct?

A: Try this:
SELECT ms.id, ms.category
FROM msqt_subjects ms
INNER JOIN msqt_class mc ON mc.subjects LIKE CONCAT('%,', ms.id, ',%')
WHERE mc.id = 1;

OR
SELECT ms.id, ms.category
FROM msqt_subjects ms
INNER JOIN msqt_class mc ON FIND_IN_SET(ms.id, TRIM(BOTH ',' FROM mc.subjects))
WHERE mc.id = 1;


text:
Q: Class 'Twilio\Rest\Client' not found in laravel 5.2 ,how to do call recording using Twilio of incoming and out going calls This is My code
 $client = new Twilio\Rest\Client($sid, $token);

 $call = $client->calls->create(
        "+9xxxxxxxxxx9",
        array("url" => "http://demo.twilio.com/docs/voice.xml", "record"
      => true)
    );

how to do call recording using Twilio of incoming and out going calls?
Thanks in advance :)

A: Have you updated composer.json to include the Twilio library?
If not, run the following command line:
composer require twilio/sdk

This should then update composer and download the SDK files. See if this fixes your issue.
Or follow the setup instructions here.

If you have already added twilio to the composer.json file, try running:
composer update --no-scripts

And then
php artisan optimize


text:
Q: .removeAttribute in Javascript fails I'm trying to remove the id from all <td> that are named "date[]", because if i keep the id, a jquery datepicker messes up later.
the following function is used to remove the id
document.getElementsByName('date[]').removeAttribute('id');
Firebug tells me:
TypeError: document.getElementsByName(...).removeAttribute is not a function
I tried all combinations of ' and ", and also just date instead of date[].
I don't think its a typo, because i copied this from w3schools

A: document.getElementsByName returns a collection, you have to iterate and remove:
var collection = document.getElementsByName('date[]');
for (var i = 0; i < collection.length; i++) {
    collection[i].removeAttribute('id');
}


text:
Q: Colorbox ajax + colorpicker plugin I'm currently making a form which is opened via colorbox's ajax feature. On my form i would like to make one of the input fields react on a jquery plugin (colorpicker), but it wont apply to the input field. I've tried to apply the script ( on the main page (where i load the ajax colorbox), and on the page that i get by ajax, but without luck.
The only thing i have to do in the plugin, is to load the js file and set the input's id="color". It isn't working as intended.
I've searched google dry for a solution to this problem.
Hope anybody has a solution to this problem!
UPDATE:
I use this in my headtag to initialize the jquery plugin (ColorPicker)

This is the function i call on Colorbox
jQuery(".ajax").colorbox({onComplete:function(){}});

The button where i execute the ajax function
poll_title.'" href="edit.php?poll_id='.$load_all_polls->poll_id.'">Indstillinger

Button with ajax call works fine!
And the inputfield which ColorPicker should respond to (inside the ajax call)
<input class="color" value="<?php echo $poll->bg_color; ?>" name="bg_color">

Again, the problem is that ColorPicker loads through my (DOM tree?) before the Ajax is called, therefore ColorPicker wont recognize the inputfield in the ajax call.
What to do ? :)
Regards,
Mathias

A: The input field is loaded after page load via ajax. So colorpicker can not able to bind event to this newly loaded element. You should use delegate for attaching event to input field.


text:
Q: apt-get wants to remove MariaDB on Debian Wheezy I've set up my server to use MariaDB and used the installation instructions on the web page. It worked quite well. Now, if I want to dist-upgrade, apt-get wants to replace MariaDB with MySQL:
The following packages will be REMOVED:
  libmariadbclient18 mariadb-client-5.5 mariadb-client-core-5.5 mariadb-server mariadb-server-5.5 mariadb-server-core-5.5
...
The following packages will be upgraded:
  libmysqlclient18 mysql-common

Why does apt-get want to do this? How can I stop apt-get from doing so?

A: Unfortunately, this is a known problem, with an already-filed bug report: see here. The conflict arises because mysql and mariadb use conflicting versions of the library libmysqlclient18.
The quick fix is to give mariadb a higher priority than mysql, I have done it like this:
 echo -e "Package: libmysqlclient18\nPin: origin mirror2.hs-esslingen.de\nPin-Priority: 1000" > /etc/apt/preferences.d/mariadb-mysqlclient18

(This is for my mirror, of course... You'll have to adjust the above command to your mirror).
I agree it should be fixed upstream, but in the meantime...


text:
Q: Is it possible to get the result generated by eclipse link? I have this entity with Generationtype table working..
@Id
@Basic(optional = false)
@Column(name = "app_users_pk")
@TableGenerator( name = "appseqstore", table = "app_seq_store", pkColumnName = "app_seq_name", pkColumnValue = "app_users_pk", valueColumnName = "app_seq_value", initialValue = 1, allocationSize = 1 )
@GeneratedValue( strategy = GenerationType.TABLE,generator = "appseqstore")
private Long appUsersPk;

when I execute a create command this is what eclipselink do.. (on my glassfish log)
UPDATE app_seq_store SET app_seq_value = app_seq_value + ? WHERE app_seq_name = ?
    bind => [1, app_users_pk]
SELECT app_seq_value FROM app_seq_store WHERE app_seq_name = ?
    bind => [app_users_pk]
INSERT INTO app_users (app_users_pk, username) VALUES (?, ?)
    bind => [33, try lang]
SELECT app_users_pk, username FROM app_users

When I check the mysql log I found that eclipselink make 3 queries
1st is to update the table by incrementing by 1
2nd get the incremented value
and 3rd insert using the the incremented value
(on mysql query log)
SET autocommit=0
UPDATE app_seq_store SET app_seq_value = app_seq_value + 1 WHERE app_seq_name = 'app_users_pk'
SELECT app_seq_value FROM app_seq_store WHERE app_seq_name = 'app_users_pk'
INSERT INTO app_users (app_users_pk, username) VALUES (33, 'try lang')
commit
SET autocommit=1

now I see that eclipselink issued an "select" query..
is it possible to get the result from that query? because i also want that key to be used in other related table, or is their any other way to achieve this purpose?


text:
Q: External VGA monitor isn't detected. How do I fix this I have an ASUSPro Laptop Model P2420L (CPU: i5 5500U, RAM: 8GB, GPU: Intel HD 5500 Graphics), and my screen stopped working yesterday, and when I plugged an Acer external monitor using a VGA cable, the GUI system isn't working properly. When I boot it, it works fine, and when I'm presented with the login page, I can enter my password and connect normally, but afterwards, it gets stuck on a blank screen I can only use command line to work on it.
When I type xrandr on the command prompt I get the following:

Can't open display (You can zoom in the image)

And all displays are OFF.
https://imgur.com/jU6zbvP


text:
Q: SM strings being replaced by ® symbol on iPad device I have to show SM(Service Mark) symbol in a label. Whatever way I employ, it is displayed on the device as the ® (Registered) symbol.
I have tried to do this using simply a string:
NSString *stringSM =  [otherString stringByReplacingOccurrencesOfString:@"SM" withString:@"℠"];

And using unicode :
NSString *stringSM =  [otherString stringByReplacingOccurrencesOfString:@"SM" withString:@"\u2120"];

where otherString is a string received from the web service, containing other information including this SM symbol.


text:
Q: How to instantiate a class with asynchronous Firebase methods in Swift? I am instantiating a User class via a Firebase DataSnapshot. Upon calling the initializer init(snapshot: DataSnapshot), it should asynchronously retrieve values from two distinct database references, namely pictureRef and nameRef, via the getFirebasePictureURL and getFirebaseNameString methods' @escaping completion handlers (using Firebase's observeSingleEvent method). To avoid the 'self' captured by a closure before all members were initialized error, I had to initialize fullName and pictureURL with temporary values of "" and URL(string: "initial"). However, when instantiating the class via User(snapshot: DataSnapshot), these values are never actually updated with the retrieved Firebase values.
import Firebase

class User {

 var uid: String
 var fullName: String? = ""
 var pictureURL: URL? = URL(string: "initial")

//DataSnapshot Initializer

init(snapshot: DataSnapshot) {

self.uid = snapshot.key

getFirebasePictureURL(userId: uid) { (url) in

    self.getFirebaseNameString(userId: self.uid) { (fullName) in

        self.fullName = fullName
        self.profilePictureURL = url

    }
}

func getFirebasePictureURL(userId: String, completion: @escaping (_ url: URL) -> Void) {

    let currentUserId = userId
    //Firebase database picture reference
    let pictureRef = Database.database().reference(withPath: "pictureChildPath")

    pictureRef.observeSingleEvent(of: .value, with: { snapshot in

        //Picture url string
        let pictureString = snapshot.value as! String

        //Completion handler (escaping)
        completion(URL(string: pictureString)!)

    })

}

func getFirebaseNameString(userId: String, completion: @escaping (_ fullName: String) -> Void) {

    let currentUserId = userId
    //Firebase database name reference
    let nameRef = Database.database().reference(withPath: "nameChildPath")

    nameRef.observeSingleEvent(of: .value, with: { snapshot in

        let fullName = snapshot.value as? String

       //Completion handler (escaping)
        completion(fullName!)

        })
     }
  }

Is there a reason this is happening, and how would I fix this so it does initialize to the retrieved values instead of just remaining with the temporary values? Is it because init isn't asynchronous?

Edit: I am reading data from one node of the Firebase database and, using that data, creating a new node child. The method that initializes the User class will create this new node in the database as:
As you can see, the children are updated with the temporary values so it seems the program execution does not wait for the callback.
Any help would be much appreciated!

A: By the comments, it seems we could reduce the code considerably which will also make it more manageable
(SEE EDIT)
Start with a simpler User class. Note that it is initialized by passing the snapshot and then reading the child nodes and populating the class vars
class UserClass {
    var uid = ""
    var username = ""
    var url = ""

    init?(snapshot: DataSnapshot) {
        self.uid = snapshot.key
        self.username = snapshot.childSnapshot(forPath: "fullName").value as? String ?? "No Name"
        self.url = snapshot.childSnapshot(forPath: "url").value as? String ?? "No Url"
    }
}

then the code to read a user from Firebase and create a single user
func fetchUser(uidToFetch: String) {
    let usersRef = self.ref.child("users")
    let thisUserRef = usersRef.child(uidToFetch)
    thisUserRef.observeSingleEvent(of: .value, with: { snapshot in
        if snapshot.exists() {
            let user = UserClass(snapshot: snapshot)
            //do something with user...
        } else {
            print("user not found")
        }
    })
}

I don't know how the user is being used but you could add a completion handler if you need to do something else with the user outside the Firebase closure
func fetchUser(uidToFetch: String completion: @escaping (UserClass?) -> Void) {
    //create user
    completion(user)

EDIT:
Based on additional info, I'll update the answer. Starting with restating the objective.
The OP has two nodes, a node that stores user information such as name and another separate node that stores urls for pictures. They want to get the name from the first node, the picture url from the second node and create a new third node that has both of those pieces of data, along with the uid. Here's a possible structure for pictures
pictureUrls
   uid_0: "some_url/uid_0"
   uid_1: "some_url/uid_1"

and then we'll use the same /users node from above.
Here's the code that reads the name from /users, the picture url from /pictureUrls combines them together and writes out a new node with an /author child that contains that data and the uid.
func createNode(uidToFetch: String) {
    let usersRef = self.ref.child("users")
    let thisUserRef = usersRef.child(uidToFetch)

    let imageUrlRef = self.ref.child("pictureUrls")
    let thisUsersImageRef = imageUrlRef.child(uidToFetch)

    let allAuthorsRef = self.ref.child("allAuthors")

    thisUserRef.observeSingleEvent(of: .value, with: { snapshot in
        let userName = snapshot.childSnapshot(forPath: "name").value as? String ?? "No Name"

        thisUsersImageRef.observeSingleEvent(of: .value, with: { imageSnap in
            let imageUrl = imageSnap.value as? String ?? "No Image Url"

            let dataToWrite = [
                "full_name": userName,
                "profile_picture": imageUrl,
                "uid": uidToFetch
            ]

            let thisAuthorRef = allAuthorsRef.childByAutoId()
            let authorRef = thisAuthorRef.child("author")
            authorRef.setValue(dataToWrite)
        })
    })
}

The output to firebase is this
allAuthors
   -LooqJlo_Oc-voUHai3k //created with .childByAutoId
      author
         full_name: "Leroy"
         profile_picture: "some_uid/uid_0_pic"
         uid: "uid_0"

which exactly matches the output shown in the question.
I removed the error checking to shorten the answer so please add that back in and I also omitted the callback since it's unclear why one it needed.

A: This is very hacky.
You should add completionHandler in init method. So, when your asynchronous call completed you will get actual value of object.
init(snapshot: DataSnapshot, completionHandler: @escaping (User) -> Void) {

    self.uid = snapshot.key

    getFirebasePictureURL(userId: uid) { (url) in

        self.getFirebaseNameString(userId: self.uid) { (fullName) in

            self.fullName = fullName
            self.profilePictureURL = url

            completionHandler(self)
        }
    }
}

I hope this will help you.


text:
Q: Drupal: getting exact date from created column in ddbb So I'm trying to extract the created, access and login dates from the users in the database of a Drupal site. But the values are like: 1377783381, 1384248801...
I have tried to do this in the SQL:
SELECT  DATE_SUB(NOW(), INTERVAL us.created SECOND), us.name
FROM users us

But it returns dates from 1970 - 1974 and dates should go from 2013 - 2018 approx.
The truth is that I don't know what represents that numbers, but they aren't seconds.

A: Perhaps the values are milliseconds.  Try this:
SELECT DATE_SUB(NOW(), INTERVAL us.created/1000 SECOND), us.name
FROM users us;

For some reason, MySQL supports seconds and microseconds, but not milliseconds.
Actually, as I think about it, subtracting a millisecond value from the current time doesn't make sense.  More likely, this is a unix time value:
SELECT FROM_UNIXTIME(us.created), us.name
FROM users us;


text:
Q: Error RunBuild CircleCI "Disabling ANDROID_TEST_USES_UNIFIED_TEST_PLATFORM" option because this is a dynamic-feature module i got some error when integrated my project with CircleCI. The error in RunBuild process and the message error like the picture below
RunBuild Error in CircleCI
I haven't found a solution yet, can you guys help me?


text:
Q: Is the Captain's Yacht from Enterprise-D (the Calypso) warp-capable? I'm wondering if it is mentioned anywhere whether or not the Captain's Yacht from the Enterprise-D (the Calypso) is warp-capable?
I understand that it is described as a large, fancy shuttlecraft, and we see in the shows that even small shuttles are warp-capable, but I'd prefer to not guess here. We can probably "safely assume" that it is warp-capable, but I'm wondering specifically if anyone has a reference in any "canon" material from the shows (including for example Okudagrams) that speaks to this?
If there is nothing like that, then is there any "quasi-canon" or non-canon stuff that mentions it?

A: Apparently, no
The Star Trek: The Next Generation Technical Manual (considered, if not entirely canon, at least a quasi-official authoritative source), gives the following description of the Captain's Yacht:

The yacht is capable of sustained sublight velocities
  approaching 0.65c. The impulse propulsion system (IPS)
  consists of six sequential beam-fusion reaction chambers
  feeding a central toroidal driver coil. Each chamber measures
  1.3 m in diameter and is similar to its larger IPS cousins on the
  Enterprise. The reaction exhaust is vented through the driver
  coil and magnetohydrodynamic (MHD) accelerator for impulse travel. The MHD tap provides power to the navigational
  deflector grid for removal of interstellar dust and gas from the
  vehicle flight path. For atmosphere flight the exhaust is
  redirected after it exits the MHD tunnel and sent through the
  aerodyne engines around the ellipse equator. The normal
  atmosphere cruising velocity is Mach 6; maximum safe waverider velocity is Mach 20. Magnetic turbulence contour equalizers, variants of the navigational deflector, provide momentum conditioning at Mach transitions.
The Enterprise is designed to operate safely without the
  yacht in place, since its structural integrity field and inertial
  damping fields produce slightly modified fields in those areas
  to compensate for the concavity of the yacht docking structure. Yacht operational rules in the vicinity of the starship are
  generally the same as those for other auxiliary spacecraft,
  with the difference being that the yacht, during emergency undockings, may be safely deployed at velocities as high as
  Warp Factor 7. The yacht's systems are designed to afford the
  craft a smooth falloff of warp field, though the decaying field
  energy cannot be sustained for any appreciable time.

It explicitly states that the Yacht is equipped with an Impulse Engine, but doesn't provide any information about a Warp Propulsion System, seemingly implying that it has none; also, the statement that it can be detached from the starship traveling at Warp speed and perform a "smooth falloff of warp field" seem to further imply that it can't sustain warp speeds on its own.
On the schematic that is present on the Manual, some systems are detailed (including the Impulse engine), but also here there is no mention of a Warp engine:

A: Short answer: Yes, it was warp capable but at low speeds only.
From Memory Beta:

At 10m long, 18m wide and 8m high with two decks, the yacht had a mass of 95 metric tonnes and was unarmed. The interior featured a flight deck, two small staterooms, bunks for the flight crew a galley and access to the engine compartment. It could accomodate two flight crew and one service representative plus VIP passengers.

More importantly on that same page, are the specifications:

Maximum speed: Warp 0.65 in space, Mach 20 in atmosphere

[Edit] Thanks to @HorusKol for some more information
It seems that the quoted figure from Memory Beta may not be entirely correct.  In this question, it quotes the speed as 0.65 times the speed of light, not warp 0.65.

A: The Calypso does not appear to have been warp capable. The Calypso's specs are not laid out in any on screen / canon source, but the closest to canon source is a trading card authored by series contributors Rick Sternbach and Michael Okuda:

This card makes specific mention, in descriptive text and diagram, of the vessel's impulse engines; however, no mention of warp engines is made. Further, the ship's top speed (0.65 times the speed of light) does not require warp drive.
Source: Memory Alpha


text:
Q: Can't get tkinter's StringVar's trace method to work Whenever I try to run my code, which looks a bit like this:
from tkinter import OptionMenu, StringVar, Tk

class Foo(OptionMenu):

    def __init__(self, master, options):
        self.bar = StringVar()
        self.bar.set(options[0])
        self.bar.trace("w", lambda: self.mouseCallback("foobar"))
        super().__init__(master, self.bar, *options)

    def mouseCallback(self, baz):
        print(baz)

def mainCycle():
    while True:
        root.update()

if __name__ == "__main__":
    opts = ["A", "LONG", "LIST", "OF", "OPTIONS"]
    root = Tk()
    foobarbaz = Foo(root, opts)
    foobarbaz.pack()
    mainCycle()

I get the following error:
Exception in Tkinter callback
Traceback (most recent call last):
  File "C:\Program Files\Python35\lib\tkinter\__init__.py", line 1549, in __call__
    return self.func(*args)
  File "C:\Program Files\Python35\lib\tkinter\__init__.py", line 3285, in __call__
    self.__var.set(self.__value)
  File "C:\Program Files\Python35\lib\tkinter\__init__.py", line 260, in set
    return self._tk.globalsetvar(self._name, value)
_tkinter.TclError: can't set "PY_VAR0":

And even after a lot of "Stack Overflowing", I still can't get it to work. How can I avoid/fix this error?

A: The signature of the callback function for StringVar.trace() should be something like def callback(*args), therefore the lambda you use in StringVar.trace() should be changed to:
self.bar.trace("w", lambda *args: self.mouseCallback("foobar"))


text:
Q: Display three non-negative integers in increasing order Prompt the user to type in three non-negative integers. Display the integers in an increasing order.
import java.util.Scanner;

{
    int number1,number2,number3;
         Scanner keyboard = new Scanner (System.in);
         number1=keyboard.nextInt();
         number2=keyboard.nextInt();
         number3=keyboard.nextInt();

        if(number1<number2&&number1<number3&&number2<number3)
        {
            System.out.println(number1);
            System.out.println(number2);
            System.out.println(number3);
        }

        else if(number1>number2&&number1>number3&&number2>number3)
        {
            System.out.println(number3);
            System.out.println(number2);
            System.out.println(number1);
        }

        else if(number1<number2&&number1<number3&&number2>number3)
        {
            System.out.println(number1);
            System.out.println(number3);
            System.out.println(number2);
        }

        else if(number2>number1&&number2>number3&&number1>number3)
        {
            System.out.println(number3);
            System.out.println(number1);
            System.out.println(number2);
        }

        else if (number3>number1&&number3>2&&number1>number2)
        {
            System.out.println(number2);
            System.out.println(number1);
            System.out.println(number3);
        }

Output:
2
1
3
1
2
3
P.S. I am not allowed to use while  statement, swing and for. I am newbie at java so this what I could come up with. Is there a faster way? Thank you.

A: This is an implementation of bubble sort. It is not much better than your implementation but gives a glimpse into how you would use a loop in the future. What happens is that after the first 2 blocks, the largest value will be in the third spot. The next block then fixes the remaining two numbers. You could move the if clauses into a separate function that accepts as parameters the two numbers you want to compare and switch.
public static void main(String[] args) {

 int number1,number2,number3;
 Scanner keyboard = new Scanner (System.in);
 number1=keyboard.nextInt();
 number2=keyboard.nextInt();
 number3=keyboard.nextInt();

 int temp;

 if (number2 < number1){
     temp = number2;
     number2 = number1;
     number1 = temp;
 }

 if (number3 < number2){
     temp = number3;
     number3 = number2;
     number2 = temp;
 }

 if (number2 < number1){
     temp = number2;
     number2 = number1;
     number1 = temp;
 }
  System.out.println(number1);
  System.out.println(number2);
  System.out.println(number3);

}

A: Your way is fast enough for three numbers but what happens if the next assignment requires you to do the same task on a list of 10 integers?  Or 100?  Or 1,000,000?
As you continue learning to program you will learn that the performance of the strategy you choose to solve a problem (the algorithm) can vary immensely depending on the size of the input.  The strategy you chose in your attempt of this problem was to enumerate all the ways that three numbers can relate by size - not too bad since there are only six - but for even ten numbers there are millions of ways!  A better choice of algorithm would be to store them in a structure where their size increases from item to item (by sorting them) since most sorting algorithms will still perform well with very large input sets.

A: Speed is not an issue.  Correctness is.  What happens if number1 and number3 are equal?  That said, here is a more compact piece of logic that should be fairly efficient.
if (number2 < number1)
{
    temp_number = number1;
    number1 = number2;
    number2 = temp_number;
}

if (number3 < number2)
{
    temp_number = number2;
    number2 = number3;
    number3 = temp_number;

    if (number2 < number1)
    {
        temp_number = number1;
        number1 = number2;
        number2 = temp_number;
    }
}

System.out.println(number1);
System.out.println(number2);
System.out.println(number3);

A: Since it is homework, i think a nested if with it's else's would be a cleaner solution. It works also correctly with equal values, negative values and does not swap the values of the variables. :-)
    int number1, number2, number3;
    Scanner keyboard = new Scanner(System.in);

    number1 = keyboard.nextInt();
    number2 = keyboard.nextInt();
    number3 = keyboard.nextInt();

    if (number1 < number2) {
        if (number2 < number3) {
            System.out.println("123 " + number1 + number2 + number3);
        } else {
            if (number1 < number3)
                System.out.println("132 " + number1 + number3 + number2);
            else
                System.out.println("231 " + number3 + number1 + number2);
        }
    } else {
        if (number3 < number2) {
            System.out.println("321 " + number3 + number2 + number1);
        } else {
            if (number3 < number1)
                System.out.println("312 " + number2 + number3 + number1);
            else
                System.out.println("213 " + number2 + number1 + number3);
        }
    }

A: boolean n2 ;
if(num1>num2) {
    if(num1>num2 && num1>num3){
        if(num2>num3){
            System.out.println(num1+">"+num2+">"+num3);
            n2=true;
        }
        else {
            System.out.println(num1+">"+num3+">"+num2);
        }
    }
    else if(n2){
        if(num1<num3){
            System.out.println(num2+">"+num3+">"+num1);
        }
    }
}
else {
    System.out.println(num2+">"+num1+">"+num3);
}


text:
Q: Formatting and use a condition to derive % and N/A MyData
0.00
0.25
0.80
0.00
0.00
0.77
In the SSRS report I need to display output as below
MyData
N/A
25%
80%
N/A
N/A
77%
I have tried below code in the Visual Studio Expression
=iif(fields!mydata = "0" then "N/A" fields!mydata & "%")
It is not working.
Can you help
=iif(fields!mydata = "0" then "N/A" fields!mydata & "%")
Output on the report should look like below
MyData
N/A
25%
80%
N/A
N/A
77%

A: The SSR IIF function doesn't use the THEN keyword (nor ELSE) - it uses commas to separate the function parameters using the syntax:
=IIF(<Boolean Expression>, <TRUE Result>, <False Result>)

There's also a FORMATPERCENT function to do inline formatting with text in a text box. It has a second parameter for the number of places to show after the decimal.

Returns an expression formatted as a percentage (that is, multiplied
  by 100) with a trailing % character.

-Visual Studio 2016 Function Description
Your expression would be
=IIF(Fields!mydata.Value = "0", "N/A", FORMATPERCENT(Fields!mydata.Value, 0) )


text:
Q: System.ComponentModel.Win32Exception: The wait operation timed out I have to read very large data, approximately 300000 lines, from SQL tables and write it to a text file in my application (.net application and using C#). I have a stored procedure to read that data, and I am using DataAdapter and DataSet in my code to get that data, but I am getting the error

The wait operation timed out

when it executed dataAdapter.Fill(dataSet). I tried to change value of timeout, but it didn't work. I tried different approaches, but nothing seems to work. It works for few lines, but it doesn't work for large data. I can't grab small data because they need whole data in one text file

A: First and very important change I did-- I changed my DateTime object to shortDate (e.g startDate.ToShortDateString() ), so it deleted the time part from my date, and it helped a lot with my SQL stored procedure with datetime param.
2nd change --- read directly from SqlDataReader and writing directly to text file with Read method, because DataTable will not hold to long file (e.g 420000KB)
using (SqlDataReader rdr = comm.ExecuteReader())
{
   while (rdr.Read())
   {
     file.WriteLine(rdr.GetString(0), true);
   }
}

3rd change --I increased my timeout
comm.CommandTimeout = 600; ( e.g for 10min)

A: See if you can split one query into multiple ones and execute it simultaneously and join the results on completion of all fetches.
Or even using a DataReader will help.


text:
Q: Procurar o valor do Array B no Array A e retornar os valores do Array A no Array C Possuo dois arrays: ArrayB com valores confirmados e ArrayA com todos os cadastrados.
Como crio um ArrayC procurando os emails do ArrayB no ArrayA?
ArrayA
(
[0] => stdClass Object
        (
            [id] => 5c4fa45sdfsd546
            [name] => Fulano
            [surname] => de Tal
            [mail] => fulano@gmail.com
            [phone] => (11) 91234-5678
            [enable] =>  1
        )

    [1] => stdClass Object
        (
            [id] => 5cd2ef021930f40f6455ad1e
            [name] => Beltrano
            [surname] => de Tal
            [mail] => beltrano@live.com
            [phone] => (11) 99876-5432
            [enable] =>
        )

    [2] => stdClass Object
        (
            [id] => 5cd8s9df89000sdf6455ad1e
            [name] => Cilano
            [surname] => de Tal
            [mail] => cilano@live.com
            [phone] => (12) 99876-5432
            [enable] => 1
        )
}

ArrayB
(
    [0] => cilano@live.com
    [1] => foo.com
}

A: $ArrayA = [
[
    'id'      => '5c4fa45sdfsd546',
    'name'    => 'Fulano',
    'surname' => 'de Tal',
    'mail'    => 'fulano@gmail.com',
    'phone'   => '(11) 91234-5678',
    'enable'  => true,
],
[
    'id'      => '5cd2ef021930f40f6455ad1e',
    'name'    => 'Beltrano',
    'surname' => 'de Tal',
    'mail'    => 'beltrano@live.com',
    'phone'   => '(11) 99876-5432',
    'enable'  => false,
],
[
    'id'      => '5cd8s9df89000sdf6455ad1e',
    'name'    => 'Cilano',
    'surname' => 'de Tal',
    'mail'    => 'cilano@live.com',
    'phone'   => '(12) 99876-5432',
    'enable'  => true,
]
];

$ArrayB = [
    'cilano@live.com',
    'foo.com',
];

$data_via_array_filter = array_filter($ArrayA, function($item) use ($ArrayB) {
    return in_array($item['mail'], $ArrayB);
});

echo "Dados via array_filter\n";
var_dump($data_via_array_filter);

$data_via_array_map = array_map(function($item) use ($ArrayB) {
    if(in_array($item['mail'], $ArrayB)) {
        return $item;
    }
}, $ArrayA);

echo "\nDados via array_map\n";
var_dump($data_via_array_map);

NOTA: Se o array for um objeto
$data_via_array_map = array_map(function($item) use ($ArrayB) {
    if(in_array($item->mail, $ArrayB)) {
        return $item;
    }
}, $ArrayA);

A: No seu caso, você pode desenvolver um laço de repetição que percorra o seu arrayB, e para cada índice do mesmo, ele fará a consulta para saber se o mesmo existe no arrayA, se existir... Você pode também acrescentar uma posição ao arrayC já setando o valor.
Tente seguir as especificações abaixo e espero que encontre solução para sua dúvida!
Para solucionar seu problema basta realizar um laço de repetição que percorra seu arrayB item a item (Que é o array que contém os dados que você vai validar). Após esse for estar montado, esse valor selecionado vai percorrer todo o arrayA em busca de um match no e-mail. Portanto, criei outro for, que vai percorrer todo o arrayA.
Então, o primeiro for se inicia e entramos no segundo for, pegando o valor do indice e procurando posição à posição do arrayA, se encontrarmos, atribuimos esse valor ao arrayC e posteriormente damos continuidade ao primeiro for, se não encontrarmos damos continuidade diretamente.
Usei sua própria estrutura para ficar de fácil entendimento.
Não sei se expliquei claramente, mas o exemplo vai funcionar na sua máquina, só testar aí!
Precisando estou por aqui!
Segue o exemplo abaixo:
    <?php

    $arrayA = [
    [
        'id'      => '5c4fa45sdfsd546',
        'name'    => 'Fulano',
        'surname' => 'de Tal',
        'mail'    => 'fulano@gmail.com',
        'phone'   => '(11) 91234-5678',
        'enable'  => true,
    ],
    [
        'id'      => '5cd2ef021930f40f6455ad1e',
        'name'    => 'Beltrano',
        'surname' => 'de Tal',
        'mail'    => 'beltrano@live.com',
        'phone'   => '(11) 99876-5432',
        'enable'  => false,
    ],
    [
        'id'      => '5cd8s9df89000sdf6455ad1e',
        'name'    => 'Cilano',
        'surname' => 'de Tal',
        'mail'    => 'cilano@live.com',
        'phone'   => '(12) 99876-5432',
        'enable'  => true,
    ],
    [
        'id'      => '5cd8s9df89000sdf6455ad1e',
        'name'    => 'Cilano',
        'surname' => 'de Tal',
        'mail'    => 'foo@live.com',
        'phone'   => '(12) 99876-5432',
        'enable'  => true,
    ]
    ];

    $arrayB = ['cilano@live.com', 'foo.com'];
    $arrayC = [];

   for($i = 0; $i < sizeof($arrayB); $i++){
        for($b = 0; $b < sizeof($arrayA); $b++){
            if($arrayB[$i] == $arrayA[$b]['mail']){
                $arrayC[$i] = $arrayB[$i];
            }
        }
   }

   for($a = 0; $a < sizeof($arrayC); $a++){
       echo $arrayC[$a] . '<br>';
   }

?>


text:
Q: "disabled for fips" error getting thrown when trying to execute a js file with the "--force-fips" flag I see the following error get thrown when trying to run node with the --force-fips flag:
Error: disabled for fips
    at Object.createSecureContext (_tls_common.js:158:19)
    at Server (_tls_wrap.js:803:25)
    at new Server (https.js:54:14)
    at Object.createServer (https.js:76:10)
    at Object.module.exports.startServer

Following the stack-trace, I was able to figure out that the error get thrown when the "loadPKCS12" method gets executed. (I am passing a keystore to the "pfx" parameter along with the keystore password corresponding to the "passphrase" parameter as part of the options object when bringing up the "https" server instance).
The method definition is in c++ and I am finding it hard to debug the issue. What could the issue be? Could it be an issue with the keystore that I am passing?
I am making use of node v8.9.4 and I am trying this out on a centos machine (centos-release-7-4.1708.el7.centos.x86_64 to be specific)

A: It seemed to be an issue with the certificate that I was making use of. The certificate was encrypted using an algorithm which was fips in-compliant (40-bit RC2). Generating the certificate (using openssl) by passing in the -descert argument fixed the issue for me (Passing in the descert argument while generating the certificate encrypts the certificate using Triple DES which is fips compliant).
Reference: https://community.rsa.com/docs/DOC-51951


text:
Q: App rejected, insert valid contact information Play console reject my aggregation news app. I get posts link by some RSS feed.
After submitted app Google response to me with a rejection for:

*

*Does not contain a website or in-app page that provides valid contact information for the news publisher

Google is not clear, this is the email i have receved:
Issue image
and this is the attached screenshot
What contact information must I insert? Can I have some example?

A: I resolve this problem, adding a new page with link to about page of all my RSS feed.

A: Maybe u need to add some sort of privacy policy or user agreements inti your app and play developer console.